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/TargetAsmInfo.h"
34 #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 // FIXME: This is not the best place to store this. To handle a (for example)
85 // .cfi_rel_offset before a .cfi_def_cfa_offset we need to know the initial
89 /// This is the current buffer index we're lexing from as managed by the
94 std::vector<AsmCond> TheCondStack;
96 /// DirectiveMap - This is a table handlers for directives. Each handler is
97 /// invoked after the directive identifier is read and is responsible for
98 /// parsing and validating the rest of the directive. The handler is passed
99 /// in the directive name and the location of the directive keyword.
100 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
102 /// MacroMap - Map of currently defined macros.
103 StringMap<Macro*> MacroMap;
105 /// ActiveMacros - Stack of active macro instantiations.
106 std::vector<MacroInstantiation*> ActiveMacros;
108 /// Boolean tracking whether macro substitution is enabled.
109 unsigned MacrosEnabled : 1;
111 /// Flag tracking whether any errors have been encountered.
112 unsigned HadError : 1;
115 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
116 const MCAsmInfo &MAI);
119 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
121 void AddDirectiveHandler(MCAsmParserExtension *Object,
123 DirectiveHandler Handler) {
124 DirectiveMap[Directive] = std::make_pair(Object, Handler);
128 /// @name MCAsmParser Interface
131 virtual SourceMgr &getSourceManager() { return SrcMgr; }
132 virtual MCAsmLexer &getLexer() { return Lexer; }
133 virtual MCContext &getContext() { return Ctx; }
134 virtual MCStreamer &getStreamer() { return Out; }
136 virtual void Warning(SMLoc L, const Twine &Meg);
137 virtual bool Error(SMLoc L, const Twine &Msg);
139 const AsmToken &Lex();
141 bool ParseExpression(const MCExpr *&Res);
142 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
143 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
144 virtual bool ParseAbsoluteExpression(int64_t &Res);
148 int64_t adjustLastOffset(int64_t Adjustment) {
149 LastOffset += Adjustment;
152 int64_t getLastOffset() {
155 void setLastOffset(int64_t Offset) {
160 void CheckForValidSection();
162 bool ParseStatement();
164 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
165 void HandleMacroExit();
167 void PrintMacroInstantiations();
168 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
169 SrcMgr.PrintMessage(Loc, Msg, Type);
172 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
173 bool EnterIncludeFile(const std::string &Filename);
175 /// \brief Reset the current lexer position to that given by \arg Loc. The
176 /// current token is not set; clients should ensure Lex() is called
178 void JumpToLoc(SMLoc Loc);
180 void EatToEndOfStatement();
182 /// \brief Parse up to the end of statement and a return the contents from the
183 /// current token until the end of the statement; the current token on exit
184 /// will be either the EndOfStatement or EOF.
185 StringRef ParseStringToEndOfStatement();
187 bool ParseAssignment(StringRef Name, bool allow_redef);
189 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
190 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
191 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
192 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
194 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
195 /// and set \arg Res to the identifier contents.
196 bool ParseIdentifier(StringRef &Res);
198 // Directive Parsing.
200 // ".ascii", ".asciiz", ".string"
201 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
202 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
203 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
204 bool ParseDirectiveFill(); // ".fill"
205 bool ParseDirectiveSpace(); // ".space"
206 bool ParseDirectiveZero(); // ".zero"
207 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
208 bool ParseDirectiveOrg(); // ".org"
209 // ".align{,32}", ".p2align{,w,l}"
210 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
212 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
213 /// accepts a single symbol (which should be a label or an external).
214 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
216 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
218 bool ParseDirectiveAbort(); // ".abort"
219 bool ParseDirectiveInclude(); // ".include"
221 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
222 // ".ifdef" or ".ifndef", depending on expect_defined
223 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
224 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
225 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
226 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
228 /// ParseEscapedString - Parse the current token as a string which may include
229 /// escaped characters and return the string contents.
230 bool ParseEscapedString(std::string &Data);
232 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
233 MCSymbolRefExpr::VariantKind Variant);
236 /// \brief Generic implementations of directive handling, etc. which is shared
237 /// (or the default, at least) for all assembler parser.
238 class GenericAsmParser : public MCAsmParserExtension {
239 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
240 void AddDirectiveHandler(StringRef Directive) {
241 getParser().AddDirectiveHandler(this, Directive,
242 HandleDirective<GenericAsmParser, Handler>);
245 GenericAsmParser() {}
247 AsmParser &getParser() {
248 return (AsmParser&) this->MCAsmParserExtension::getParser();
251 virtual void Initialize(MCAsmParser &Parser) {
252 // Call the base implementation.
253 this->MCAsmParserExtension::Initialize(Parser);
255 // Debugging directives.
256 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
257 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
258 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
259 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
262 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
264 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
266 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
268 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
269 ".cfi_def_cfa_offset");
270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
271 ".cfi_adjust_cfa_offset");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
273 ".cfi_def_cfa_register");
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
279 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
281 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
283 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
285 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
288 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
293 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
294 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
296 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
297 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
300 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
302 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
303 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
304 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
305 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
306 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
307 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
308 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
309 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
310 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
311 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
312 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
313 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
314 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
315 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
316 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
318 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
319 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
320 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
322 bool ParseDirectiveLEB128(StringRef, SMLoc);
329 extern MCAsmParserExtension *createDarwinAsmParser();
330 extern MCAsmParserExtension *createELFAsmParser();
331 extern MCAsmParserExtension *createCOFFAsmParser();
335 enum { DEFAULT_ADDRSPACE = 0 };
337 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
338 MCStreamer &_Out, const MCAsmInfo &_MAI)
339 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
340 GenericParser(new GenericAsmParser), PlatformParser(0), LastOffset(0),
341 CurBuffer(0), MacrosEnabled(true) {
342 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
344 // Initialize the generic parser.
345 GenericParser->Initialize(*this);
347 // Initialize the platform / file format parser.
349 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
351 if (_MAI.hasMicrosoftFastStdCallMangling()) {
352 PlatformParser = createCOFFAsmParser();
353 PlatformParser->Initialize(*this);
354 } else if (_MAI.hasSubsectionsViaSymbols()) {
355 PlatformParser = createDarwinAsmParser();
356 PlatformParser->Initialize(*this);
358 PlatformParser = createELFAsmParser();
359 PlatformParser->Initialize(*this);
363 AsmParser::~AsmParser() {
364 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
366 // Destroy any macros.
367 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
368 ie = MacroMap.end(); it != ie; ++it)
369 delete it->getValue();
371 delete PlatformParser;
372 delete GenericParser;
375 void AsmParser::PrintMacroInstantiations() {
376 // Print the active macro instantiation stack.
377 for (std::vector<MacroInstantiation*>::const_reverse_iterator
378 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
379 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
383 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
384 PrintMessage(L, Msg, "warning");
385 PrintMacroInstantiations();
388 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
390 PrintMessage(L, Msg, "error");
391 PrintMacroInstantiations();
395 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
396 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
402 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
407 void AsmParser::JumpToLoc(SMLoc Loc) {
408 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
409 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
412 const AsmToken &AsmParser::Lex() {
413 const AsmToken *tok = &Lexer.Lex();
415 if (tok->is(AsmToken::Eof)) {
416 // If this is the end of an included file, pop the parent file off the
418 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
419 if (ParentIncludeLoc != SMLoc()) {
420 JumpToLoc(ParentIncludeLoc);
425 if (tok->is(AsmToken::Error))
426 Error(Lexer.getErrLoc(), Lexer.getErr());
431 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
432 // Create the initial section, if requested.
433 if (!NoInitialTextSection)
440 AsmCond StartingCondState = TheCondState;
442 // While we have input, parse each statement.
443 while (Lexer.isNot(AsmToken::Eof)) {
444 if (!ParseStatement()) continue;
446 // We had an error, validate that one was emitted and recover by skipping to
448 assert(HadError && "Parse statement returned an error, but none emitted!");
449 EatToEndOfStatement();
452 if (TheCondState.TheCond != StartingCondState.TheCond ||
453 TheCondState.Ignore != StartingCondState.Ignore)
454 return TokError("unmatched .ifs or .elses");
456 // Check to see there are no empty DwarfFile slots.
457 const std::vector<MCDwarfFile *> &MCDwarfFiles =
458 getContext().getMCDwarfFiles();
459 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
460 if (!MCDwarfFiles[i])
461 TokError("unassigned file number: " + Twine(i) + " for .file directives");
464 // Finalize the output stream if there are no errors and if the client wants
466 if (!HadError && !NoFinalize)
472 void AsmParser::CheckForValidSection() {
473 if (!getStreamer().getCurrentSection()) {
474 TokError("expected section directive before assembly directive");
475 Out.SwitchSection(Ctx.getMachOSection(
477 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
478 0, SectionKind::getText()));
482 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
483 void AsmParser::EatToEndOfStatement() {
484 while (Lexer.isNot(AsmToken::EndOfStatement) &&
485 Lexer.isNot(AsmToken::Eof))
489 if (Lexer.is(AsmToken::EndOfStatement))
493 StringRef AsmParser::ParseStringToEndOfStatement() {
494 const char *Start = getTok().getLoc().getPointer();
496 while (Lexer.isNot(AsmToken::EndOfStatement) &&
497 Lexer.isNot(AsmToken::Eof))
500 const char *End = getTok().getLoc().getPointer();
501 return StringRef(Start, End - Start);
504 /// ParseParenExpr - Parse a paren expression and return it.
505 /// NOTE: This assumes the leading '(' has already been consumed.
507 /// parenexpr ::= expr)
509 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
510 if (ParseExpression(Res)) return true;
511 if (Lexer.isNot(AsmToken::RParen))
512 return TokError("expected ')' in parentheses expression");
513 EndLoc = Lexer.getLoc();
518 /// ParseBracketExpr - Parse a bracket expression and return it.
519 /// NOTE: This assumes the leading '[' has already been consumed.
521 /// bracketexpr ::= expr]
523 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
524 if (ParseExpression(Res)) return true;
525 if (Lexer.isNot(AsmToken::RBrac))
526 return TokError("expected ']' in brackets expression");
527 EndLoc = Lexer.getLoc();
532 /// ParsePrimaryExpr - Parse a primary expression and return it.
533 /// primaryexpr ::= (parenexpr
534 /// primaryexpr ::= symbol
535 /// primaryexpr ::= number
536 /// primaryexpr ::= '.'
537 /// primaryexpr ::= ~,+,- primaryexpr
538 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
539 switch (Lexer.getKind()) {
541 return TokError("unknown token in expression");
542 case AsmToken::Exclaim:
543 Lex(); // Eat the operator.
544 if (ParsePrimaryExpr(Res, EndLoc))
546 Res = MCUnaryExpr::CreateLNot(Res, getContext());
548 case AsmToken::Dollar:
549 case AsmToken::String:
550 case AsmToken::Identifier: {
551 EndLoc = Lexer.getLoc();
553 StringRef Identifier;
554 if (ParseIdentifier(Identifier))
557 // This is a symbol reference.
558 std::pair<StringRef, StringRef> Split = Identifier.split('@');
559 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
561 // Lookup the symbol variant if used.
562 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
563 if (Split.first.size() != Identifier.size()) {
564 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
565 if (Variant == MCSymbolRefExpr::VK_Invalid) {
566 Variant = MCSymbolRefExpr::VK_None;
567 return TokError("invalid variant '" + Split.second + "'");
571 // If this is an absolute variable reference, substitute it now to preserve
572 // semantics in the face of reassignment.
573 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
575 return Error(EndLoc, "unexpected modifier on variable reference");
577 Res = Sym->getVariableValue();
581 // Otherwise create a symbol ref.
582 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
585 case AsmToken::Integer: {
586 SMLoc Loc = getTok().getLoc();
587 int64_t IntVal = getTok().getIntVal();
588 Res = MCConstantExpr::Create(IntVal, getContext());
589 EndLoc = Lexer.getLoc();
591 // Look for 'b' or 'f' following an Integer as a directional label
592 if (Lexer.getKind() == AsmToken::Identifier) {
593 StringRef IDVal = getTok().getString();
594 if (IDVal == "f" || IDVal == "b"){
595 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
596 IDVal == "f" ? 1 : 0);
597 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
599 if(IDVal == "b" && Sym->isUndefined())
600 return Error(Loc, "invalid reference to undefined symbol");
601 EndLoc = Lexer.getLoc();
602 Lex(); // Eat identifier.
607 case AsmToken::Real: {
608 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
609 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
610 Res = MCConstantExpr::Create(IntVal, getContext());
614 case AsmToken::Dot: {
615 // This is a '.' reference, which references the current PC. Emit a
616 // temporary label to the streamer and refer to it.
617 MCSymbol *Sym = Ctx.CreateTempSymbol();
619 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
620 EndLoc = Lexer.getLoc();
621 Lex(); // Eat identifier.
624 case AsmToken::LParen:
625 Lex(); // Eat the '('.
626 return ParseParenExpr(Res, EndLoc);
627 case AsmToken::LBrac:
628 if (!PlatformParser->HasBracketExpressions())
629 return TokError("brackets expression not supported on this target");
630 Lex(); // Eat the '['.
631 return ParseBracketExpr(Res, EndLoc);
632 case AsmToken::Minus:
633 Lex(); // Eat the operator.
634 if (ParsePrimaryExpr(Res, EndLoc))
636 Res = MCUnaryExpr::CreateMinus(Res, getContext());
639 Lex(); // Eat the operator.
640 if (ParsePrimaryExpr(Res, EndLoc))
642 Res = MCUnaryExpr::CreatePlus(Res, getContext());
644 case AsmToken::Tilde:
645 Lex(); // Eat the operator.
646 if (ParsePrimaryExpr(Res, EndLoc))
648 Res = MCUnaryExpr::CreateNot(Res, getContext());
653 bool AsmParser::ParseExpression(const MCExpr *&Res) {
655 return ParseExpression(Res, EndLoc);
659 AsmParser::ApplyModifierToExpr(const MCExpr *E,
660 MCSymbolRefExpr::VariantKind Variant) {
661 // Recurse over the given expression, rebuilding it to apply the given variant
662 // if there is exactly one symbol.
663 switch (E->getKind()) {
665 case MCExpr::Constant:
668 case MCExpr::SymbolRef: {
669 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
671 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
672 TokError("invalid variant on expression '" +
673 getTok().getIdentifier() + "' (already modified)");
677 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
680 case MCExpr::Unary: {
681 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
682 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
685 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
688 case MCExpr::Binary: {
689 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
690 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
691 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
696 if (!LHS) LHS = BE->getLHS();
697 if (!RHS) RHS = BE->getRHS();
699 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
703 assert(0 && "Invalid expression kind!");
707 /// ParseExpression - Parse an expression and return it.
709 /// expr ::= expr +,- expr -> lowest.
710 /// expr ::= expr |,^,&,! expr -> middle.
711 /// expr ::= expr *,/,%,<<,>> expr -> highest.
712 /// expr ::= primaryexpr
714 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
715 // Parse the expression.
717 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
720 // As a special case, we support 'a op b @ modifier' by rewriting the
721 // expression to include the modifier. This is inefficient, but in general we
722 // expect users to use 'a@modifier op b'.
723 if (Lexer.getKind() == AsmToken::At) {
726 if (Lexer.isNot(AsmToken::Identifier))
727 return TokError("unexpected symbol modifier following '@'");
729 MCSymbolRefExpr::VariantKind Variant =
730 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
731 if (Variant == MCSymbolRefExpr::VK_Invalid)
732 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
734 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
736 return TokError("invalid modifier '" + getTok().getIdentifier() +
737 "' (no symbols present)");
745 // Try to constant fold it up front, if possible.
747 if (Res->EvaluateAsAbsolute(Value))
748 Res = MCConstantExpr::Create(Value, getContext());
753 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
755 return ParseParenExpr(Res, EndLoc) ||
756 ParseBinOpRHS(1, Res, EndLoc);
759 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
762 SMLoc StartLoc = Lexer.getLoc();
763 if (ParseExpression(Expr))
766 if (!Expr->EvaluateAsAbsolute(Res))
767 return Error(StartLoc, "expected absolute expression");
772 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
773 MCBinaryExpr::Opcode &Kind) {
776 return 0; // not a binop.
778 // Lowest Precedence: &&, ||, @
779 case AsmToken::AmpAmp:
780 Kind = MCBinaryExpr::LAnd;
782 case AsmToken::PipePipe:
783 Kind = MCBinaryExpr::LOr;
787 // Low Precedence: |, &, ^
789 // FIXME: gas seems to support '!' as an infix operator?
791 Kind = MCBinaryExpr::Or;
793 case AsmToken::Caret:
794 Kind = MCBinaryExpr::Xor;
797 Kind = MCBinaryExpr::And;
800 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
801 case AsmToken::EqualEqual:
802 Kind = MCBinaryExpr::EQ;
804 case AsmToken::ExclaimEqual:
805 case AsmToken::LessGreater:
806 Kind = MCBinaryExpr::NE;
809 Kind = MCBinaryExpr::LT;
811 case AsmToken::LessEqual:
812 Kind = MCBinaryExpr::LTE;
814 case AsmToken::Greater:
815 Kind = MCBinaryExpr::GT;
817 case AsmToken::GreaterEqual:
818 Kind = MCBinaryExpr::GTE;
821 // High Intermediate Precedence: +, -
823 Kind = MCBinaryExpr::Add;
825 case AsmToken::Minus:
826 Kind = MCBinaryExpr::Sub;
829 // Highest Precedence: *, /, %, <<, >>
831 Kind = MCBinaryExpr::Mul;
833 case AsmToken::Slash:
834 Kind = MCBinaryExpr::Div;
836 case AsmToken::Percent:
837 Kind = MCBinaryExpr::Mod;
839 case AsmToken::LessLess:
840 Kind = MCBinaryExpr::Shl;
842 case AsmToken::GreaterGreater:
843 Kind = MCBinaryExpr::Shr;
849 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
850 /// Res contains the LHS of the expression on input.
851 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
854 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
855 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
857 // If the next token is lower precedence than we are allowed to eat, return
858 // successfully with what we ate already.
859 if (TokPrec < Precedence)
864 // Eat the next primary expression.
866 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
868 // If BinOp binds less tightly with RHS than the operator after RHS, let
869 // the pending operator take RHS as its LHS.
870 MCBinaryExpr::Opcode Dummy;
871 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
872 if (TokPrec < NextTokPrec) {
873 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
876 // Merge LHS and RHS according to operator.
877 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
885 /// ::= EndOfStatement
886 /// ::= Label* Directive ...Operands... EndOfStatement
887 /// ::= Label* Identifier OperandList* EndOfStatement
888 bool AsmParser::ParseStatement() {
889 if (Lexer.is(AsmToken::EndOfStatement)) {
895 // Statements always start with an identifier or are a full line comment.
896 AsmToken ID = getTok();
897 SMLoc IDLoc = ID.getLoc();
899 int64_t LocalLabelVal = -1;
900 // A full line comment is a '#' as the first token.
901 if (Lexer.is(AsmToken::Hash)) {
902 EatToEndOfStatement();
906 // Allow an integer followed by a ':' as a directional local label.
907 if (Lexer.is(AsmToken::Integer)) {
908 LocalLabelVal = getTok().getIntVal();
909 if (LocalLabelVal < 0) {
910 if (!TheCondState.Ignore)
911 return TokError("unexpected token at start of statement");
915 IDVal = getTok().getString();
916 Lex(); // Consume the integer token to be used as an identifier token.
917 if (Lexer.getKind() != AsmToken::Colon) {
918 if (!TheCondState.Ignore)
919 return TokError("unexpected token at start of statement");
923 } else if (Lexer.is(AsmToken::Dot)) {
924 // Treat '.' as a valid identifier in this context.
928 } else if (ParseIdentifier(IDVal)) {
929 if (!TheCondState.Ignore)
930 return TokError("unexpected token at start of statement");
935 // Handle conditional assembly here before checking for skipping. We
936 // have to do this so that .endif isn't skipped in a ".if 0" block for
939 return ParseDirectiveIf(IDLoc);
940 if (IDVal == ".ifdef")
941 return ParseDirectiveIfdef(IDLoc, true);
942 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
943 return ParseDirectiveIfdef(IDLoc, false);
944 if (IDVal == ".elseif")
945 return ParseDirectiveElseIf(IDLoc);
946 if (IDVal == ".else")
947 return ParseDirectiveElse(IDLoc);
948 if (IDVal == ".endif")
949 return ParseDirectiveEndIf(IDLoc);
951 // If we are in a ".if 0" block, ignore this statement.
952 if (TheCondState.Ignore) {
953 EatToEndOfStatement();
957 // FIXME: Recurse on local labels?
959 // See what kind of statement we have.
960 switch (Lexer.getKind()) {
961 case AsmToken::Colon: {
962 CheckForValidSection();
964 // identifier ':' -> Label.
967 // Diagnose attempt to use '.' as a label.
969 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
971 // Diagnose attempt to use a variable as a label.
973 // FIXME: Diagnostics. Note the location of the definition as a label.
974 // FIXME: This doesn't diagnose assignment to a symbol which has been
975 // implicitly marked as external.
977 if (LocalLabelVal == -1)
978 Sym = getContext().GetOrCreateSymbol(IDVal);
980 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
981 if (!Sym->isUndefined() || Sym->isVariable())
982 return Error(IDLoc, "invalid symbol redefinition");
987 // Consume any end of statement token, if present, to avoid spurious
988 // AddBlankLine calls().
989 if (Lexer.is(AsmToken::EndOfStatement)) {
991 if (Lexer.is(AsmToken::Eof))
995 return ParseStatement();
998 case AsmToken::Equal:
999 // identifier '=' ... -> assignment statement
1002 return ParseAssignment(IDVal, true);
1004 default: // Normal instruction or directive.
1008 // If macros are enabled, check to see if this is a macro instantiation.
1010 if (const Macro *M = MacroMap.lookup(IDVal))
1011 return HandleMacroEntry(IDVal, IDLoc, M);
1013 // Otherwise, we have a normal instruction or directive.
1014 if (IDVal[0] == '.' && IDVal != ".") {
1015 // Assembler features
1016 if (IDVal == ".set" || IDVal == ".equ")
1017 return ParseDirectiveSet(IDVal, true);
1018 if (IDVal == ".equiv")
1019 return ParseDirectiveSet(IDVal, false);
1023 if (IDVal == ".ascii")
1024 return ParseDirectiveAscii(IDVal, false);
1025 if (IDVal == ".asciz" || IDVal == ".string")
1026 return ParseDirectiveAscii(IDVal, true);
1028 if (IDVal == ".byte")
1029 return ParseDirectiveValue(1);
1030 if (IDVal == ".short")
1031 return ParseDirectiveValue(2);
1032 if (IDVal == ".value")
1033 return ParseDirectiveValue(2);
1034 if (IDVal == ".2byte")
1035 return ParseDirectiveValue(2);
1036 if (IDVal == ".long")
1037 return ParseDirectiveValue(4);
1038 if (IDVal == ".int")
1039 return ParseDirectiveValue(4);
1040 if (IDVal == ".4byte")
1041 return ParseDirectiveValue(4);
1042 if (IDVal == ".quad")
1043 return ParseDirectiveValue(8);
1044 if (IDVal == ".8byte")
1045 return ParseDirectiveValue(8);
1046 if (IDVal == ".single" || IDVal == ".float")
1047 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1048 if (IDVal == ".double")
1049 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1051 if (IDVal == ".align") {
1052 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1053 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1055 if (IDVal == ".align32") {
1056 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1057 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1059 if (IDVal == ".balign")
1060 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1061 if (IDVal == ".balignw")
1062 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1063 if (IDVal == ".balignl")
1064 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1065 if (IDVal == ".p2align")
1066 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1067 if (IDVal == ".p2alignw")
1068 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1069 if (IDVal == ".p2alignl")
1070 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1072 if (IDVal == ".org")
1073 return ParseDirectiveOrg();
1075 if (IDVal == ".fill")
1076 return ParseDirectiveFill();
1077 if (IDVal == ".space" || IDVal == ".skip")
1078 return ParseDirectiveSpace();
1079 if (IDVal == ".zero")
1080 return ParseDirectiveZero();
1082 // Symbol attribute directives
1084 if (IDVal == ".globl" || IDVal == ".global")
1085 return ParseDirectiveSymbolAttribute(MCSA_Global);
1086 // ELF only? Should it be here?
1087 if (IDVal == ".local")
1088 return ParseDirectiveSymbolAttribute(MCSA_Local);
1089 if (IDVal == ".hidden")
1090 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1091 if (IDVal == ".indirect_symbol")
1092 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1093 if (IDVal == ".internal")
1094 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1095 if (IDVal == ".lazy_reference")
1096 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1097 if (IDVal == ".no_dead_strip")
1098 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1099 if (IDVal == ".symbol_resolver")
1100 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1101 if (IDVal == ".private_extern")
1102 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1103 if (IDVal == ".protected")
1104 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1105 if (IDVal == ".reference")
1106 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1107 if (IDVal == ".weak")
1108 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1109 if (IDVal == ".weak_definition")
1110 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1111 if (IDVal == ".weak_reference")
1112 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1113 if (IDVal == ".weak_def_can_be_hidden")
1114 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1116 if (IDVal == ".comm")
1117 return ParseDirectiveComm(/*IsLocal=*/false);
1118 if (IDVal == ".lcomm")
1119 return ParseDirectiveComm(/*IsLocal=*/true);
1121 if (IDVal == ".abort")
1122 return ParseDirectiveAbort();
1123 if (IDVal == ".include")
1124 return ParseDirectiveInclude();
1126 if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1127 return TokError(Twine(IDVal) + " not supported yet");
1129 // Look up the handler in the handler table.
1130 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1131 DirectiveMap.lookup(IDVal);
1133 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1135 // Target hook for parsing target specific directives.
1136 if (!getTargetParser().ParseDirective(ID))
1139 Warning(IDLoc, "ignoring directive for now");
1140 EatToEndOfStatement();
1144 CheckForValidSection();
1146 // Canonicalize the opcode to lower case.
1147 SmallString<128> Opcode;
1148 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1149 Opcode.push_back(tolower(IDVal[i]));
1151 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1152 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1155 // Dump the parsed representation, if requested.
1156 if (getShowParsedOperands()) {
1157 SmallString<256> Str;
1158 raw_svector_ostream OS(Str);
1159 OS << "parsed instruction: [";
1160 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1163 ParsedOperands[i]->dump(OS);
1167 PrintMessage(IDLoc, OS.str(), "note");
1170 // If parsing succeeded, match the instruction.
1172 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1175 // Free any parsed operands.
1176 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1177 delete ParsedOperands[i];
1179 // Don't skip the rest of the line, the instruction parser is responsible for
1184 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1185 const std::vector<std::vector<AsmToken> > &A)
1186 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1188 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1189 // to hold the macro body with substitutions.
1190 SmallString<256> Buf;
1191 raw_svector_ostream OS(Buf);
1193 StringRef Body = M->Body;
1194 while (!Body.empty()) {
1195 // Scan for the next substitution.
1196 std::size_t End = Body.size(), Pos = 0;
1197 for (; Pos != End; ++Pos) {
1198 // Check for a substitution or escape.
1199 if (Body[Pos] != '$' || Pos + 1 == End)
1202 char Next = Body[Pos + 1];
1203 if (Next == '$' || Next == 'n' || isdigit(Next))
1208 OS << Body.slice(0, Pos);
1210 // Check if we reached the end.
1214 switch (Body[Pos+1]) {
1220 // $n => number of arguments
1225 // $[0-9] => argument
1227 // Missing arguments are ignored.
1228 unsigned Index = Body[Pos+1] - '0';
1229 if (Index >= A.size())
1232 // Otherwise substitute with the token values, with spaces eliminated.
1233 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1234 ie = A[Index].end(); it != ie; ++it)
1235 OS << it->getString();
1240 // Update the scan point.
1241 Body = Body.substr(Pos + 2);
1244 // We include the .endmacro in the buffer as our queue to exit the macro
1246 OS << ".endmacro\n";
1248 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1251 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1253 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1254 // this, although we should protect against infinite loops.
1255 if (ActiveMacros.size() == 20)
1256 return TokError("macros cannot be nested more than 20 levels deep");
1258 // Parse the macro instantiation arguments.
1259 std::vector<std::vector<AsmToken> > MacroArguments;
1260 MacroArguments.push_back(std::vector<AsmToken>());
1261 unsigned ParenLevel = 0;
1263 if (Lexer.is(AsmToken::Eof))
1264 return TokError("unexpected token in macro instantiation");
1265 if (Lexer.is(AsmToken::EndOfStatement))
1268 // If we aren't inside parentheses and this is a comma, start a new token
1270 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1271 MacroArguments.push_back(std::vector<AsmToken>());
1273 // Adjust the current parentheses level.
1274 if (Lexer.is(AsmToken::LParen))
1276 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1279 // Append the token to the current argument list.
1280 MacroArguments.back().push_back(getTok());
1285 // Create the macro instantiation object and add to the current macro
1286 // instantiation stack.
1287 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1290 ActiveMacros.push_back(MI);
1292 // Jump to the macro instantiation and prime the lexer.
1293 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1294 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1300 void AsmParser::HandleMacroExit() {
1301 // Jump to the EndOfStatement we should return to, and consume it.
1302 JumpToLoc(ActiveMacros.back()->ExitLoc);
1305 // Pop the instantiation entry.
1306 delete ActiveMacros.back();
1307 ActiveMacros.pop_back();
1310 static void MarkUsed(const MCExpr *Value) {
1311 switch (Value->getKind()) {
1312 case MCExpr::Binary:
1313 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1314 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1316 case MCExpr::Target:
1317 case MCExpr::Constant:
1319 case MCExpr::SymbolRef: {
1320 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1324 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1329 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1330 // FIXME: Use better location, we should use proper tokens.
1331 SMLoc EqualLoc = Lexer.getLoc();
1333 const MCExpr *Value;
1334 if (ParseExpression(Value))
1339 if (Lexer.isNot(AsmToken::EndOfStatement))
1340 return TokError("unexpected token in assignment");
1342 // Error on assignment to '.'.
1344 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1345 "(use '.space' or '.org').)"));
1348 // Eat the end of statement marker.
1351 // Validate that the LHS is allowed to be a variable (either it has not been
1352 // used as a symbol, or it is an absolute symbol).
1353 MCSymbol *Sym = getContext().LookupSymbol(Name);
1355 // Diagnose assignment to a label.
1357 // FIXME: Diagnostics. Note the location of the definition as a label.
1358 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1359 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1360 ; // Allow redefinitions of undefined symbols only used in directives.
1361 else if (!Sym->isUndefined() && (!Sym->isAbsolute() || !allow_redef))
1362 return Error(EqualLoc, "redefinition of '" + Name + "'");
1363 else if (!Sym->isVariable())
1364 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1365 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1366 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1369 // Don't count these checks as uses.
1370 Sym->setUsed(false);
1372 Sym = getContext().GetOrCreateSymbol(Name);
1374 // FIXME: Handle '.'.
1376 // Do the assignment.
1377 Out.EmitAssignment(Sym, Value);
1382 /// ParseIdentifier:
1385 bool AsmParser::ParseIdentifier(StringRef &Res) {
1386 // The assembler has relaxed rules for accepting identifiers, in particular we
1387 // allow things like '.globl $foo', which would normally be separate
1388 // tokens. At this level, we have already lexed so we cannot (currently)
1389 // handle this as a context dependent token, instead we detect adjacent tokens
1390 // and return the combined identifier.
1391 if (Lexer.is(AsmToken::Dollar)) {
1392 SMLoc DollarLoc = getLexer().getLoc();
1394 // Consume the dollar sign, and check for a following identifier.
1396 if (Lexer.isNot(AsmToken::Identifier))
1399 // We have a '$' followed by an identifier, make sure they are adjacent.
1400 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1403 // Construct the joined identifier and consume the token.
1404 Res = StringRef(DollarLoc.getPointer(),
1405 getTok().getIdentifier().size() + 1);
1410 if (Lexer.isNot(AsmToken::Identifier) &&
1411 Lexer.isNot(AsmToken::String))
1414 Res = getTok().getIdentifier();
1416 Lex(); // Consume the identifier token.
1421 /// ParseDirectiveSet:
1422 /// ::= .equ identifier ',' expression
1423 /// ::= .equiv identifier ',' expression
1424 /// ::= .set identifier ',' expression
1425 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1428 if (ParseIdentifier(Name))
1429 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1431 if (getLexer().isNot(AsmToken::Comma))
1432 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1435 return ParseAssignment(Name, allow_redef);
1438 bool AsmParser::ParseEscapedString(std::string &Data) {
1439 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1442 StringRef Str = getTok().getStringContents();
1443 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1444 if (Str[i] != '\\') {
1449 // Recognize escaped characters. Note that this escape semantics currently
1450 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1453 return TokError("unexpected backslash at end of string");
1455 // Recognize octal sequences.
1456 if ((unsigned) (Str[i] - '0') <= 7) {
1457 // Consume up to three octal characters.
1458 unsigned Value = Str[i] - '0';
1460 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1462 Value = Value * 8 + (Str[i] - '0');
1464 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1466 Value = Value * 8 + (Str[i] - '0');
1471 return TokError("invalid octal escape sequence (out of range)");
1473 Data += (unsigned char) Value;
1477 // Otherwise recognize individual escapes.
1480 // Just reject invalid escape sequences for now.
1481 return TokError("invalid escape sequence (unrecognized character)");
1483 case 'b': Data += '\b'; break;
1484 case 'f': Data += '\f'; break;
1485 case 'n': Data += '\n'; break;
1486 case 'r': Data += '\r'; break;
1487 case 't': Data += '\t'; break;
1488 case '"': Data += '"'; break;
1489 case '\\': Data += '\\'; break;
1496 /// ParseDirectiveAscii:
1497 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1498 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1499 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1500 CheckForValidSection();
1503 if (getLexer().isNot(AsmToken::String))
1504 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1507 if (ParseEscapedString(Data))
1510 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1512 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1516 if (getLexer().is(AsmToken::EndOfStatement))
1519 if (getLexer().isNot(AsmToken::Comma))
1520 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1529 /// ParseDirectiveValue
1530 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1531 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1532 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1533 CheckForValidSection();
1536 const MCExpr *Value;
1537 if (ParseExpression(Value))
1540 // Special case constant expressions to match code generator.
1541 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1542 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1544 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1546 if (getLexer().is(AsmToken::EndOfStatement))
1549 // FIXME: Improve diagnostic.
1550 if (getLexer().isNot(AsmToken::Comma))
1551 return TokError("unexpected token in directive");
1560 /// ParseDirectiveRealValue
1561 /// ::= (.single | .double) [ expression (, expression)* ]
1562 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1563 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1564 CheckForValidSection();
1567 // We don't truly support arithmetic on floating point expressions, so we
1568 // have to manually parse unary prefixes.
1570 if (getLexer().is(AsmToken::Minus)) {
1573 } else if (getLexer().is(AsmToken::Plus))
1576 if (getLexer().isNot(AsmToken::Integer) &&
1577 getLexer().isNot(AsmToken::Real) &&
1578 getLexer().isNot(AsmToken::Identifier))
1579 return TokError("unexpected token in directive");
1581 // Convert to an APFloat.
1582 APFloat Value(Semantics);
1583 StringRef IDVal = getTok().getString();
1584 if (getLexer().is(AsmToken::Identifier)) {
1585 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1586 Value = APFloat::getInf(Semantics);
1587 else if (!IDVal.compare_lower("nan"))
1588 Value = APFloat::getNaN(Semantics, false, ~0);
1590 return TokError("invalid floating point literal");
1591 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1592 APFloat::opInvalidOp)
1593 return TokError("invalid floating point literal");
1597 // Consume the numeric token.
1600 // Emit the value as an integer.
1601 APInt AsInt = Value.bitcastToAPInt();
1602 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1603 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1605 if (getLexer().is(AsmToken::EndOfStatement))
1608 if (getLexer().isNot(AsmToken::Comma))
1609 return TokError("unexpected token in directive");
1618 /// ParseDirectiveSpace
1619 /// ::= .space expression [ , expression ]
1620 bool AsmParser::ParseDirectiveSpace() {
1621 CheckForValidSection();
1624 if (ParseAbsoluteExpression(NumBytes))
1627 int64_t FillExpr = 0;
1628 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1629 if (getLexer().isNot(AsmToken::Comma))
1630 return TokError("unexpected token in '.space' directive");
1633 if (ParseAbsoluteExpression(FillExpr))
1636 if (getLexer().isNot(AsmToken::EndOfStatement))
1637 return TokError("unexpected token in '.space' directive");
1643 return TokError("invalid number of bytes in '.space' directive");
1645 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1646 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1651 /// ParseDirectiveZero
1652 /// ::= .zero expression
1653 bool AsmParser::ParseDirectiveZero() {
1654 CheckForValidSection();
1657 if (ParseAbsoluteExpression(NumBytes))
1661 if (getLexer().is(AsmToken::Comma)) {
1663 if (ParseAbsoluteExpression(Val))
1667 if (getLexer().isNot(AsmToken::EndOfStatement))
1668 return TokError("unexpected token in '.zero' directive");
1672 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1677 /// ParseDirectiveFill
1678 /// ::= .fill expression , expression , expression
1679 bool AsmParser::ParseDirectiveFill() {
1680 CheckForValidSection();
1683 if (ParseAbsoluteExpression(NumValues))
1686 if (getLexer().isNot(AsmToken::Comma))
1687 return TokError("unexpected token in '.fill' directive");
1691 if (ParseAbsoluteExpression(FillSize))
1694 if (getLexer().isNot(AsmToken::Comma))
1695 return TokError("unexpected token in '.fill' directive");
1699 if (ParseAbsoluteExpression(FillExpr))
1702 if (getLexer().isNot(AsmToken::EndOfStatement))
1703 return TokError("unexpected token in '.fill' directive");
1707 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1708 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1710 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1711 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1716 /// ParseDirectiveOrg
1717 /// ::= .org expression [ , expression ]
1718 bool AsmParser::ParseDirectiveOrg() {
1719 CheckForValidSection();
1721 const MCExpr *Offset;
1722 if (ParseExpression(Offset))
1725 // Parse optional fill expression.
1726 int64_t FillExpr = 0;
1727 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1728 if (getLexer().isNot(AsmToken::Comma))
1729 return TokError("unexpected token in '.org' directive");
1732 if (ParseAbsoluteExpression(FillExpr))
1735 if (getLexer().isNot(AsmToken::EndOfStatement))
1736 return TokError("unexpected token in '.org' directive");
1741 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1742 // has to be relative to the current section.
1743 getStreamer().EmitValueToOffset(Offset, FillExpr);
1748 /// ParseDirectiveAlign
1749 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1750 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1751 CheckForValidSection();
1753 SMLoc AlignmentLoc = getLexer().getLoc();
1755 if (ParseAbsoluteExpression(Alignment))
1759 bool HasFillExpr = false;
1760 int64_t FillExpr = 0;
1761 int64_t MaxBytesToFill = 0;
1762 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1763 if (getLexer().isNot(AsmToken::Comma))
1764 return TokError("unexpected token in directive");
1767 // The fill expression can be omitted while specifying a maximum number of
1768 // alignment bytes, e.g:
1770 if (getLexer().isNot(AsmToken::Comma)) {
1772 if (ParseAbsoluteExpression(FillExpr))
1776 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1777 if (getLexer().isNot(AsmToken::Comma))
1778 return TokError("unexpected token in directive");
1781 MaxBytesLoc = getLexer().getLoc();
1782 if (ParseAbsoluteExpression(MaxBytesToFill))
1785 if (getLexer().isNot(AsmToken::EndOfStatement))
1786 return TokError("unexpected token in directive");
1795 // Compute alignment in bytes.
1797 // FIXME: Diagnose overflow.
1798 if (Alignment >= 32) {
1799 Error(AlignmentLoc, "invalid alignment value");
1803 Alignment = 1ULL << Alignment;
1806 // Diagnose non-sensical max bytes to align.
1807 if (MaxBytesLoc.isValid()) {
1808 if (MaxBytesToFill < 1) {
1809 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1810 "many bytes, ignoring maximum bytes expression");
1814 if (MaxBytesToFill >= Alignment) {
1815 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1821 // Check whether we should use optimal code alignment for this .align
1823 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1824 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1825 ValueSize == 1 && UseCodeAlign) {
1826 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1828 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1829 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1836 /// ParseDirectiveSymbolAttribute
1837 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1838 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1839 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1843 if (ParseIdentifier(Name))
1844 return TokError("expected identifier in directive");
1846 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1848 getStreamer().EmitSymbolAttribute(Sym, Attr);
1850 if (getLexer().is(AsmToken::EndOfStatement))
1853 if (getLexer().isNot(AsmToken::Comma))
1854 return TokError("unexpected token in directive");
1863 /// ParseDirectiveComm
1864 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1865 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1866 CheckForValidSection();
1868 SMLoc IDLoc = getLexer().getLoc();
1870 if (ParseIdentifier(Name))
1871 return TokError("expected identifier in directive");
1873 // Handle the identifier as the key symbol.
1874 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1876 if (getLexer().isNot(AsmToken::Comma))
1877 return TokError("unexpected token in directive");
1881 SMLoc SizeLoc = getLexer().getLoc();
1882 if (ParseAbsoluteExpression(Size))
1885 int64_t Pow2Alignment = 0;
1886 SMLoc Pow2AlignmentLoc;
1887 if (getLexer().is(AsmToken::Comma)) {
1889 Pow2AlignmentLoc = getLexer().getLoc();
1890 if (ParseAbsoluteExpression(Pow2Alignment))
1893 // If this target takes alignments in bytes (not log) validate and convert.
1894 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1895 if (!isPowerOf2_64(Pow2Alignment))
1896 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1897 Pow2Alignment = Log2_64(Pow2Alignment);
1901 if (getLexer().isNot(AsmToken::EndOfStatement))
1902 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1906 // NOTE: a size of zero for a .comm should create a undefined symbol
1907 // but a size of .lcomm creates a bss symbol of size zero.
1909 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1910 "be less than zero");
1912 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1913 // may internally end up wanting an alignment in bytes.
1914 // FIXME: Diagnose overflow.
1915 if (Pow2Alignment < 0)
1916 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1917 "alignment, can't be less than zero");
1919 if (!Sym->isUndefined())
1920 return Error(IDLoc, "invalid symbol redefinition");
1922 // '.lcomm' is equivalent to '.zerofill'.
1923 // Create the Symbol as a common or local common with Size and Pow2Alignment
1925 getStreamer().EmitZerofill(Ctx.getMachOSection(
1926 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1927 0, SectionKind::getBSS()),
1928 Sym, Size, 1 << Pow2Alignment);
1932 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1936 /// ParseDirectiveAbort
1937 /// ::= .abort [... message ...]
1938 bool AsmParser::ParseDirectiveAbort() {
1939 // FIXME: Use loc from directive.
1940 SMLoc Loc = getLexer().getLoc();
1942 StringRef Str = ParseStringToEndOfStatement();
1943 if (getLexer().isNot(AsmToken::EndOfStatement))
1944 return TokError("unexpected token in '.abort' directive");
1949 Error(Loc, ".abort detected. Assembly stopping.");
1951 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1952 // FIXME: Actually abort assembly here.
1957 /// ParseDirectiveInclude
1958 /// ::= .include "filename"
1959 bool AsmParser::ParseDirectiveInclude() {
1960 if (getLexer().isNot(AsmToken::String))
1961 return TokError("expected string in '.include' directive");
1963 std::string Filename = getTok().getString();
1964 SMLoc IncludeLoc = getLexer().getLoc();
1967 if (getLexer().isNot(AsmToken::EndOfStatement))
1968 return TokError("unexpected token in '.include' directive");
1970 // Strip the quotes.
1971 Filename = Filename.substr(1, Filename.size()-2);
1973 // Attempt to switch the lexer to the included file before consuming the end
1974 // of statement to avoid losing it when we switch.
1975 if (EnterIncludeFile(Filename)) {
1976 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1983 /// ParseDirectiveIf
1984 /// ::= .if expression
1985 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1986 TheCondStack.push_back(TheCondState);
1987 TheCondState.TheCond = AsmCond::IfCond;
1988 if(TheCondState.Ignore) {
1989 EatToEndOfStatement();
1993 if (ParseAbsoluteExpression(ExprValue))
1996 if (getLexer().isNot(AsmToken::EndOfStatement))
1997 return TokError("unexpected token in '.if' directive");
2001 TheCondState.CondMet = ExprValue;
2002 TheCondState.Ignore = !TheCondState.CondMet;
2008 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2010 TheCondStack.push_back(TheCondState);
2011 TheCondState.TheCond = AsmCond::IfCond;
2013 if (TheCondState.Ignore) {
2014 EatToEndOfStatement();
2016 if (ParseIdentifier(Name))
2017 return TokError("expected identifier after '.ifdef'");
2021 MCSymbol *Sym = getContext().LookupSymbol(Name);
2024 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2026 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2027 TheCondState.Ignore = !TheCondState.CondMet;
2033 /// ParseDirectiveElseIf
2034 /// ::= .elseif expression
2035 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2036 if (TheCondState.TheCond != AsmCond::IfCond &&
2037 TheCondState.TheCond != AsmCond::ElseIfCond)
2038 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2040 TheCondState.TheCond = AsmCond::ElseIfCond;
2042 bool LastIgnoreState = false;
2043 if (!TheCondStack.empty())
2044 LastIgnoreState = TheCondStack.back().Ignore;
2045 if (LastIgnoreState || TheCondState.CondMet) {
2046 TheCondState.Ignore = true;
2047 EatToEndOfStatement();
2051 if (ParseAbsoluteExpression(ExprValue))
2054 if (getLexer().isNot(AsmToken::EndOfStatement))
2055 return TokError("unexpected token in '.elseif' directive");
2058 TheCondState.CondMet = ExprValue;
2059 TheCondState.Ignore = !TheCondState.CondMet;
2065 /// ParseDirectiveElse
2067 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2068 if (getLexer().isNot(AsmToken::EndOfStatement))
2069 return TokError("unexpected token in '.else' directive");
2073 if (TheCondState.TheCond != AsmCond::IfCond &&
2074 TheCondState.TheCond != AsmCond::ElseIfCond)
2075 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2077 TheCondState.TheCond = AsmCond::ElseCond;
2078 bool LastIgnoreState = false;
2079 if (!TheCondStack.empty())
2080 LastIgnoreState = TheCondStack.back().Ignore;
2081 if (LastIgnoreState || TheCondState.CondMet)
2082 TheCondState.Ignore = true;
2084 TheCondState.Ignore = false;
2089 /// ParseDirectiveEndIf
2091 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2092 if (getLexer().isNot(AsmToken::EndOfStatement))
2093 return TokError("unexpected token in '.endif' directive");
2097 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2098 TheCondStack.empty())
2099 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2101 if (!TheCondStack.empty()) {
2102 TheCondState = TheCondStack.back();
2103 TheCondStack.pop_back();
2109 /// ParseDirectiveFile
2110 /// ::= .file [number] string
2111 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2112 // FIXME: I'm not sure what this is.
2113 int64_t FileNumber = -1;
2114 SMLoc FileNumberLoc = getLexer().getLoc();
2115 if (getLexer().is(AsmToken::Integer)) {
2116 FileNumber = getTok().getIntVal();
2120 return TokError("file number less than one");
2123 if (getLexer().isNot(AsmToken::String))
2124 return TokError("unexpected token in '.file' directive");
2126 StringRef Filename = getTok().getString();
2127 Filename = Filename.substr(1, Filename.size()-2);
2130 if (getLexer().isNot(AsmToken::EndOfStatement))
2131 return TokError("unexpected token in '.file' directive");
2133 if (FileNumber == -1)
2134 getStreamer().EmitFileDirective(Filename);
2136 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2137 Error(FileNumberLoc, "file number already allocated");
2143 /// ParseDirectiveLine
2144 /// ::= .line [number]
2145 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2146 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2147 if (getLexer().isNot(AsmToken::Integer))
2148 return TokError("unexpected token in '.line' directive");
2150 int64_t LineNumber = getTok().getIntVal();
2154 // FIXME: Do something with the .line.
2157 if (getLexer().isNot(AsmToken::EndOfStatement))
2158 return TokError("unexpected token in '.line' directive");
2164 /// ParseDirectiveLoc
2165 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2166 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2167 /// The first number is a file number, must have been previously assigned with
2168 /// a .file directive, the second number is the line number and optionally the
2169 /// third number is a column position (zero if not specified). The remaining
2170 /// optional items are .loc sub-directives.
2171 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2173 if (getLexer().isNot(AsmToken::Integer))
2174 return TokError("unexpected token in '.loc' directive");
2175 int64_t FileNumber = getTok().getIntVal();
2177 return TokError("file number less than one in '.loc' directive");
2178 if (!getContext().isValidDwarfFileNumber(FileNumber))
2179 return TokError("unassigned file number in '.loc' directive");
2182 int64_t LineNumber = 0;
2183 if (getLexer().is(AsmToken::Integer)) {
2184 LineNumber = getTok().getIntVal();
2186 return TokError("line number less than one in '.loc' directive");
2190 int64_t ColumnPos = 0;
2191 if (getLexer().is(AsmToken::Integer)) {
2192 ColumnPos = getTok().getIntVal();
2194 return TokError("column position less than zero in '.loc' directive");
2198 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2200 int64_t Discriminator = 0;
2201 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2203 if (getLexer().is(AsmToken::EndOfStatement))
2207 SMLoc Loc = getTok().getLoc();
2208 if (getParser().ParseIdentifier(Name))
2209 return TokError("unexpected token in '.loc' directive");
2211 if (Name == "basic_block")
2212 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2213 else if (Name == "prologue_end")
2214 Flags |= DWARF2_FLAG_PROLOGUE_END;
2215 else if (Name == "epilogue_begin")
2216 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2217 else if (Name == "is_stmt") {
2218 SMLoc Loc = getTok().getLoc();
2219 const MCExpr *Value;
2220 if (getParser().ParseExpression(Value))
2222 // The expression must be the constant 0 or 1.
2223 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2224 int Value = MCE->getValue();
2226 Flags &= ~DWARF2_FLAG_IS_STMT;
2227 else if (Value == 1)
2228 Flags |= DWARF2_FLAG_IS_STMT;
2230 return Error(Loc, "is_stmt value not 0 or 1");
2233 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2236 else if (Name == "isa") {
2237 SMLoc Loc = getTok().getLoc();
2238 const MCExpr *Value;
2239 if (getParser().ParseExpression(Value))
2241 // The expression must be a constant greater or equal to 0.
2242 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2243 int Value = MCE->getValue();
2245 return Error(Loc, "isa number less than zero");
2249 return Error(Loc, "isa number not a constant value");
2252 else if (Name == "discriminator") {
2253 if (getParser().ParseAbsoluteExpression(Discriminator))
2257 return Error(Loc, "unknown sub-directive in '.loc' directive");
2260 if (getLexer().is(AsmToken::EndOfStatement))
2265 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2266 Isa, Discriminator);
2271 /// ParseDirectiveStabs
2272 /// ::= .stabs string, number, number, number
2273 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2274 SMLoc DirectiveLoc) {
2275 return TokError("unsupported directive '" + Directive + "'");
2278 /// ParseDirectiveCFIStartProc
2279 /// ::= .cfi_startproc
2280 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2281 SMLoc DirectiveLoc) {
2282 return getStreamer().EmitCFIStartProc();
2285 /// ParseDirectiveCFIEndProc
2286 /// ::= .cfi_endproc
2287 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2288 return getStreamer().EmitCFIEndProc();
2291 /// ParseRegisterOrRegisterNumber - parse register name or number.
2292 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2293 SMLoc DirectiveLoc) {
2296 if (getLexer().is(AsmToken::Percent)) {
2297 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2300 Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2302 return getParser().ParseAbsoluteExpression(Register);
2307 /// ParseDirectiveCFIDefCfa
2308 /// ::= .cfi_def_cfa register, offset
2309 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2310 SMLoc DirectiveLoc) {
2311 int64_t Register = 0;
2312 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2315 if (getLexer().isNot(AsmToken::Comma))
2316 return TokError("unexpected token in directive");
2320 if (getParser().ParseAbsoluteExpression(Offset))
2323 return getStreamer().EmitCFIDefCfa(Register, Offset);
2326 /// ParseDirectiveCFIDefCfaOffset
2327 /// ::= .cfi_def_cfa_offset offset
2328 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2329 SMLoc DirectiveLoc) {
2331 if (getParser().ParseAbsoluteExpression(Offset))
2334 getParser().setLastOffset(Offset);
2336 return getStreamer().EmitCFIDefCfaOffset(Offset);
2339 /// ParseDirectiveCFIAdjustCfaOffset
2340 /// ::= .cfi_adjust_cfa_offset adjustment
2341 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2342 SMLoc DirectiveLoc) {
2343 int64_t Adjustment = 0;
2344 if (getParser().ParseAbsoluteExpression(Adjustment))
2347 int64_t Offset = getParser().adjustLastOffset(Adjustment);
2349 return getStreamer().EmitCFIDefCfaOffset(Offset);
2352 /// ParseDirectiveCFIDefCfaRegister
2353 /// ::= .cfi_def_cfa_register register
2354 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2355 SMLoc DirectiveLoc) {
2356 int64_t Register = 0;
2357 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2360 return getStreamer().EmitCFIDefCfaRegister(Register);
2363 /// ParseDirectiveCFIOffset
2364 /// ::= .cfi_offset register, offset
2365 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2366 int64_t Register = 0;
2369 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2372 if (getLexer().isNot(AsmToken::Comma))
2373 return TokError("unexpected token in directive");
2376 if (getParser().ParseAbsoluteExpression(Offset))
2379 return getStreamer().EmitCFIOffset(Register, Offset);
2382 /// ParseDirectiveCFIRelOffset
2383 /// ::= .cfi_rel_offset register, offset
2384 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2385 SMLoc DirectiveLoc) {
2386 int64_t Register = 0;
2388 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2391 if (getLexer().isNot(AsmToken::Comma))
2392 return TokError("unexpected token in directive");
2396 if (getParser().ParseAbsoluteExpression(Offset))
2399 Offset -= getParser().getLastOffset();
2401 return getStreamer().EmitCFIOffset(Register, Offset);
2404 static bool isValidEncoding(int64_t Encoding) {
2405 if (Encoding & ~0xff)
2408 if (Encoding == dwarf::DW_EH_PE_omit)
2411 const unsigned Format = Encoding & 0xf;
2412 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2413 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2414 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2415 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2418 const unsigned Application = Encoding & 0x70;
2419 if (Application != dwarf::DW_EH_PE_absptr &&
2420 Application != dwarf::DW_EH_PE_pcrel)
2426 /// ParseDirectiveCFIPersonalityOrLsda
2427 /// ::= .cfi_personality encoding, [symbol_name]
2428 /// ::= .cfi_lsda encoding, [symbol_name]
2429 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2430 SMLoc DirectiveLoc) {
2431 int64_t Encoding = 0;
2432 if (getParser().ParseAbsoluteExpression(Encoding))
2434 if (Encoding == dwarf::DW_EH_PE_omit)
2437 if (!isValidEncoding(Encoding))
2438 return TokError("unsupported encoding.");
2440 if (getLexer().isNot(AsmToken::Comma))
2441 return TokError("unexpected token in directive");
2445 if (getParser().ParseIdentifier(Name))
2446 return TokError("expected identifier in directive");
2448 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2450 if (IDVal == ".cfi_personality")
2451 return getStreamer().EmitCFIPersonality(Sym, Encoding);
2453 assert(IDVal == ".cfi_lsda");
2454 return getStreamer().EmitCFILsda(Sym, Encoding);
2458 /// ParseDirectiveCFIRememberState
2459 /// ::= .cfi_remember_state
2460 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2461 SMLoc DirectiveLoc) {
2462 return getStreamer().EmitCFIRememberState();
2465 /// ParseDirectiveCFIRestoreState
2466 /// ::= .cfi_remember_state
2467 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2468 SMLoc DirectiveLoc) {
2469 return getStreamer().EmitCFIRestoreState();
2472 /// ParseDirectiveMacrosOnOff
2475 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2476 SMLoc DirectiveLoc) {
2477 if (getLexer().isNot(AsmToken::EndOfStatement))
2478 return Error(getLexer().getLoc(),
2479 "unexpected token in '" + Directive + "' directive");
2481 getParser().MacrosEnabled = Directive == ".macros_on";
2486 /// ParseDirectiveMacro
2488 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2489 SMLoc DirectiveLoc) {
2491 if (getParser().ParseIdentifier(Name))
2492 return TokError("expected identifier in directive");
2494 if (getLexer().isNot(AsmToken::EndOfStatement))
2495 return TokError("unexpected token in '.macro' directive");
2497 // Eat the end of statement.
2500 AsmToken EndToken, StartToken = getTok();
2502 // Lex the macro definition.
2504 // Check whether we have reached the end of the file.
2505 if (getLexer().is(AsmToken::Eof))
2506 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2508 // Otherwise, check whether we have reach the .endmacro.
2509 if (getLexer().is(AsmToken::Identifier) &&
2510 (getTok().getIdentifier() == ".endm" ||
2511 getTok().getIdentifier() == ".endmacro")) {
2512 EndToken = getTok();
2514 if (getLexer().isNot(AsmToken::EndOfStatement))
2515 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2520 // Otherwise, scan til the end of the statement.
2521 getParser().EatToEndOfStatement();
2524 if (getParser().MacroMap.lookup(Name)) {
2525 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2528 const char *BodyStart = StartToken.getLoc().getPointer();
2529 const char *BodyEnd = EndToken.getLoc().getPointer();
2530 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2531 getParser().MacroMap[Name] = new Macro(Name, Body);
2535 /// ParseDirectiveEndMacro
2538 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2539 SMLoc DirectiveLoc) {
2540 if (getLexer().isNot(AsmToken::EndOfStatement))
2541 return TokError("unexpected token in '" + Directive + "' directive");
2543 // If we are inside a macro instantiation, terminate the current
2545 if (!getParser().ActiveMacros.empty()) {
2546 getParser().HandleMacroExit();
2550 // Otherwise, this .endmacro is a stray entry in the file; well formed
2551 // .endmacro directives are handled during the macro definition parsing.
2552 return TokError("unexpected '" + Directive + "' in file, "
2553 "no current macro definition");
2556 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2557 getParser().CheckForValidSection();
2559 const MCExpr *Value;
2561 if (getParser().ParseExpression(Value))
2564 if (getLexer().isNot(AsmToken::EndOfStatement))
2565 return TokError("unexpected token in directive");
2567 if (DirName[1] == 's')
2568 getStreamer().EmitSLEB128Value(Value);
2570 getStreamer().EmitULEB128Value(Value);
2576 /// \brief Create an MCAsmParser instance.
2577 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2578 MCContext &C, MCStreamer &Out,
2579 const MCAsmInfo &MAI) {
2580 return new AsmParser(T, SM, C, Out, MAI);