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/MemoryBuffer.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmParser.h"
39 /// \brief Helper class for tracking macro definitions.
45 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
48 /// \brief Helper class for storing information about an active macro
50 struct MacroInstantiation {
51 /// The macro being instantiated.
52 const Macro *TheMacro;
54 /// The macro instantiation with substitutions.
55 MemoryBuffer *Instantiation;
57 /// The location of the instantiation.
58 SMLoc InstantiationLoc;
60 /// The location where parsing should resume upon instantiation completion.
64 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
65 const std::vector<std::vector<AsmToken> > &A);
68 /// \brief The concrete assembly parser instance.
69 class AsmParser : public MCAsmParser {
70 friend class GenericAsmParser;
72 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
73 void operator=(const AsmParser &); // DO NOT IMPLEMENT
79 MCAsmParserExtension *GenericParser;
80 MCAsmParserExtension *PlatformParser;
82 /// This is the current buffer index we're lexing from as managed by the
87 std::vector<AsmCond> TheCondStack;
89 /// DirectiveMap - This is a table handlers for directives. Each handler is
90 /// invoked after the directive identifier is read and is responsible for
91 /// parsing and validating the rest of the directive. The handler is passed
92 /// in the directive name and the location of the directive keyword.
93 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
95 /// MacroMap - Map of currently defined macros.
96 StringMap<Macro*> MacroMap;
98 /// ActiveMacros - Stack of active macro instantiations.
99 std::vector<MacroInstantiation*> ActiveMacros;
101 /// Boolean tracking whether macro substitution is enabled.
102 unsigned MacrosEnabled : 1;
104 /// Flag tracking whether any errors have been encountered.
105 unsigned HadError : 1;
108 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
109 const MCAsmInfo &MAI);
112 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
114 void AddDirectiveHandler(MCAsmParserExtension *Object,
116 DirectiveHandler Handler) {
117 DirectiveMap[Directive] = std::make_pair(Object, Handler);
121 /// @name MCAsmParser Interface
124 virtual SourceMgr &getSourceManager() { return SrcMgr; }
125 virtual MCAsmLexer &getLexer() { return Lexer; }
126 virtual MCContext &getContext() { return Ctx; }
127 virtual MCStreamer &getStreamer() { return Out; }
129 virtual void Warning(SMLoc L, const Twine &Meg);
130 virtual bool Error(SMLoc L, const Twine &Msg);
132 const AsmToken &Lex();
134 bool ParseExpression(const MCExpr *&Res);
135 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
136 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
137 virtual bool ParseAbsoluteExpression(int64_t &Res);
142 void CheckForValidSection();
144 bool ParseStatement();
146 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
147 void HandleMacroExit();
149 void PrintMacroInstantiations();
150 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
151 SrcMgr.PrintMessage(Loc, Msg, Type);
154 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
155 bool EnterIncludeFile(const std::string &Filename);
157 /// \brief Reset the current lexer position to that given by \arg Loc. The
158 /// current token is not set; clients should ensure Lex() is called
160 void JumpToLoc(SMLoc Loc);
162 void EatToEndOfStatement();
164 /// \brief Parse up to the end of statement and a return the contents from the
165 /// current token until the end of the statement; the current token on exit
166 /// will be either the EndOfStatement or EOF.
167 StringRef ParseStringToEndOfStatement();
169 bool ParseAssignment(StringRef Name);
171 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
172 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
173 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
175 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
176 /// and set \arg Res to the identifier contents.
177 bool ParseIdentifier(StringRef &Res);
179 // Directive Parsing.
180 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
181 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
182 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
183 bool ParseDirectiveFill(); // ".fill"
184 bool ParseDirectiveSpace(); // ".space"
185 bool ParseDirectiveZero(); // ".zero"
186 bool ParseDirectiveSet(StringRef IDVal); // ".set" or ".equ"
187 bool ParseDirectiveOrg(); // ".org"
188 // ".align{,32}", ".p2align{,w,l}"
189 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
191 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
192 /// accepts a single symbol (which should be a label or an external).
193 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
194 bool ParseDirectiveELFType(); // ELF specific ".type"
196 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
198 bool ParseDirectiveAbort(); // ".abort"
199 bool ParseDirectiveInclude(); // ".include"
201 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
202 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
203 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
204 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
206 /// ParseEscapedString - Parse the current token as a string which may include
207 /// escaped characters and return the string contents.
208 bool ParseEscapedString(std::string &Data);
210 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
211 MCSymbolRefExpr::VariantKind Variant);
214 /// \brief Generic implementations of directive handling, etc. which is shared
215 /// (or the default, at least) for all assembler parser.
216 class GenericAsmParser : public MCAsmParserExtension {
217 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
218 void AddDirectiveHandler(StringRef Directive) {
219 getParser().AddDirectiveHandler(this, Directive,
220 HandleDirective<GenericAsmParser, Handler>);
224 GenericAsmParser() {}
226 AsmParser &getParser() {
227 return (AsmParser&) this->MCAsmParserExtension::getParser();
230 virtual void Initialize(MCAsmParser &Parser) {
231 // Call the base implementation.
232 this->MCAsmParserExtension::Initialize(Parser);
234 // Debugging directives.
235 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
236 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
237 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
238 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
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);
256 bool ParseDirectiveStabs(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();
273 extern MCAsmParserExtension *createCOFFAsmParser();
277 enum { DEFAULT_ADDRSPACE = 0 };
279 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
280 MCStreamer &_Out, const MCAsmInfo &_MAI)
281 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
282 GenericParser(new GenericAsmParser), PlatformParser(0),
283 CurBuffer(0), MacrosEnabled(true) {
284 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
286 // Initialize the generic parser.
287 GenericParser->Initialize(*this);
289 // Initialize the platform / file format parser.
291 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
293 if (_MAI.hasMicrosoftFastStdCallMangling()) {
294 PlatformParser = createCOFFAsmParser();
295 PlatformParser->Initialize(*this);
296 } else if (_MAI.hasSubsectionsViaSymbols()) {
297 PlatformParser = createDarwinAsmParser();
298 PlatformParser->Initialize(*this);
300 PlatformParser = createELFAsmParser();
301 PlatformParser->Initialize(*this);
305 AsmParser::~AsmParser() {
306 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
308 // Destroy any macros.
309 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
310 ie = MacroMap.end(); it != ie; ++it)
311 delete it->getValue();
313 delete PlatformParser;
314 delete GenericParser;
317 void AsmParser::PrintMacroInstantiations() {
318 // Print the active macro instantiation stack.
319 for (std::vector<MacroInstantiation*>::const_reverse_iterator
320 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
321 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
325 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
326 PrintMessage(L, Msg, "warning");
327 PrintMacroInstantiations();
330 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
332 PrintMessage(L, Msg, "error");
333 PrintMacroInstantiations();
337 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
338 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
344 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
349 void AsmParser::JumpToLoc(SMLoc Loc) {
350 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
351 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
354 const AsmToken &AsmParser::Lex() {
355 const AsmToken *tok = &Lexer.Lex();
357 if (tok->is(AsmToken::Eof)) {
358 // If this is the end of an included file, pop the parent file off the
360 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
361 if (ParentIncludeLoc != SMLoc()) {
362 JumpToLoc(ParentIncludeLoc);
367 if (tok->is(AsmToken::Error))
368 Error(Lexer.getErrLoc(), Lexer.getErr());
373 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
374 // Create the initial section, if requested.
375 if (!NoInitialTextSection)
382 AsmCond StartingCondState = TheCondState;
384 // While we have input, parse each statement.
385 while (Lexer.isNot(AsmToken::Eof)) {
386 if (!ParseStatement()) continue;
388 // We had an error, validate that one was emitted and recover by skipping to
390 assert(HadError && "Parse statement returned an error, but none emitted!");
391 EatToEndOfStatement();
394 if (TheCondState.TheCond != StartingCondState.TheCond ||
395 TheCondState.Ignore != StartingCondState.Ignore)
396 return TokError("unmatched .ifs or .elses");
398 // Check to see there are no empty DwarfFile slots.
399 const std::vector<MCDwarfFile *> &MCDwarfFiles =
400 getContext().getMCDwarfFiles();
401 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
402 if (!MCDwarfFiles[i])
403 TokError("unassigned file number: " + Twine(i) + " for .file directives");
406 // Finalize the output stream if there are no errors and if the client wants
408 if (!HadError && !NoFinalize)
414 void AsmParser::CheckForValidSection() {
415 if (!getStreamer().getCurrentSection()) {
416 TokError("expected section directive before assembly directive");
417 Out.SwitchSection(Ctx.getMachOSection(
419 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
420 0, SectionKind::getText()));
424 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
425 void AsmParser::EatToEndOfStatement() {
426 while (Lexer.isNot(AsmToken::EndOfStatement) &&
427 Lexer.isNot(AsmToken::Eof))
431 if (Lexer.is(AsmToken::EndOfStatement))
435 StringRef AsmParser::ParseStringToEndOfStatement() {
436 const char *Start = getTok().getLoc().getPointer();
438 while (Lexer.isNot(AsmToken::EndOfStatement) &&
439 Lexer.isNot(AsmToken::Eof))
442 const char *End = getTok().getLoc().getPointer();
443 return StringRef(Start, End - Start);
446 /// ParseParenExpr - Parse a paren expression and return it.
447 /// NOTE: This assumes the leading '(' has already been consumed.
449 /// parenexpr ::= expr)
451 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
452 if (ParseExpression(Res)) return true;
453 if (Lexer.isNot(AsmToken::RParen))
454 return TokError("expected ')' in parentheses expression");
455 EndLoc = Lexer.getLoc();
460 /// ParsePrimaryExpr - Parse a primary expression and return it.
461 /// primaryexpr ::= (parenexpr
462 /// primaryexpr ::= symbol
463 /// primaryexpr ::= number
464 /// primaryexpr ::= '.'
465 /// primaryexpr ::= ~,+,- primaryexpr
466 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
467 switch (Lexer.getKind()) {
469 return TokError("unknown token in expression");
470 case AsmToken::Exclaim:
471 Lex(); // Eat the operator.
472 if (ParsePrimaryExpr(Res, EndLoc))
474 Res = MCUnaryExpr::CreateLNot(Res, getContext());
476 case AsmToken::Dollar:
477 case AsmToken::String:
478 case AsmToken::Identifier: {
479 EndLoc = Lexer.getLoc();
481 StringRef Identifier;
482 if (ParseIdentifier(Identifier))
485 // This is a symbol reference.
486 std::pair<StringRef, StringRef> Split = Identifier.split('@');
487 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
489 // Mark the symbol as used in an expression.
490 Sym->setUsedInExpr(true);
492 // Lookup the symbol variant if used.
493 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
494 if (Split.first.size() != Identifier.size()) {
495 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
496 if (Variant == MCSymbolRefExpr::VK_Invalid) {
497 Variant = MCSymbolRefExpr::VK_None;
498 TokError("invalid variant '" + Split.second + "'");
502 // If this is an absolute variable reference, substitute it now to preserve
503 // semantics in the face of reassignment.
504 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
506 return Error(EndLoc, "unexpected modified on variable reference");
508 Res = Sym->getVariableValue();
512 // Otherwise create a symbol ref.
513 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
516 case AsmToken::Integer: {
517 SMLoc Loc = getTok().getLoc();
518 int64_t IntVal = getTok().getIntVal();
519 Res = MCConstantExpr::Create(IntVal, getContext());
520 EndLoc = Lexer.getLoc();
522 // Look for 'b' or 'f' following an Integer as a directional label
523 if (Lexer.getKind() == AsmToken::Identifier) {
524 StringRef IDVal = getTok().getString();
525 if (IDVal == "f" || IDVal == "b"){
526 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
527 IDVal == "f" ? 1 : 0);
528 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
530 if(IDVal == "b" && Sym->isUndefined())
531 return Error(Loc, "invalid reference to undefined symbol");
532 EndLoc = Lexer.getLoc();
533 Lex(); // Eat identifier.
538 case AsmToken::Dot: {
539 // This is a '.' reference, which references the current PC. Emit a
540 // temporary label to the streamer and refer to it.
541 MCSymbol *Sym = Ctx.CreateTempSymbol();
543 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
544 EndLoc = Lexer.getLoc();
545 Lex(); // Eat identifier.
549 case AsmToken::LParen:
550 Lex(); // Eat the '('.
551 return ParseParenExpr(Res, EndLoc);
552 case AsmToken::Minus:
553 Lex(); // Eat the operator.
554 if (ParsePrimaryExpr(Res, EndLoc))
556 Res = MCUnaryExpr::CreateMinus(Res, getContext());
559 Lex(); // Eat the operator.
560 if (ParsePrimaryExpr(Res, EndLoc))
562 Res = MCUnaryExpr::CreatePlus(Res, getContext());
564 case AsmToken::Tilde:
565 Lex(); // Eat the operator.
566 if (ParsePrimaryExpr(Res, EndLoc))
568 Res = MCUnaryExpr::CreateNot(Res, getContext());
573 bool AsmParser::ParseExpression(const MCExpr *&Res) {
575 return ParseExpression(Res, EndLoc);
579 AsmParser::ApplyModifierToExpr(const MCExpr *E,
580 MCSymbolRefExpr::VariantKind Variant) {
581 // Recurse over the given expression, rebuilding it to apply the given variant
582 // if there is exactly one symbol.
583 switch (E->getKind()) {
585 case MCExpr::Constant:
588 case MCExpr::SymbolRef: {
589 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
591 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
592 TokError("invalid variant on expression '" +
593 getTok().getIdentifier() + "' (already modified)");
597 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
600 case MCExpr::Unary: {
601 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
602 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
605 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
608 case MCExpr::Binary: {
609 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
610 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
611 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
616 if (!LHS) LHS = BE->getLHS();
617 if (!RHS) RHS = BE->getRHS();
619 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
623 assert(0 && "Invalid expression kind!");
627 /// ParseExpression - Parse an expression and return it.
629 /// expr ::= expr +,- expr -> lowest.
630 /// expr ::= expr |,^,&,! expr -> middle.
631 /// expr ::= expr *,/,%,<<,>> expr -> highest.
632 /// expr ::= primaryexpr
634 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
635 // Parse the expression.
637 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
640 // As a special case, we support 'a op b @ modifier' by rewriting the
641 // expression to include the modifier. This is inefficient, but in general we
642 // expect users to use 'a@modifier op b'.
643 if (Lexer.getKind() == AsmToken::At) {
646 if (Lexer.isNot(AsmToken::Identifier))
647 return TokError("unexpected symbol modifier following '@'");
649 MCSymbolRefExpr::VariantKind Variant =
650 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
651 if (Variant == MCSymbolRefExpr::VK_Invalid)
652 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
654 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
656 return TokError("invalid modifier '" + getTok().getIdentifier() +
657 "' (no symbols present)");
665 // Try to constant fold it up front, if possible.
667 if (Res->EvaluateAsAbsolute(Value))
668 Res = MCConstantExpr::Create(Value, getContext());
673 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
675 return ParseParenExpr(Res, EndLoc) ||
676 ParseBinOpRHS(1, Res, EndLoc);
679 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
682 SMLoc StartLoc = Lexer.getLoc();
683 if (ParseExpression(Expr))
686 if (!Expr->EvaluateAsAbsolute(Res))
687 return Error(StartLoc, "expected absolute expression");
692 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
693 MCBinaryExpr::Opcode &Kind) {
696 return 0; // not a binop.
698 // Lowest Precedence: &&, ||, @
699 case AsmToken::AmpAmp:
700 Kind = MCBinaryExpr::LAnd;
702 case AsmToken::PipePipe:
703 Kind = MCBinaryExpr::LOr;
707 // Low Precedence: |, &, ^
709 // FIXME: gas seems to support '!' as an infix operator?
711 Kind = MCBinaryExpr::Or;
713 case AsmToken::Caret:
714 Kind = MCBinaryExpr::Xor;
717 Kind = MCBinaryExpr::And;
720 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
721 case AsmToken::EqualEqual:
722 Kind = MCBinaryExpr::EQ;
724 case AsmToken::ExclaimEqual:
725 case AsmToken::LessGreater:
726 Kind = MCBinaryExpr::NE;
729 Kind = MCBinaryExpr::LT;
731 case AsmToken::LessEqual:
732 Kind = MCBinaryExpr::LTE;
734 case AsmToken::Greater:
735 Kind = MCBinaryExpr::GT;
737 case AsmToken::GreaterEqual:
738 Kind = MCBinaryExpr::GTE;
741 // High Intermediate Precedence: +, -
743 Kind = MCBinaryExpr::Add;
745 case AsmToken::Minus:
746 Kind = MCBinaryExpr::Sub;
749 // Highest Precedence: *, /, %, <<, >>
751 Kind = MCBinaryExpr::Mul;
753 case AsmToken::Slash:
754 Kind = MCBinaryExpr::Div;
756 case AsmToken::Percent:
757 Kind = MCBinaryExpr::Mod;
759 case AsmToken::LessLess:
760 Kind = MCBinaryExpr::Shl;
762 case AsmToken::GreaterGreater:
763 Kind = MCBinaryExpr::Shr;
769 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
770 /// Res contains the LHS of the expression on input.
771 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
774 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
775 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
777 // If the next token is lower precedence than we are allowed to eat, return
778 // successfully with what we ate already.
779 if (TokPrec < Precedence)
784 // Eat the next primary expression.
786 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
788 // If BinOp binds less tightly with RHS than the operator after RHS, let
789 // the pending operator take RHS as its LHS.
790 MCBinaryExpr::Opcode Dummy;
791 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
792 if (TokPrec < NextTokPrec) {
793 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
796 // Merge LHS and RHS according to operator.
797 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
805 /// ::= EndOfStatement
806 /// ::= Label* Directive ...Operands... EndOfStatement
807 /// ::= Label* Identifier OperandList* EndOfStatement
808 bool AsmParser::ParseStatement() {
809 if (Lexer.is(AsmToken::EndOfStatement)) {
815 // Statements always start with an identifier.
816 AsmToken ID = getTok();
817 SMLoc IDLoc = ID.getLoc();
819 int64_t LocalLabelVal = -1;
820 // GUESS allow an integer followed by a ':' as a directional local label
821 if (Lexer.is(AsmToken::Integer)) {
822 LocalLabelVal = getTok().getIntVal();
823 if (LocalLabelVal < 0) {
824 if (!TheCondState.Ignore)
825 return TokError("unexpected token at start of statement");
829 IDVal = getTok().getString();
830 Lex(); // Consume the integer token to be used as an identifier token.
831 if (Lexer.getKind() != AsmToken::Colon) {
832 if (!TheCondState.Ignore)
833 return TokError("unexpected token at start of statement");
837 else if (ParseIdentifier(IDVal)) {
838 if (!TheCondState.Ignore)
839 return TokError("unexpected token at start of statement");
843 // Handle conditional assembly here before checking for skipping. We
844 // have to do this so that .endif isn't skipped in a ".if 0" block for
847 return ParseDirectiveIf(IDLoc);
848 if (IDVal == ".elseif")
849 return ParseDirectiveElseIf(IDLoc);
850 if (IDVal == ".else")
851 return ParseDirectiveElse(IDLoc);
852 if (IDVal == ".endif")
853 return ParseDirectiveEndIf(IDLoc);
855 // If we are in a ".if 0" block, ignore this statement.
856 if (TheCondState.Ignore) {
857 EatToEndOfStatement();
861 // FIXME: Recurse on local labels?
863 // See what kind of statement we have.
864 switch (Lexer.getKind()) {
865 case AsmToken::Colon: {
866 CheckForValidSection();
868 // identifier ':' -> Label.
871 // Diagnose attempt to use a variable as a label.
873 // FIXME: Diagnostics. Note the location of the definition as a label.
874 // FIXME: This doesn't diagnose assignment to a symbol which has been
875 // implicitly marked as external.
877 if (LocalLabelVal == -1)
878 Sym = getContext().GetOrCreateSymbol(IDVal);
880 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
881 if (!Sym->isUndefined() || Sym->isVariable())
882 return Error(IDLoc, "invalid symbol redefinition");
887 // Consume any end of statement token, if present, to avoid spurious
888 // AddBlankLine calls().
889 if (Lexer.is(AsmToken::EndOfStatement)) {
891 if (Lexer.is(AsmToken::Eof))
895 return ParseStatement();
898 case AsmToken::Equal:
899 // identifier '=' ... -> assignment statement
902 return ParseAssignment(IDVal);
904 default: // Normal instruction or directive.
908 // If macros are enabled, check to see if this is a macro instantiation.
910 if (const Macro *M = MacroMap.lookup(IDVal))
911 return HandleMacroEntry(IDVal, IDLoc, M);
913 // Otherwise, we have a normal instruction or directive.
914 if (IDVal[0] == '.') {
915 // Assembler features
916 if (IDVal == ".set" || IDVal == ".equ")
917 return ParseDirectiveSet(IDVal);
921 if (IDVal == ".ascii")
922 return ParseDirectiveAscii(false);
923 if (IDVal == ".asciz")
924 return ParseDirectiveAscii(true);
926 if (IDVal == ".byte")
927 return ParseDirectiveValue(1);
928 if (IDVal == ".short")
929 return ParseDirectiveValue(2);
930 if (IDVal == ".long")
931 return ParseDirectiveValue(4);
932 if (IDVal == ".quad")
933 return ParseDirectiveValue(8);
934 if (IDVal == ".single")
935 return ParseDirectiveRealValue(APFloat::IEEEsingle);
936 if (IDVal == ".double")
937 return ParseDirectiveRealValue(APFloat::IEEEdouble);
939 if (IDVal == ".align") {
940 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
941 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
943 if (IDVal == ".align32") {
944 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
945 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
947 if (IDVal == ".balign")
948 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
949 if (IDVal == ".balignw")
950 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
951 if (IDVal == ".balignl")
952 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
953 if (IDVal == ".p2align")
954 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
955 if (IDVal == ".p2alignw")
956 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
957 if (IDVal == ".p2alignl")
958 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
961 return ParseDirectiveOrg();
963 if (IDVal == ".fill")
964 return ParseDirectiveFill();
965 if (IDVal == ".space")
966 return ParseDirectiveSpace();
967 if (IDVal == ".zero")
968 return ParseDirectiveZero();
970 // Symbol attribute directives
972 if (IDVal == ".globl" || IDVal == ".global")
973 return ParseDirectiveSymbolAttribute(MCSA_Global);
974 // ELF only? Should it be here?
975 if (IDVal == ".local")
976 return ParseDirectiveSymbolAttribute(MCSA_Local);
977 if (IDVal == ".hidden")
978 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
979 if (IDVal == ".indirect_symbol")
980 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
981 if (IDVal == ".internal")
982 return ParseDirectiveSymbolAttribute(MCSA_Internal);
983 if (IDVal == ".lazy_reference")
984 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
985 if (IDVal == ".no_dead_strip")
986 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
987 if (IDVal == ".private_extern")
988 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
989 if (IDVal == ".protected")
990 return ParseDirectiveSymbolAttribute(MCSA_Protected);
991 if (IDVal == ".reference")
992 return ParseDirectiveSymbolAttribute(MCSA_Reference);
993 if (IDVal == ".weak")
994 return ParseDirectiveSymbolAttribute(MCSA_Weak);
995 if (IDVal == ".weak_definition")
996 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
997 if (IDVal == ".weak_reference")
998 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
999 if (IDVal == ".weak_def_can_be_hidden")
1000 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1002 if (IDVal == ".comm")
1003 return ParseDirectiveComm(/*IsLocal=*/false);
1004 if (IDVal == ".lcomm")
1005 return ParseDirectiveComm(/*IsLocal=*/true);
1007 if (IDVal == ".abort")
1008 return ParseDirectiveAbort();
1009 if (IDVal == ".include")
1010 return ParseDirectiveInclude();
1012 // Look up the handler in the handler table.
1013 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1014 DirectiveMap.lookup(IDVal);
1016 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1018 // Target hook for parsing target specific directives.
1019 if (!getTargetParser().ParseDirective(ID))
1022 Warning(IDLoc, "ignoring directive for now");
1023 EatToEndOfStatement();
1027 CheckForValidSection();
1029 // Canonicalize the opcode to lower case.
1030 SmallString<128> Opcode;
1031 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1032 Opcode.push_back(tolower(IDVal[i]));
1034 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1035 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1038 // Dump the parsed representation, if requested.
1039 if (getShowParsedOperands()) {
1040 SmallString<256> Str;
1041 raw_svector_ostream OS(Str);
1042 OS << "parsed instruction: [";
1043 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1046 ParsedOperands[i]->dump(OS);
1050 PrintMessage(IDLoc, OS.str(), "note");
1053 // If parsing succeeded, match the instruction.
1055 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1058 // Free any parsed operands.
1059 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1060 delete ParsedOperands[i];
1062 // Don't skip the rest of the line, the instruction parser is responsible for
1067 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1068 const std::vector<std::vector<AsmToken> > &A)
1069 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1071 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1072 // to hold the macro body with substitutions.
1073 SmallString<256> Buf;
1074 raw_svector_ostream OS(Buf);
1076 StringRef Body = M->Body;
1077 while (!Body.empty()) {
1078 // Scan for the next substitution.
1079 std::size_t End = Body.size(), Pos = 0;
1080 for (; Pos != End; ++Pos) {
1081 // Check for a substitution or escape.
1082 if (Body[Pos] != '$' || Pos + 1 == End)
1085 char Next = Body[Pos + 1];
1086 if (Next == '$' || Next == 'n' || isdigit(Next))
1091 OS << Body.slice(0, Pos);
1093 // Check if we reached the end.
1097 switch (Body[Pos+1]) {
1103 // $n => number of arguments
1108 // $[0-9] => argument
1110 // Missing arguments are ignored.
1111 unsigned Index = Body[Pos+1] - '0';
1112 if (Index >= A.size())
1115 // Otherwise substitute with the token values, with spaces eliminated.
1116 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1117 ie = A[Index].end(); it != ie; ++it)
1118 OS << it->getString();
1123 // Update the scan point.
1124 Body = Body.substr(Pos + 2);
1127 // We include the .endmacro in the buffer as our queue to exit the macro
1129 OS << ".endmacro\n";
1131 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1134 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1136 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1137 // this, although we should protect against infinite loops.
1138 if (ActiveMacros.size() == 20)
1139 return TokError("macros cannot be nested more than 20 levels deep");
1141 // Parse the macro instantiation arguments.
1142 std::vector<std::vector<AsmToken> > MacroArguments;
1143 MacroArguments.push_back(std::vector<AsmToken>());
1144 unsigned ParenLevel = 0;
1146 if (Lexer.is(AsmToken::Eof))
1147 return TokError("unexpected token in macro instantiation");
1148 if (Lexer.is(AsmToken::EndOfStatement))
1151 // If we aren't inside parentheses and this is a comma, start a new token
1153 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1154 MacroArguments.push_back(std::vector<AsmToken>());
1156 // Adjust the current parentheses level.
1157 if (Lexer.is(AsmToken::LParen))
1159 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1162 // Append the token to the current argument list.
1163 MacroArguments.back().push_back(getTok());
1168 // Create the macro instantiation object and add to the current macro
1169 // instantiation stack.
1170 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1173 ActiveMacros.push_back(MI);
1175 // Jump to the macro instantiation and prime the lexer.
1176 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1177 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1183 void AsmParser::HandleMacroExit() {
1184 // Jump to the EndOfStatement we should return to, and consume it.
1185 JumpToLoc(ActiveMacros.back()->ExitLoc);
1188 // Pop the instantiation entry.
1189 delete ActiveMacros.back();
1190 ActiveMacros.pop_back();
1193 bool AsmParser::ParseAssignment(StringRef Name) {
1194 // FIXME: Use better location, we should use proper tokens.
1195 SMLoc EqualLoc = Lexer.getLoc();
1197 const MCExpr *Value;
1198 if (ParseExpression(Value))
1201 if (Lexer.isNot(AsmToken::EndOfStatement))
1202 return TokError("unexpected token in assignment");
1204 // Eat the end of statement marker.
1207 // Validate that the LHS is allowed to be a variable (either it has not been
1208 // used as a symbol, or it is an absolute symbol).
1209 MCSymbol *Sym = getContext().LookupSymbol(Name);
1211 // Diagnose assignment to a label.
1213 // FIXME: Diagnostics. Note the location of the definition as a label.
1214 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1215 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1216 ; // Allow redefinitions of undefined symbols only used in directives.
1217 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1218 return Error(EqualLoc, "redefinition of '" + Name + "'");
1219 else if (!Sym->isVariable())
1220 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1221 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1222 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1225 Sym = getContext().GetOrCreateSymbol(Name);
1227 // FIXME: Handle '.'.
1229 Sym->setUsedInExpr(true);
1231 // Do the assignment.
1232 Out.EmitAssignment(Sym, Value);
1237 /// ParseIdentifier:
1240 bool AsmParser::ParseIdentifier(StringRef &Res) {
1241 // The assembler has relaxed rules for accepting identifiers, in particular we
1242 // allow things like '.globl $foo', which would normally be separate
1243 // tokens. At this level, we have already lexed so we cannot (currently)
1244 // handle this as a context dependent token, instead we detect adjacent tokens
1245 // and return the combined identifier.
1246 if (Lexer.is(AsmToken::Dollar)) {
1247 SMLoc DollarLoc = getLexer().getLoc();
1249 // Consume the dollar sign, and check for a following identifier.
1251 if (Lexer.isNot(AsmToken::Identifier))
1254 // We have a '$' followed by an identifier, make sure they are adjacent.
1255 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1258 // Construct the joined identifier and consume the token.
1259 Res = StringRef(DollarLoc.getPointer(),
1260 getTok().getIdentifier().size() + 1);
1265 if (Lexer.isNot(AsmToken::Identifier) &&
1266 Lexer.isNot(AsmToken::String))
1269 Res = getTok().getIdentifier();
1271 Lex(); // Consume the identifier token.
1276 /// ParseDirectiveSet:
1277 /// ::= .set identifier ',' expression
1278 bool AsmParser::ParseDirectiveSet(StringRef IDVal) {
1281 if (ParseIdentifier(Name))
1282 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1284 if (getLexer().isNot(AsmToken::Comma))
1285 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1288 return ParseAssignment(Name);
1291 bool AsmParser::ParseEscapedString(std::string &Data) {
1292 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1295 StringRef Str = getTok().getStringContents();
1296 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1297 if (Str[i] != '\\') {
1302 // Recognize escaped characters. Note that this escape semantics currently
1303 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1306 return TokError("unexpected backslash at end of string");
1308 // Recognize octal sequences.
1309 if ((unsigned) (Str[i] - '0') <= 7) {
1310 // Consume up to three octal characters.
1311 unsigned Value = Str[i] - '0';
1313 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1315 Value = Value * 8 + (Str[i] - '0');
1317 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1319 Value = Value * 8 + (Str[i] - '0');
1324 return TokError("invalid octal escape sequence (out of range)");
1326 Data += (unsigned char) Value;
1330 // Otherwise recognize individual escapes.
1333 // Just reject invalid escape sequences for now.
1334 return TokError("invalid escape sequence (unrecognized character)");
1336 case 'b': Data += '\b'; break;
1337 case 'f': Data += '\f'; break;
1338 case 'n': Data += '\n'; break;
1339 case 'r': Data += '\r'; break;
1340 case 't': Data += '\t'; break;
1341 case '"': Data += '"'; break;
1342 case '\\': Data += '\\'; break;
1349 /// ParseDirectiveAscii:
1350 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1351 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1352 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1353 CheckForValidSection();
1356 if (getLexer().isNot(AsmToken::String))
1357 return TokError("expected string in '.ascii' or '.asciz' directive");
1360 if (ParseEscapedString(Data))
1363 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1365 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1369 if (getLexer().is(AsmToken::EndOfStatement))
1372 if (getLexer().isNot(AsmToken::Comma))
1373 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1382 /// ParseDirectiveValue
1383 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1384 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1385 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1386 CheckForValidSection();
1389 const MCExpr *Value;
1390 if (ParseExpression(Value))
1393 // Special case constant expressions to match code generator.
1394 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1395 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1397 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1399 if (getLexer().is(AsmToken::EndOfStatement))
1402 // FIXME: Improve diagnostic.
1403 if (getLexer().isNot(AsmToken::Comma))
1404 return TokError("unexpected token in directive");
1413 /// ParseDirectiveRealValue
1414 /// ::= (.single | .double) [ expression (, expression)* ]
1415 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1416 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1417 CheckForValidSection();
1420 // We don't truly support arithmetic on floating point expressions, so we
1421 // have to manually parse unary prefixes.
1423 if (getLexer().is(AsmToken::Minus)) {
1426 } else if (getLexer().is(AsmToken::Plus))
1429 if (getLexer().isNot(AsmToken::Integer) &&
1430 getLexer().isNot(AsmToken::Real))
1431 return TokError("unexpected token in directive");
1433 // Convert to an APFloat.
1434 APFloat Value(Semantics);
1435 if (Value.convertFromString(getTok().getString(),
1436 APFloat::rmNearestTiesToEven) ==
1437 APFloat::opInvalidOp)
1438 return TokError("invalid floating point literal");
1442 // Consume the numeric token.
1445 // Emit the value as an integer.
1446 APInt AsInt = Value.bitcastToAPInt();
1447 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1448 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1450 if (getLexer().is(AsmToken::EndOfStatement))
1453 if (getLexer().isNot(AsmToken::Comma))
1454 return TokError("unexpected token in directive");
1463 /// ParseDirectiveSpace
1464 /// ::= .space expression [ , expression ]
1465 bool AsmParser::ParseDirectiveSpace() {
1466 CheckForValidSection();
1469 if (ParseAbsoluteExpression(NumBytes))
1472 int64_t FillExpr = 0;
1473 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1474 if (getLexer().isNot(AsmToken::Comma))
1475 return TokError("unexpected token in '.space' directive");
1478 if (ParseAbsoluteExpression(FillExpr))
1481 if (getLexer().isNot(AsmToken::EndOfStatement))
1482 return TokError("unexpected token in '.space' directive");
1488 return TokError("invalid number of bytes in '.space' directive");
1490 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1491 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1496 /// ParseDirectiveZero
1497 /// ::= .zero expression
1498 bool AsmParser::ParseDirectiveZero() {
1499 CheckForValidSection();
1502 if (ParseAbsoluteExpression(NumBytes))
1506 if (getLexer().is(AsmToken::Comma)) {
1508 if (ParseAbsoluteExpression(Val))
1512 if (getLexer().isNot(AsmToken::EndOfStatement))
1513 return TokError("unexpected token in '.zero' directive");
1517 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1522 /// ParseDirectiveFill
1523 /// ::= .fill expression , expression , expression
1524 bool AsmParser::ParseDirectiveFill() {
1525 CheckForValidSection();
1528 if (ParseAbsoluteExpression(NumValues))
1531 if (getLexer().isNot(AsmToken::Comma))
1532 return TokError("unexpected token in '.fill' directive");
1536 if (ParseAbsoluteExpression(FillSize))
1539 if (getLexer().isNot(AsmToken::Comma))
1540 return TokError("unexpected token in '.fill' directive");
1544 if (ParseAbsoluteExpression(FillExpr))
1547 if (getLexer().isNot(AsmToken::EndOfStatement))
1548 return TokError("unexpected token in '.fill' directive");
1552 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1553 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1555 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1556 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1561 /// ParseDirectiveOrg
1562 /// ::= .org expression [ , expression ]
1563 bool AsmParser::ParseDirectiveOrg() {
1564 CheckForValidSection();
1566 const MCExpr *Offset;
1567 if (ParseExpression(Offset))
1570 // Parse optional fill expression.
1571 int64_t FillExpr = 0;
1572 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1573 if (getLexer().isNot(AsmToken::Comma))
1574 return TokError("unexpected token in '.org' directive");
1577 if (ParseAbsoluteExpression(FillExpr))
1580 if (getLexer().isNot(AsmToken::EndOfStatement))
1581 return TokError("unexpected token in '.org' directive");
1586 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1587 // has to be relative to the current section.
1588 getStreamer().EmitValueToOffset(Offset, FillExpr);
1593 /// ParseDirectiveAlign
1594 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1595 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1596 CheckForValidSection();
1598 SMLoc AlignmentLoc = getLexer().getLoc();
1600 if (ParseAbsoluteExpression(Alignment))
1604 bool HasFillExpr = false;
1605 int64_t FillExpr = 0;
1606 int64_t MaxBytesToFill = 0;
1607 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1608 if (getLexer().isNot(AsmToken::Comma))
1609 return TokError("unexpected token in directive");
1612 // The fill expression can be omitted while specifying a maximum number of
1613 // alignment bytes, e.g:
1615 if (getLexer().isNot(AsmToken::Comma)) {
1617 if (ParseAbsoluteExpression(FillExpr))
1621 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1622 if (getLexer().isNot(AsmToken::Comma))
1623 return TokError("unexpected token in directive");
1626 MaxBytesLoc = getLexer().getLoc();
1627 if (ParseAbsoluteExpression(MaxBytesToFill))
1630 if (getLexer().isNot(AsmToken::EndOfStatement))
1631 return TokError("unexpected token in directive");
1640 // Compute alignment in bytes.
1642 // FIXME: Diagnose overflow.
1643 if (Alignment >= 32) {
1644 Error(AlignmentLoc, "invalid alignment value");
1648 Alignment = 1ULL << Alignment;
1651 // Diagnose non-sensical max bytes to align.
1652 if (MaxBytesLoc.isValid()) {
1653 if (MaxBytesToFill < 1) {
1654 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1655 "many bytes, ignoring maximum bytes expression");
1659 if (MaxBytesToFill >= Alignment) {
1660 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1666 // Check whether we should use optimal code alignment for this .align
1668 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
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 /// ParseDirectiveComm
1709 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1710 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1711 CheckForValidSection();
1713 SMLoc IDLoc = getLexer().getLoc();
1715 if (ParseIdentifier(Name))
1716 return TokError("expected identifier in directive");
1718 // Handle the identifier as the key symbol.
1719 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1721 if (getLexer().isNot(AsmToken::Comma))
1722 return TokError("unexpected token in directive");
1726 SMLoc SizeLoc = getLexer().getLoc();
1727 if (ParseAbsoluteExpression(Size))
1730 int64_t Pow2Alignment = 0;
1731 SMLoc Pow2AlignmentLoc;
1732 if (getLexer().is(AsmToken::Comma)) {
1734 Pow2AlignmentLoc = getLexer().getLoc();
1735 if (ParseAbsoluteExpression(Pow2Alignment))
1738 // If this target takes alignments in bytes (not log) validate and convert.
1739 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1740 if (!isPowerOf2_64(Pow2Alignment))
1741 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1742 Pow2Alignment = Log2_64(Pow2Alignment);
1746 if (getLexer().isNot(AsmToken::EndOfStatement))
1747 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1751 // NOTE: a size of zero for a .comm should create a undefined symbol
1752 // but a size of .lcomm creates a bss symbol of size zero.
1754 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1755 "be less than zero");
1757 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1758 // may internally end up wanting an alignment in bytes.
1759 // FIXME: Diagnose overflow.
1760 if (Pow2Alignment < 0)
1761 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1762 "alignment, can't be less than zero");
1764 if (!Sym->isUndefined())
1765 return Error(IDLoc, "invalid symbol redefinition");
1767 // '.lcomm' is equivalent to '.zerofill'.
1768 // Create the Symbol as a common or local common with Size and Pow2Alignment
1770 getStreamer().EmitZerofill(Ctx.getMachOSection(
1771 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1772 0, SectionKind::getBSS()),
1773 Sym, Size, 1 << Pow2Alignment);
1777 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1781 /// ParseDirectiveAbort
1782 /// ::= .abort [... message ...]
1783 bool AsmParser::ParseDirectiveAbort() {
1784 // FIXME: Use loc from directive.
1785 SMLoc Loc = getLexer().getLoc();
1787 StringRef Str = ParseStringToEndOfStatement();
1788 if (getLexer().isNot(AsmToken::EndOfStatement))
1789 return TokError("unexpected token in '.abort' directive");
1794 Error(Loc, ".abort detected. Assembly stopping.");
1796 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1797 // FIXME: Actually abort assembly here.
1802 /// ParseDirectiveInclude
1803 /// ::= .include "filename"
1804 bool AsmParser::ParseDirectiveInclude() {
1805 if (getLexer().isNot(AsmToken::String))
1806 return TokError("expected string in '.include' directive");
1808 std::string Filename = getTok().getString();
1809 SMLoc IncludeLoc = getLexer().getLoc();
1812 if (getLexer().isNot(AsmToken::EndOfStatement))
1813 return TokError("unexpected token in '.include' directive");
1815 // Strip the quotes.
1816 Filename = Filename.substr(1, Filename.size()-2);
1818 // Attempt to switch the lexer to the included file before consuming the end
1819 // of statement to avoid losing it when we switch.
1820 if (EnterIncludeFile(Filename)) {
1821 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1828 /// ParseDirectiveIf
1829 /// ::= .if expression
1830 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1831 TheCondStack.push_back(TheCondState);
1832 TheCondState.TheCond = AsmCond::IfCond;
1833 if(TheCondState.Ignore) {
1834 EatToEndOfStatement();
1838 if (ParseAbsoluteExpression(ExprValue))
1841 if (getLexer().isNot(AsmToken::EndOfStatement))
1842 return TokError("unexpected token in '.if' directive");
1846 TheCondState.CondMet = ExprValue;
1847 TheCondState.Ignore = !TheCondState.CondMet;
1853 /// ParseDirectiveElseIf
1854 /// ::= .elseif expression
1855 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1856 if (TheCondState.TheCond != AsmCond::IfCond &&
1857 TheCondState.TheCond != AsmCond::ElseIfCond)
1858 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1860 TheCondState.TheCond = AsmCond::ElseIfCond;
1862 bool LastIgnoreState = false;
1863 if (!TheCondStack.empty())
1864 LastIgnoreState = TheCondStack.back().Ignore;
1865 if (LastIgnoreState || TheCondState.CondMet) {
1866 TheCondState.Ignore = true;
1867 EatToEndOfStatement();
1871 if (ParseAbsoluteExpression(ExprValue))
1874 if (getLexer().isNot(AsmToken::EndOfStatement))
1875 return TokError("unexpected token in '.elseif' directive");
1878 TheCondState.CondMet = ExprValue;
1879 TheCondState.Ignore = !TheCondState.CondMet;
1885 /// ParseDirectiveElse
1887 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1888 if (getLexer().isNot(AsmToken::EndOfStatement))
1889 return TokError("unexpected token in '.else' directive");
1893 if (TheCondState.TheCond != AsmCond::IfCond &&
1894 TheCondState.TheCond != AsmCond::ElseIfCond)
1895 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1897 TheCondState.TheCond = AsmCond::ElseCond;
1898 bool LastIgnoreState = false;
1899 if (!TheCondStack.empty())
1900 LastIgnoreState = TheCondStack.back().Ignore;
1901 if (LastIgnoreState || TheCondState.CondMet)
1902 TheCondState.Ignore = true;
1904 TheCondState.Ignore = false;
1909 /// ParseDirectiveEndIf
1911 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1912 if (getLexer().isNot(AsmToken::EndOfStatement))
1913 return TokError("unexpected token in '.endif' directive");
1917 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1918 TheCondStack.empty())
1919 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1921 if (!TheCondStack.empty()) {
1922 TheCondState = TheCondStack.back();
1923 TheCondStack.pop_back();
1929 /// ParseDirectiveFile
1930 /// ::= .file [number] string
1931 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1932 // FIXME: I'm not sure what this is.
1933 int64_t FileNumber = -1;
1934 SMLoc FileNumberLoc = getLexer().getLoc();
1935 if (getLexer().is(AsmToken::Integer)) {
1936 FileNumber = getTok().getIntVal();
1940 return TokError("file number less than one");
1943 if (getLexer().isNot(AsmToken::String))
1944 return TokError("unexpected token in '.file' directive");
1946 StringRef Filename = getTok().getString();
1947 Filename = Filename.substr(1, Filename.size()-2);
1950 if (getLexer().isNot(AsmToken::EndOfStatement))
1951 return TokError("unexpected token in '.file' directive");
1953 if (FileNumber == -1)
1954 getStreamer().EmitFileDirective(Filename);
1956 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1957 Error(FileNumberLoc, "file number already allocated");
1958 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1964 /// ParseDirectiveLine
1965 /// ::= .line [number]
1966 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1967 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1968 if (getLexer().isNot(AsmToken::Integer))
1969 return TokError("unexpected token in '.line' directive");
1971 int64_t LineNumber = getTok().getIntVal();
1975 // FIXME: Do something with the .line.
1978 if (getLexer().isNot(AsmToken::EndOfStatement))
1979 return TokError("unexpected token in '.line' directive");
1985 /// ParseDirectiveLoc
1986 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
1987 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
1988 /// The first number is a file number, must have been previously assigned with
1989 /// a .file directive, the second number is the line number and optionally the
1990 /// third number is a column position (zero if not specified). The remaining
1991 /// optional items are .loc sub-directives.
1992 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1994 if (getLexer().isNot(AsmToken::Integer))
1995 return TokError("unexpected token in '.loc' directive");
1996 int64_t FileNumber = getTok().getIntVal();
1998 return TokError("file number less than one in '.loc' directive");
1999 if (!getContext().isValidDwarfFileNumber(FileNumber))
2000 return TokError("unassigned file number in '.loc' directive");
2003 int64_t LineNumber = 0;
2004 if (getLexer().is(AsmToken::Integer)) {
2005 LineNumber = getTok().getIntVal();
2007 return TokError("line number less than one in '.loc' directive");
2011 int64_t ColumnPos = 0;
2012 if (getLexer().is(AsmToken::Integer)) {
2013 ColumnPos = getTok().getIntVal();
2015 return TokError("column position less than zero in '.loc' directive");
2019 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2021 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2023 if (getLexer().is(AsmToken::EndOfStatement))
2027 SMLoc Loc = getTok().getLoc();
2028 if (getParser().ParseIdentifier(Name))
2029 return TokError("unexpected token in '.loc' directive");
2031 if (Name == "basic_block")
2032 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2033 else if (Name == "prologue_end")
2034 Flags |= DWARF2_FLAG_PROLOGUE_END;
2035 else if (Name == "epilogue_begin")
2036 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2037 else if (Name == "is_stmt") {
2038 SMLoc Loc = getTok().getLoc();
2039 const MCExpr *Value;
2040 if (getParser().ParseExpression(Value))
2042 // The expression must be the constant 0 or 1.
2043 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2044 int Value = MCE->getValue();
2046 Flags &= ~DWARF2_FLAG_IS_STMT;
2047 else if (Value == 1)
2048 Flags |= DWARF2_FLAG_IS_STMT;
2050 return Error(Loc, "is_stmt value not 0 or 1");
2053 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2056 else if (Name == "isa") {
2057 SMLoc Loc = getTok().getLoc();
2058 const MCExpr *Value;
2059 if (getParser().ParseExpression(Value))
2061 // The expression must be a constant greater or equal to 0.
2062 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2063 int Value = MCE->getValue();
2065 return Error(Loc, "isa number less than zero");
2069 return Error(Loc, "isa number not a constant value");
2073 return Error(Loc, "unknown sub-directive in '.loc' directive");
2076 if (getLexer().is(AsmToken::EndOfStatement))
2081 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
2086 /// ParseDirectiveStabs
2087 /// ::= .stabs string, number, number, number
2088 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2089 SMLoc DirectiveLoc) {
2090 return TokError("unsupported directive '" + Directive + "'");
2093 /// ParseDirectiveMacrosOnOff
2096 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2097 SMLoc DirectiveLoc) {
2098 if (getLexer().isNot(AsmToken::EndOfStatement))
2099 return Error(getLexer().getLoc(),
2100 "unexpected token in '" + Directive + "' directive");
2102 getParser().MacrosEnabled = Directive == ".macros_on";
2107 /// ParseDirectiveMacro
2109 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2110 SMLoc DirectiveLoc) {
2112 if (getParser().ParseIdentifier(Name))
2113 return TokError("expected identifier in directive");
2115 if (getLexer().isNot(AsmToken::EndOfStatement))
2116 return TokError("unexpected token in '.macro' directive");
2118 // Eat the end of statement.
2121 AsmToken EndToken, StartToken = getTok();
2123 // Lex the macro definition.
2125 // Check whether we have reached the end of the file.
2126 if (getLexer().is(AsmToken::Eof))
2127 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2129 // Otherwise, check whether we have reach the .endmacro.
2130 if (getLexer().is(AsmToken::Identifier) &&
2131 (getTok().getIdentifier() == ".endm" ||
2132 getTok().getIdentifier() == ".endmacro")) {
2133 EndToken = getTok();
2135 if (getLexer().isNot(AsmToken::EndOfStatement))
2136 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2141 // Otherwise, scan til the end of the statement.
2142 getParser().EatToEndOfStatement();
2145 if (getParser().MacroMap.lookup(Name)) {
2146 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2149 const char *BodyStart = StartToken.getLoc().getPointer();
2150 const char *BodyEnd = EndToken.getLoc().getPointer();
2151 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2152 getParser().MacroMap[Name] = new Macro(Name, Body);
2156 /// ParseDirectiveEndMacro
2159 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2160 SMLoc DirectiveLoc) {
2161 if (getLexer().isNot(AsmToken::EndOfStatement))
2162 return TokError("unexpected token in '" + Directive + "' directive");
2164 // If we are inside a macro instantiation, terminate the current
2166 if (!getParser().ActiveMacros.empty()) {
2167 getParser().HandleMacroExit();
2171 // Otherwise, this .endmacro is a stray entry in the file; well formed
2172 // .endmacro directives are handled during the macro definition parsing.
2173 return TokError("unexpected '" + Directive + "' in file, "
2174 "no current macro definition");
2177 void GenericAsmParser::ParseUleb128(uint64_t Value) {
2178 const uint64_t Mask = (1 << 7) - 1;
2180 unsigned Byte = Value & Mask;
2182 if (Value) // Not the last one
2184 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2188 void GenericAsmParser::ParseSleb128(int64_t Value) {
2189 const int64_t Mask = (1 << 7) - 1;
2191 unsigned Byte = Value & Mask;
2193 bool Done = ((Value == 0 && (Byte & 0x40) == 0) ||
2194 (Value == -1 && (Byte & 0x40) != 0));
2197 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2203 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2205 if (getParser().ParseAbsoluteExpression(Value))
2208 if (getLexer().isNot(AsmToken::EndOfStatement))
2209 return TokError("unexpected token in directive");
2211 if (DirName[1] == 's')
2212 ParseSleb128(Value);
2214 ParseUleb128(Value);
2219 /// \brief Create an MCAsmParser instance.
2220 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2221 MCContext &C, MCStreamer &Out,
2222 const MCAsmInfo &MAI) {
2223 return new AsmParser(T, SM, C, Out, MAI);