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"
40 /// \brief Helper class for tracking macro definitions.
46 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
49 /// \brief Helper class for storing information about an active macro
51 struct MacroInstantiation {
52 /// The macro being instantiated.
53 const Macro *TheMacro;
55 /// The macro instantiation with substitutions.
56 MemoryBuffer *Instantiation;
58 /// The location of the instantiation.
59 SMLoc InstantiationLoc;
61 /// The location where parsing should resume upon instantiation completion.
65 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
66 const std::vector<std::vector<AsmToken> > &A);
69 /// \brief The concrete assembly parser instance.
70 class AsmParser : public MCAsmParser {
71 friend class GenericAsmParser;
73 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
74 void operator=(const AsmParser &); // DO NOT IMPLEMENT
80 MCAsmParserExtension *GenericParser;
81 MCAsmParserExtension *PlatformParser;
83 /// This is the current buffer index we're lexing from as managed by the
88 std::vector<AsmCond> TheCondStack;
90 /// DirectiveMap - This is a table handlers for directives. Each handler is
91 /// invoked after the directive identifier is read and is responsible for
92 /// parsing and validating the rest of the directive. The handler is passed
93 /// in the directive name and the location of the directive keyword.
94 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
96 /// MacroMap - Map of currently defined macros.
97 StringMap<Macro*> MacroMap;
99 /// ActiveMacros - Stack of active macro instantiations.
100 std::vector<MacroInstantiation*> ActiveMacros;
102 /// Boolean tracking whether macro substitution is enabled.
103 unsigned MacrosEnabled : 1;
105 /// Flag tracking whether any errors have been encountered.
106 unsigned HadError : 1;
109 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
110 const MCAsmInfo &MAI);
113 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
115 void AddDirectiveHandler(MCAsmParserExtension *Object,
117 DirectiveHandler Handler) {
118 DirectiveMap[Directive] = std::make_pair(Object, Handler);
122 /// @name MCAsmParser Interface
125 virtual SourceMgr &getSourceManager() { return SrcMgr; }
126 virtual MCAsmLexer &getLexer() { return Lexer; }
127 virtual MCContext &getContext() { return Ctx; }
128 virtual MCStreamer &getStreamer() { return Out; }
130 virtual void Warning(SMLoc L, const Twine &Meg);
131 virtual bool Error(SMLoc L, const Twine &Msg);
133 const AsmToken &Lex();
135 bool ParseExpression(const MCExpr *&Res);
136 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
137 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
138 virtual bool ParseAbsoluteExpression(int64_t &Res);
143 void CheckForValidSection();
145 bool ParseStatement();
147 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
148 void HandleMacroExit();
150 void PrintMacroInstantiations();
151 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
152 SrcMgr.PrintMessage(Loc, Msg, Type);
155 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
156 bool EnterIncludeFile(const std::string &Filename);
158 /// \brief Reset the current lexer position to that given by \arg Loc. The
159 /// current token is not set; clients should ensure Lex() is called
161 void JumpToLoc(SMLoc Loc);
163 void EatToEndOfStatement();
165 /// \brief Parse up to the end of statement and a return the contents from the
166 /// current token until the end of the statement; the current token on exit
167 /// will be either the EndOfStatement or EOF.
168 StringRef ParseStringToEndOfStatement();
170 bool ParseAssignment(StringRef Name);
172 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
173 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
174 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
176 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
177 /// and set \arg Res to the identifier contents.
178 bool ParseIdentifier(StringRef &Res);
180 // Directive Parsing.
182 // ".ascii", ".asciiz", ".string"
183 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
184 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
185 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
186 bool ParseDirectiveFill(); // ".fill"
187 bool ParseDirectiveSpace(); // ".space"
188 bool ParseDirectiveZero(); // ".zero"
189 bool ParseDirectiveSet(StringRef IDVal); // ".set" or ".equ"
190 bool ParseDirectiveOrg(); // ".org"
191 // ".align{,32}", ".p2align{,w,l}"
192 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
194 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
195 /// accepts a single symbol (which should be a label or an external).
196 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
198 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
200 bool ParseDirectiveAbort(); // ".abort"
201 bool ParseDirectiveInclude(); // ".include"
203 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
204 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
205 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
206 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
208 /// ParseEscapedString - Parse the current token as a string which may include
209 /// escaped characters and return the string contents.
210 bool ParseEscapedString(std::string &Data);
212 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
213 MCSymbolRefExpr::VariantKind Variant);
216 /// \brief Generic implementations of directive handling, etc. which is shared
217 /// (or the default, at least) for all assembler parser.
218 class GenericAsmParser : public MCAsmParserExtension {
219 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
220 void AddDirectiveHandler(StringRef Directive) {
221 getParser().AddDirectiveHandler(this, Directive,
222 HandleDirective<GenericAsmParser, Handler>);
226 GenericAsmParser() {}
228 AsmParser &getParser() {
229 return (AsmParser&) this->MCAsmParserExtension::getParser();
232 virtual void Initialize(MCAsmParser &Parser) {
233 // Call the base implementation.
234 this->MCAsmParserExtension::Initialize(Parser);
236 // Debugging directives.
237 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
238 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
239 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
243 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
245 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
247 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
248 ".cfi_def_cfa_offset");
249 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
250 ".cfi_def_cfa_register");
251 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
254 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
256 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
258 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
260 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
263 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
265 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
268 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
269 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
275 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
276 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
277 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
278 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
279 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
280 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
281 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
282 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
283 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
284 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
285 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
286 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
288 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
289 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
290 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
292 bool ParseDirectiveLEB128(StringRef, SMLoc);
299 extern MCAsmParserExtension *createDarwinAsmParser();
300 extern MCAsmParserExtension *createELFAsmParser();
301 extern MCAsmParserExtension *createCOFFAsmParser();
305 enum { DEFAULT_ADDRSPACE = 0 };
307 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
308 MCStreamer &_Out, const MCAsmInfo &_MAI)
309 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
310 GenericParser(new GenericAsmParser), PlatformParser(0),
311 CurBuffer(0), MacrosEnabled(true) {
312 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
314 // Initialize the generic parser.
315 GenericParser->Initialize(*this);
317 // Initialize the platform / file format parser.
319 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
321 if (_MAI.hasMicrosoftFastStdCallMangling()) {
322 PlatformParser = createCOFFAsmParser();
323 PlatformParser->Initialize(*this);
324 } else if (_MAI.hasSubsectionsViaSymbols()) {
325 PlatformParser = createDarwinAsmParser();
326 PlatformParser->Initialize(*this);
328 PlatformParser = createELFAsmParser();
329 PlatformParser->Initialize(*this);
333 AsmParser::~AsmParser() {
334 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
336 // Destroy any macros.
337 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
338 ie = MacroMap.end(); it != ie; ++it)
339 delete it->getValue();
341 delete PlatformParser;
342 delete GenericParser;
345 void AsmParser::PrintMacroInstantiations() {
346 // Print the active macro instantiation stack.
347 for (std::vector<MacroInstantiation*>::const_reverse_iterator
348 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
349 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
353 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
354 PrintMessage(L, Msg, "warning");
355 PrintMacroInstantiations();
358 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
360 PrintMessage(L, Msg, "error");
361 PrintMacroInstantiations();
365 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
366 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
372 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
377 void AsmParser::JumpToLoc(SMLoc Loc) {
378 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
379 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
382 const AsmToken &AsmParser::Lex() {
383 const AsmToken *tok = &Lexer.Lex();
385 if (tok->is(AsmToken::Eof)) {
386 // If this is the end of an included file, pop the parent file off the
388 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
389 if (ParentIncludeLoc != SMLoc()) {
390 JumpToLoc(ParentIncludeLoc);
395 if (tok->is(AsmToken::Error))
396 Error(Lexer.getErrLoc(), Lexer.getErr());
401 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
402 // Create the initial section, if requested.
403 if (!NoInitialTextSection)
410 AsmCond StartingCondState = TheCondState;
412 // While we have input, parse each statement.
413 while (Lexer.isNot(AsmToken::Eof)) {
414 if (!ParseStatement()) continue;
416 // We had an error, validate that one was emitted and recover by skipping to
418 assert(HadError && "Parse statement returned an error, but none emitted!");
419 EatToEndOfStatement();
422 if (TheCondState.TheCond != StartingCondState.TheCond ||
423 TheCondState.Ignore != StartingCondState.Ignore)
424 return TokError("unmatched .ifs or .elses");
426 // Check to see there are no empty DwarfFile slots.
427 const std::vector<MCDwarfFile *> &MCDwarfFiles =
428 getContext().getMCDwarfFiles();
429 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
430 if (!MCDwarfFiles[i])
431 TokError("unassigned file number: " + Twine(i) + " for .file directives");
434 // Finalize the output stream if there are no errors and if the client wants
436 if (!HadError && !NoFinalize)
442 void AsmParser::CheckForValidSection() {
443 if (!getStreamer().getCurrentSection()) {
444 TokError("expected section directive before assembly directive");
445 Out.SwitchSection(Ctx.getMachOSection(
447 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
448 0, SectionKind::getText()));
452 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
453 void AsmParser::EatToEndOfStatement() {
454 while (Lexer.isNot(AsmToken::EndOfStatement) &&
455 Lexer.isNot(AsmToken::Eof))
459 if (Lexer.is(AsmToken::EndOfStatement))
463 StringRef AsmParser::ParseStringToEndOfStatement() {
464 const char *Start = getTok().getLoc().getPointer();
466 while (Lexer.isNot(AsmToken::EndOfStatement) &&
467 Lexer.isNot(AsmToken::Eof))
470 const char *End = getTok().getLoc().getPointer();
471 return StringRef(Start, End - Start);
474 /// ParseParenExpr - Parse a paren expression and return it.
475 /// NOTE: This assumes the leading '(' has already been consumed.
477 /// parenexpr ::= expr)
479 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
480 if (ParseExpression(Res)) return true;
481 if (Lexer.isNot(AsmToken::RParen))
482 return TokError("expected ')' in parentheses expression");
483 EndLoc = Lexer.getLoc();
488 /// ParsePrimaryExpr - Parse a primary expression and return it.
489 /// primaryexpr ::= (parenexpr
490 /// primaryexpr ::= symbol
491 /// primaryexpr ::= number
492 /// primaryexpr ::= '.'
493 /// primaryexpr ::= ~,+,- primaryexpr
494 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
495 switch (Lexer.getKind()) {
497 return TokError("unknown token in expression");
498 case AsmToken::Exclaim:
499 Lex(); // Eat the operator.
500 if (ParsePrimaryExpr(Res, EndLoc))
502 Res = MCUnaryExpr::CreateLNot(Res, getContext());
504 case AsmToken::Dollar:
505 case AsmToken::String:
506 case AsmToken::Identifier: {
507 EndLoc = Lexer.getLoc();
509 StringRef Identifier;
510 if (ParseIdentifier(Identifier))
513 // This is a symbol reference.
514 std::pair<StringRef, StringRef> Split = Identifier.split('@');
515 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
517 // Lookup the symbol variant if used.
518 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
519 if (Split.first.size() != Identifier.size()) {
520 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
521 if (Variant == MCSymbolRefExpr::VK_Invalid) {
522 Variant = MCSymbolRefExpr::VK_None;
523 TokError("invalid variant '" + Split.second + "'");
527 // If this is an absolute variable reference, substitute it now to preserve
528 // semantics in the face of reassignment.
529 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
531 return Error(EndLoc, "unexpected modifier on variable reference");
533 Res = Sym->getVariableValue();
537 // Otherwise create a symbol ref.
538 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
541 case AsmToken::Integer: {
542 SMLoc Loc = getTok().getLoc();
543 int64_t IntVal = getTok().getIntVal();
544 Res = MCConstantExpr::Create(IntVal, getContext());
545 EndLoc = Lexer.getLoc();
547 // Look for 'b' or 'f' following an Integer as a directional label
548 if (Lexer.getKind() == AsmToken::Identifier) {
549 StringRef IDVal = getTok().getString();
550 if (IDVal == "f" || IDVal == "b"){
551 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
552 IDVal == "f" ? 1 : 0);
553 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
555 if(IDVal == "b" && Sym->isUndefined())
556 return Error(Loc, "invalid reference to undefined symbol");
557 EndLoc = Lexer.getLoc();
558 Lex(); // Eat identifier.
563 case AsmToken::Dot: {
564 // This is a '.' reference, which references the current PC. Emit a
565 // temporary label to the streamer and refer to it.
566 MCSymbol *Sym = Ctx.CreateTempSymbol();
568 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
569 EndLoc = Lexer.getLoc();
570 Lex(); // Eat identifier.
574 case AsmToken::LParen:
575 Lex(); // Eat the '('.
576 return ParseParenExpr(Res, EndLoc);
577 case AsmToken::Minus:
578 Lex(); // Eat the operator.
579 if (ParsePrimaryExpr(Res, EndLoc))
581 Res = MCUnaryExpr::CreateMinus(Res, getContext());
584 Lex(); // Eat the operator.
585 if (ParsePrimaryExpr(Res, EndLoc))
587 Res = MCUnaryExpr::CreatePlus(Res, getContext());
589 case AsmToken::Tilde:
590 Lex(); // Eat the operator.
591 if (ParsePrimaryExpr(Res, EndLoc))
593 Res = MCUnaryExpr::CreateNot(Res, getContext());
598 bool AsmParser::ParseExpression(const MCExpr *&Res) {
600 return ParseExpression(Res, EndLoc);
604 AsmParser::ApplyModifierToExpr(const MCExpr *E,
605 MCSymbolRefExpr::VariantKind Variant) {
606 // Recurse over the given expression, rebuilding it to apply the given variant
607 // if there is exactly one symbol.
608 switch (E->getKind()) {
610 case MCExpr::Constant:
613 case MCExpr::SymbolRef: {
614 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
616 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
617 TokError("invalid variant on expression '" +
618 getTok().getIdentifier() + "' (already modified)");
622 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
625 case MCExpr::Unary: {
626 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
627 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
630 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
633 case MCExpr::Binary: {
634 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
635 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
636 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
641 if (!LHS) LHS = BE->getLHS();
642 if (!RHS) RHS = BE->getRHS();
644 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
648 assert(0 && "Invalid expression kind!");
652 /// ParseExpression - Parse an expression and return it.
654 /// expr ::= expr +,- expr -> lowest.
655 /// expr ::= expr |,^,&,! expr -> middle.
656 /// expr ::= expr *,/,%,<<,>> expr -> highest.
657 /// expr ::= primaryexpr
659 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
660 // Parse the expression.
662 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
665 // As a special case, we support 'a op b @ modifier' by rewriting the
666 // expression to include the modifier. This is inefficient, but in general we
667 // expect users to use 'a@modifier op b'.
668 if (Lexer.getKind() == AsmToken::At) {
671 if (Lexer.isNot(AsmToken::Identifier))
672 return TokError("unexpected symbol modifier following '@'");
674 MCSymbolRefExpr::VariantKind Variant =
675 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
676 if (Variant == MCSymbolRefExpr::VK_Invalid)
677 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
679 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
681 return TokError("invalid modifier '" + getTok().getIdentifier() +
682 "' (no symbols present)");
690 // Try to constant fold it up front, if possible.
692 if (Res->EvaluateAsAbsolute(Value))
693 Res = MCConstantExpr::Create(Value, getContext());
698 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
700 return ParseParenExpr(Res, EndLoc) ||
701 ParseBinOpRHS(1, Res, EndLoc);
704 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
707 SMLoc StartLoc = Lexer.getLoc();
708 if (ParseExpression(Expr))
711 if (!Expr->EvaluateAsAbsolute(Res))
712 return Error(StartLoc, "expected absolute expression");
717 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
718 MCBinaryExpr::Opcode &Kind) {
721 return 0; // not a binop.
723 // Lowest Precedence: &&, ||, @
724 case AsmToken::AmpAmp:
725 Kind = MCBinaryExpr::LAnd;
727 case AsmToken::PipePipe:
728 Kind = MCBinaryExpr::LOr;
732 // Low Precedence: |, &, ^
734 // FIXME: gas seems to support '!' as an infix operator?
736 Kind = MCBinaryExpr::Or;
738 case AsmToken::Caret:
739 Kind = MCBinaryExpr::Xor;
742 Kind = MCBinaryExpr::And;
745 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
746 case AsmToken::EqualEqual:
747 Kind = MCBinaryExpr::EQ;
749 case AsmToken::ExclaimEqual:
750 case AsmToken::LessGreater:
751 Kind = MCBinaryExpr::NE;
754 Kind = MCBinaryExpr::LT;
756 case AsmToken::LessEqual:
757 Kind = MCBinaryExpr::LTE;
759 case AsmToken::Greater:
760 Kind = MCBinaryExpr::GT;
762 case AsmToken::GreaterEqual:
763 Kind = MCBinaryExpr::GTE;
766 // High Intermediate Precedence: +, -
768 Kind = MCBinaryExpr::Add;
770 case AsmToken::Minus:
771 Kind = MCBinaryExpr::Sub;
774 // Highest Precedence: *, /, %, <<, >>
776 Kind = MCBinaryExpr::Mul;
778 case AsmToken::Slash:
779 Kind = MCBinaryExpr::Div;
781 case AsmToken::Percent:
782 Kind = MCBinaryExpr::Mod;
784 case AsmToken::LessLess:
785 Kind = MCBinaryExpr::Shl;
787 case AsmToken::GreaterGreater:
788 Kind = MCBinaryExpr::Shr;
794 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
795 /// Res contains the LHS of the expression on input.
796 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
799 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
800 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
802 // If the next token is lower precedence than we are allowed to eat, return
803 // successfully with what we ate already.
804 if (TokPrec < Precedence)
809 // Eat the next primary expression.
811 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
813 // If BinOp binds less tightly with RHS than the operator after RHS, let
814 // the pending operator take RHS as its LHS.
815 MCBinaryExpr::Opcode Dummy;
816 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
817 if (TokPrec < NextTokPrec) {
818 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
821 // Merge LHS and RHS according to operator.
822 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
830 /// ::= EndOfStatement
831 /// ::= Label* Directive ...Operands... EndOfStatement
832 /// ::= Label* Identifier OperandList* EndOfStatement
833 bool AsmParser::ParseStatement() {
834 if (Lexer.is(AsmToken::EndOfStatement)) {
840 // Statements always start with an identifier or are a full line comment.
841 AsmToken ID = getTok();
842 SMLoc IDLoc = ID.getLoc();
844 int64_t LocalLabelVal = -1;
845 // A full line comment is a '#' as the first token.
846 if (Lexer.is(AsmToken::Hash)) {
847 EatToEndOfStatement();
850 // Allow an integer followed by a ':' as a directional local label.
851 if (Lexer.is(AsmToken::Integer)) {
852 LocalLabelVal = getTok().getIntVal();
853 if (LocalLabelVal < 0) {
854 if (!TheCondState.Ignore)
855 return TokError("unexpected token at start of statement");
859 IDVal = getTok().getString();
860 Lex(); // Consume the integer token to be used as an identifier token.
861 if (Lexer.getKind() != AsmToken::Colon) {
862 if (!TheCondState.Ignore)
863 return TokError("unexpected token at start of statement");
867 else if (ParseIdentifier(IDVal)) {
868 if (!TheCondState.Ignore)
869 return TokError("unexpected token at start of statement");
873 // Handle conditional assembly here before checking for skipping. We
874 // have to do this so that .endif isn't skipped in a ".if 0" block for
877 return ParseDirectiveIf(IDLoc);
878 if (IDVal == ".elseif")
879 return ParseDirectiveElseIf(IDLoc);
880 if (IDVal == ".else")
881 return ParseDirectiveElse(IDLoc);
882 if (IDVal == ".endif")
883 return ParseDirectiveEndIf(IDLoc);
885 // If we are in a ".if 0" block, ignore this statement.
886 if (TheCondState.Ignore) {
887 EatToEndOfStatement();
891 // FIXME: Recurse on local labels?
893 // See what kind of statement we have.
894 switch (Lexer.getKind()) {
895 case AsmToken::Colon: {
896 CheckForValidSection();
898 // identifier ':' -> Label.
901 // Diagnose attempt to use a variable as a label.
903 // FIXME: Diagnostics. Note the location of the definition as a label.
904 // FIXME: This doesn't diagnose assignment to a symbol which has been
905 // implicitly marked as external.
907 if (LocalLabelVal == -1)
908 Sym = getContext().GetOrCreateSymbol(IDVal);
910 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
911 if (!Sym->isUndefined() || Sym->isVariable())
912 return Error(IDLoc, "invalid symbol redefinition");
917 // Consume any end of statement token, if present, to avoid spurious
918 // AddBlankLine calls().
919 if (Lexer.is(AsmToken::EndOfStatement)) {
921 if (Lexer.is(AsmToken::Eof))
925 return ParseStatement();
928 case AsmToken::Equal:
929 // identifier '=' ... -> assignment statement
932 return ParseAssignment(IDVal);
934 default: // Normal instruction or directive.
938 // If macros are enabled, check to see if this is a macro instantiation.
940 if (const Macro *M = MacroMap.lookup(IDVal))
941 return HandleMacroEntry(IDVal, IDLoc, M);
943 // Otherwise, we have a normal instruction or directive.
944 if (IDVal[0] == '.') {
945 // Assembler features
946 if (IDVal == ".set" || IDVal == ".equ")
947 return ParseDirectiveSet(IDVal);
951 if (IDVal == ".ascii")
952 return ParseDirectiveAscii(IDVal, false);
953 if (IDVal == ".asciz" || IDVal == ".string")
954 return ParseDirectiveAscii(IDVal, true);
956 if (IDVal == ".byte")
957 return ParseDirectiveValue(1);
958 if (IDVal == ".short")
959 return ParseDirectiveValue(2);
960 if (IDVal == ".value")
961 return ParseDirectiveValue(2);
962 if (IDVal == ".2byte")
963 return ParseDirectiveValue(2);
964 if (IDVal == ".long")
965 return ParseDirectiveValue(4);
967 return ParseDirectiveValue(4);
968 if (IDVal == ".4byte")
969 return ParseDirectiveValue(4);
970 if (IDVal == ".quad")
971 return ParseDirectiveValue(8);
972 if (IDVal == ".8byte")
973 return ParseDirectiveValue(8);
974 if (IDVal == ".single")
975 return ParseDirectiveRealValue(APFloat::IEEEsingle);
976 if (IDVal == ".double")
977 return ParseDirectiveRealValue(APFloat::IEEEdouble);
979 if (IDVal == ".align") {
980 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
981 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
983 if (IDVal == ".align32") {
984 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
985 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
987 if (IDVal == ".balign")
988 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
989 if (IDVal == ".balignw")
990 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
991 if (IDVal == ".balignl")
992 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
993 if (IDVal == ".p2align")
994 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
995 if (IDVal == ".p2alignw")
996 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
997 if (IDVal == ".p2alignl")
998 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1000 if (IDVal == ".org")
1001 return ParseDirectiveOrg();
1003 if (IDVal == ".fill")
1004 return ParseDirectiveFill();
1005 if (IDVal == ".space")
1006 return ParseDirectiveSpace();
1007 if (IDVal == ".zero")
1008 return ParseDirectiveZero();
1010 // Symbol attribute directives
1012 if (IDVal == ".globl" || IDVal == ".global")
1013 return ParseDirectiveSymbolAttribute(MCSA_Global);
1014 // ELF only? Should it be here?
1015 if (IDVal == ".local")
1016 return ParseDirectiveSymbolAttribute(MCSA_Local);
1017 if (IDVal == ".hidden")
1018 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1019 if (IDVal == ".indirect_symbol")
1020 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1021 if (IDVal == ".internal")
1022 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1023 if (IDVal == ".lazy_reference")
1024 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1025 if (IDVal == ".no_dead_strip")
1026 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1027 if (IDVal == ".symbol_resolver")
1028 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1029 if (IDVal == ".private_extern")
1030 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1031 if (IDVal == ".protected")
1032 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1033 if (IDVal == ".reference")
1034 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1035 if (IDVal == ".weak")
1036 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1037 if (IDVal == ".weak_definition")
1038 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1039 if (IDVal == ".weak_reference")
1040 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1041 if (IDVal == ".weak_def_can_be_hidden")
1042 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1044 if (IDVal == ".comm")
1045 return ParseDirectiveComm(/*IsLocal=*/false);
1046 if (IDVal == ".lcomm")
1047 return ParseDirectiveComm(/*IsLocal=*/true);
1049 if (IDVal == ".abort")
1050 return ParseDirectiveAbort();
1051 if (IDVal == ".include")
1052 return ParseDirectiveInclude();
1054 // Look up the handler in the handler table.
1055 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1056 DirectiveMap.lookup(IDVal);
1058 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1060 // Target hook for parsing target specific directives.
1061 if (!getTargetParser().ParseDirective(ID))
1064 Warning(IDLoc, "ignoring directive for now");
1065 EatToEndOfStatement();
1069 CheckForValidSection();
1071 // Canonicalize the opcode to lower case.
1072 SmallString<128> Opcode;
1073 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1074 Opcode.push_back(tolower(IDVal[i]));
1076 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1077 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1080 // Dump the parsed representation, if requested.
1081 if (getShowParsedOperands()) {
1082 SmallString<256> Str;
1083 raw_svector_ostream OS(Str);
1084 OS << "parsed instruction: [";
1085 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1088 ParsedOperands[i]->dump(OS);
1092 PrintMessage(IDLoc, OS.str(), "note");
1095 // If parsing succeeded, match the instruction.
1097 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1100 // Free any parsed operands.
1101 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1102 delete ParsedOperands[i];
1104 // Don't skip the rest of the line, the instruction parser is responsible for
1109 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1110 const std::vector<std::vector<AsmToken> > &A)
1111 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1113 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1114 // to hold the macro body with substitutions.
1115 SmallString<256> Buf;
1116 raw_svector_ostream OS(Buf);
1118 StringRef Body = M->Body;
1119 while (!Body.empty()) {
1120 // Scan for the next substitution.
1121 std::size_t End = Body.size(), Pos = 0;
1122 for (; Pos != End; ++Pos) {
1123 // Check for a substitution or escape.
1124 if (Body[Pos] != '$' || Pos + 1 == End)
1127 char Next = Body[Pos + 1];
1128 if (Next == '$' || Next == 'n' || isdigit(Next))
1133 OS << Body.slice(0, Pos);
1135 // Check if we reached the end.
1139 switch (Body[Pos+1]) {
1145 // $n => number of arguments
1150 // $[0-9] => argument
1152 // Missing arguments are ignored.
1153 unsigned Index = Body[Pos+1] - '0';
1154 if (Index >= A.size())
1157 // Otherwise substitute with the token values, with spaces eliminated.
1158 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1159 ie = A[Index].end(); it != ie; ++it)
1160 OS << it->getString();
1165 // Update the scan point.
1166 Body = Body.substr(Pos + 2);
1169 // We include the .endmacro in the buffer as our queue to exit the macro
1171 OS << ".endmacro\n";
1173 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1176 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1178 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1179 // this, although we should protect against infinite loops.
1180 if (ActiveMacros.size() == 20)
1181 return TokError("macros cannot be nested more than 20 levels deep");
1183 // Parse the macro instantiation arguments.
1184 std::vector<std::vector<AsmToken> > MacroArguments;
1185 MacroArguments.push_back(std::vector<AsmToken>());
1186 unsigned ParenLevel = 0;
1188 if (Lexer.is(AsmToken::Eof))
1189 return TokError("unexpected token in macro instantiation");
1190 if (Lexer.is(AsmToken::EndOfStatement))
1193 // If we aren't inside parentheses and this is a comma, start a new token
1195 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1196 MacroArguments.push_back(std::vector<AsmToken>());
1198 // Adjust the current parentheses level.
1199 if (Lexer.is(AsmToken::LParen))
1201 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1204 // Append the token to the current argument list.
1205 MacroArguments.back().push_back(getTok());
1210 // Create the macro instantiation object and add to the current macro
1211 // instantiation stack.
1212 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1215 ActiveMacros.push_back(MI);
1217 // Jump to the macro instantiation and prime the lexer.
1218 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1219 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1225 void AsmParser::HandleMacroExit() {
1226 // Jump to the EndOfStatement we should return to, and consume it.
1227 JumpToLoc(ActiveMacros.back()->ExitLoc);
1230 // Pop the instantiation entry.
1231 delete ActiveMacros.back();
1232 ActiveMacros.pop_back();
1235 static void MarkUsed(const MCExpr *Value) {
1236 switch (Value->getKind()) {
1237 case MCExpr::Binary:
1238 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1239 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1241 case MCExpr::Target:
1242 case MCExpr::Constant:
1244 case MCExpr::SymbolRef: {
1245 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1249 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1254 bool AsmParser::ParseAssignment(StringRef Name) {
1255 // FIXME: Use better location, we should use proper tokens.
1256 SMLoc EqualLoc = Lexer.getLoc();
1258 const MCExpr *Value;
1259 if (ParseExpression(Value))
1264 if (Lexer.isNot(AsmToken::EndOfStatement))
1265 return TokError("unexpected token in assignment");
1267 // Eat the end of statement marker.
1270 // Validate that the LHS is allowed to be a variable (either it has not been
1271 // used as a symbol, or it is an absolute symbol).
1272 MCSymbol *Sym = getContext().LookupSymbol(Name);
1274 // Diagnose assignment to a label.
1276 // FIXME: Diagnostics. Note the location of the definition as a label.
1277 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1278 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1279 ; // Allow redefinitions of undefined symbols only used in directives.
1280 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1281 return Error(EqualLoc, "redefinition of '" + Name + "'");
1282 else if (!Sym->isVariable())
1283 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1284 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1285 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1288 // Don't count these checks as uses.
1289 Sym->setUsed(false);
1291 Sym = getContext().GetOrCreateSymbol(Name);
1293 // FIXME: Handle '.'.
1295 // Do the assignment.
1296 Out.EmitAssignment(Sym, Value);
1301 /// ParseIdentifier:
1304 bool AsmParser::ParseIdentifier(StringRef &Res) {
1305 // The assembler has relaxed rules for accepting identifiers, in particular we
1306 // allow things like '.globl $foo', which would normally be separate
1307 // tokens. At this level, we have already lexed so we cannot (currently)
1308 // handle this as a context dependent token, instead we detect adjacent tokens
1309 // and return the combined identifier.
1310 if (Lexer.is(AsmToken::Dollar)) {
1311 SMLoc DollarLoc = getLexer().getLoc();
1313 // Consume the dollar sign, and check for a following identifier.
1315 if (Lexer.isNot(AsmToken::Identifier))
1318 // We have a '$' followed by an identifier, make sure they are adjacent.
1319 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1322 // Construct the joined identifier and consume the token.
1323 Res = StringRef(DollarLoc.getPointer(),
1324 getTok().getIdentifier().size() + 1);
1329 if (Lexer.isNot(AsmToken::Identifier) &&
1330 Lexer.isNot(AsmToken::String))
1333 Res = getTok().getIdentifier();
1335 Lex(); // Consume the identifier token.
1340 /// ParseDirectiveSet:
1341 /// ::= .set identifier ',' expression
1342 bool AsmParser::ParseDirectiveSet(StringRef IDVal) {
1345 if (ParseIdentifier(Name))
1346 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1348 if (getLexer().isNot(AsmToken::Comma))
1349 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1352 return ParseAssignment(Name);
1355 bool AsmParser::ParseEscapedString(std::string &Data) {
1356 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1359 StringRef Str = getTok().getStringContents();
1360 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1361 if (Str[i] != '\\') {
1366 // Recognize escaped characters. Note that this escape semantics currently
1367 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1370 return TokError("unexpected backslash at end of string");
1372 // Recognize octal sequences.
1373 if ((unsigned) (Str[i] - '0') <= 7) {
1374 // Consume up to three octal characters.
1375 unsigned Value = Str[i] - '0';
1377 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1379 Value = Value * 8 + (Str[i] - '0');
1381 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1383 Value = Value * 8 + (Str[i] - '0');
1388 return TokError("invalid octal escape sequence (out of range)");
1390 Data += (unsigned char) Value;
1394 // Otherwise recognize individual escapes.
1397 // Just reject invalid escape sequences for now.
1398 return TokError("invalid escape sequence (unrecognized character)");
1400 case 'b': Data += '\b'; break;
1401 case 'f': Data += '\f'; break;
1402 case 'n': Data += '\n'; break;
1403 case 'r': Data += '\r'; break;
1404 case 't': Data += '\t'; break;
1405 case '"': Data += '"'; break;
1406 case '\\': Data += '\\'; break;
1413 /// ParseDirectiveAscii:
1414 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1415 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1416 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1417 CheckForValidSection();
1420 if (getLexer().isNot(AsmToken::String))
1421 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1424 if (ParseEscapedString(Data))
1427 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1429 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1433 if (getLexer().is(AsmToken::EndOfStatement))
1436 if (getLexer().isNot(AsmToken::Comma))
1437 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1446 /// ParseDirectiveValue
1447 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1448 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1449 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1450 CheckForValidSection();
1453 const MCExpr *Value;
1454 if (ParseExpression(Value))
1457 // Special case constant expressions to match code generator.
1458 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1459 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1461 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1463 if (getLexer().is(AsmToken::EndOfStatement))
1466 // FIXME: Improve diagnostic.
1467 if (getLexer().isNot(AsmToken::Comma))
1468 return TokError("unexpected token in directive");
1477 /// ParseDirectiveRealValue
1478 /// ::= (.single | .double) [ expression (, expression)* ]
1479 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1480 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1481 CheckForValidSection();
1484 // We don't truly support arithmetic on floating point expressions, so we
1485 // have to manually parse unary prefixes.
1487 if (getLexer().is(AsmToken::Minus)) {
1490 } else if (getLexer().is(AsmToken::Plus))
1493 if (getLexer().isNot(AsmToken::Integer) &&
1494 getLexer().isNot(AsmToken::Real))
1495 return TokError("unexpected token in directive");
1497 // Convert to an APFloat.
1498 APFloat Value(Semantics);
1499 if (Value.convertFromString(getTok().getString(),
1500 APFloat::rmNearestTiesToEven) ==
1501 APFloat::opInvalidOp)
1502 return TokError("invalid floating point literal");
1506 // Consume the numeric token.
1509 // Emit the value as an integer.
1510 APInt AsInt = Value.bitcastToAPInt();
1511 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1512 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1514 if (getLexer().is(AsmToken::EndOfStatement))
1517 if (getLexer().isNot(AsmToken::Comma))
1518 return TokError("unexpected token in directive");
1527 /// ParseDirectiveSpace
1528 /// ::= .space expression [ , expression ]
1529 bool AsmParser::ParseDirectiveSpace() {
1530 CheckForValidSection();
1533 if (ParseAbsoluteExpression(NumBytes))
1536 int64_t FillExpr = 0;
1537 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1538 if (getLexer().isNot(AsmToken::Comma))
1539 return TokError("unexpected token in '.space' directive");
1542 if (ParseAbsoluteExpression(FillExpr))
1545 if (getLexer().isNot(AsmToken::EndOfStatement))
1546 return TokError("unexpected token in '.space' directive");
1552 return TokError("invalid number of bytes in '.space' directive");
1554 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1555 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1560 /// ParseDirectiveZero
1561 /// ::= .zero expression
1562 bool AsmParser::ParseDirectiveZero() {
1563 CheckForValidSection();
1566 if (ParseAbsoluteExpression(NumBytes))
1570 if (getLexer().is(AsmToken::Comma)) {
1572 if (ParseAbsoluteExpression(Val))
1576 if (getLexer().isNot(AsmToken::EndOfStatement))
1577 return TokError("unexpected token in '.zero' directive");
1581 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1586 /// ParseDirectiveFill
1587 /// ::= .fill expression , expression , expression
1588 bool AsmParser::ParseDirectiveFill() {
1589 CheckForValidSection();
1592 if (ParseAbsoluteExpression(NumValues))
1595 if (getLexer().isNot(AsmToken::Comma))
1596 return TokError("unexpected token in '.fill' directive");
1600 if (ParseAbsoluteExpression(FillSize))
1603 if (getLexer().isNot(AsmToken::Comma))
1604 return TokError("unexpected token in '.fill' directive");
1608 if (ParseAbsoluteExpression(FillExpr))
1611 if (getLexer().isNot(AsmToken::EndOfStatement))
1612 return TokError("unexpected token in '.fill' directive");
1616 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1617 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1619 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1620 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1625 /// ParseDirectiveOrg
1626 /// ::= .org expression [ , expression ]
1627 bool AsmParser::ParseDirectiveOrg() {
1628 CheckForValidSection();
1630 const MCExpr *Offset;
1631 if (ParseExpression(Offset))
1634 // Parse optional fill expression.
1635 int64_t FillExpr = 0;
1636 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1637 if (getLexer().isNot(AsmToken::Comma))
1638 return TokError("unexpected token in '.org' directive");
1641 if (ParseAbsoluteExpression(FillExpr))
1644 if (getLexer().isNot(AsmToken::EndOfStatement))
1645 return TokError("unexpected token in '.org' directive");
1650 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1651 // has to be relative to the current section.
1652 getStreamer().EmitValueToOffset(Offset, FillExpr);
1657 /// ParseDirectiveAlign
1658 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1659 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1660 CheckForValidSection();
1662 SMLoc AlignmentLoc = getLexer().getLoc();
1664 if (ParseAbsoluteExpression(Alignment))
1668 bool HasFillExpr = false;
1669 int64_t FillExpr = 0;
1670 int64_t MaxBytesToFill = 0;
1671 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1672 if (getLexer().isNot(AsmToken::Comma))
1673 return TokError("unexpected token in directive");
1676 // The fill expression can be omitted while specifying a maximum number of
1677 // alignment bytes, e.g:
1679 if (getLexer().isNot(AsmToken::Comma)) {
1681 if (ParseAbsoluteExpression(FillExpr))
1685 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1686 if (getLexer().isNot(AsmToken::Comma))
1687 return TokError("unexpected token in directive");
1690 MaxBytesLoc = getLexer().getLoc();
1691 if (ParseAbsoluteExpression(MaxBytesToFill))
1694 if (getLexer().isNot(AsmToken::EndOfStatement))
1695 return TokError("unexpected token in directive");
1704 // Compute alignment in bytes.
1706 // FIXME: Diagnose overflow.
1707 if (Alignment >= 32) {
1708 Error(AlignmentLoc, "invalid alignment value");
1712 Alignment = 1ULL << Alignment;
1715 // Diagnose non-sensical max bytes to align.
1716 if (MaxBytesLoc.isValid()) {
1717 if (MaxBytesToFill < 1) {
1718 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1719 "many bytes, ignoring maximum bytes expression");
1723 if (MaxBytesToFill >= Alignment) {
1724 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1730 // Check whether we should use optimal code alignment for this .align
1732 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1733 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1734 ValueSize == 1 && UseCodeAlign) {
1735 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1737 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1738 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1745 /// ParseDirectiveSymbolAttribute
1746 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1747 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1748 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1752 if (ParseIdentifier(Name))
1753 return TokError("expected identifier in directive");
1755 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1757 getStreamer().EmitSymbolAttribute(Sym, Attr);
1759 if (getLexer().is(AsmToken::EndOfStatement))
1762 if (getLexer().isNot(AsmToken::Comma))
1763 return TokError("unexpected token in directive");
1772 /// ParseDirectiveComm
1773 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1774 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1775 CheckForValidSection();
1777 SMLoc IDLoc = getLexer().getLoc();
1779 if (ParseIdentifier(Name))
1780 return TokError("expected identifier in directive");
1782 // Handle the identifier as the key symbol.
1783 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1785 if (getLexer().isNot(AsmToken::Comma))
1786 return TokError("unexpected token in directive");
1790 SMLoc SizeLoc = getLexer().getLoc();
1791 if (ParseAbsoluteExpression(Size))
1794 int64_t Pow2Alignment = 0;
1795 SMLoc Pow2AlignmentLoc;
1796 if (getLexer().is(AsmToken::Comma)) {
1798 Pow2AlignmentLoc = getLexer().getLoc();
1799 if (ParseAbsoluteExpression(Pow2Alignment))
1802 // If this target takes alignments in bytes (not log) validate and convert.
1803 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1804 if (!isPowerOf2_64(Pow2Alignment))
1805 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1806 Pow2Alignment = Log2_64(Pow2Alignment);
1810 if (getLexer().isNot(AsmToken::EndOfStatement))
1811 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1815 // NOTE: a size of zero for a .comm should create a undefined symbol
1816 // but a size of .lcomm creates a bss symbol of size zero.
1818 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1819 "be less than zero");
1821 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1822 // may internally end up wanting an alignment in bytes.
1823 // FIXME: Diagnose overflow.
1824 if (Pow2Alignment < 0)
1825 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1826 "alignment, can't be less than zero");
1828 if (!Sym->isUndefined())
1829 return Error(IDLoc, "invalid symbol redefinition");
1831 // '.lcomm' is equivalent to '.zerofill'.
1832 // Create the Symbol as a common or local common with Size and Pow2Alignment
1834 getStreamer().EmitZerofill(Ctx.getMachOSection(
1835 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1836 0, SectionKind::getBSS()),
1837 Sym, Size, 1 << Pow2Alignment);
1841 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1845 /// ParseDirectiveAbort
1846 /// ::= .abort [... message ...]
1847 bool AsmParser::ParseDirectiveAbort() {
1848 // FIXME: Use loc from directive.
1849 SMLoc Loc = getLexer().getLoc();
1851 StringRef Str = ParseStringToEndOfStatement();
1852 if (getLexer().isNot(AsmToken::EndOfStatement))
1853 return TokError("unexpected token in '.abort' directive");
1858 Error(Loc, ".abort detected. Assembly stopping.");
1860 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1861 // FIXME: Actually abort assembly here.
1866 /// ParseDirectiveInclude
1867 /// ::= .include "filename"
1868 bool AsmParser::ParseDirectiveInclude() {
1869 if (getLexer().isNot(AsmToken::String))
1870 return TokError("expected string in '.include' directive");
1872 std::string Filename = getTok().getString();
1873 SMLoc IncludeLoc = getLexer().getLoc();
1876 if (getLexer().isNot(AsmToken::EndOfStatement))
1877 return TokError("unexpected token in '.include' directive");
1879 // Strip the quotes.
1880 Filename = Filename.substr(1, Filename.size()-2);
1882 // Attempt to switch the lexer to the included file before consuming the end
1883 // of statement to avoid losing it when we switch.
1884 if (EnterIncludeFile(Filename)) {
1885 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1892 /// ParseDirectiveIf
1893 /// ::= .if expression
1894 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1895 TheCondStack.push_back(TheCondState);
1896 TheCondState.TheCond = AsmCond::IfCond;
1897 if(TheCondState.Ignore) {
1898 EatToEndOfStatement();
1902 if (ParseAbsoluteExpression(ExprValue))
1905 if (getLexer().isNot(AsmToken::EndOfStatement))
1906 return TokError("unexpected token in '.if' directive");
1910 TheCondState.CondMet = ExprValue;
1911 TheCondState.Ignore = !TheCondState.CondMet;
1917 /// ParseDirectiveElseIf
1918 /// ::= .elseif expression
1919 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1920 if (TheCondState.TheCond != AsmCond::IfCond &&
1921 TheCondState.TheCond != AsmCond::ElseIfCond)
1922 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1924 TheCondState.TheCond = AsmCond::ElseIfCond;
1926 bool LastIgnoreState = false;
1927 if (!TheCondStack.empty())
1928 LastIgnoreState = TheCondStack.back().Ignore;
1929 if (LastIgnoreState || TheCondState.CondMet) {
1930 TheCondState.Ignore = true;
1931 EatToEndOfStatement();
1935 if (ParseAbsoluteExpression(ExprValue))
1938 if (getLexer().isNot(AsmToken::EndOfStatement))
1939 return TokError("unexpected token in '.elseif' directive");
1942 TheCondState.CondMet = ExprValue;
1943 TheCondState.Ignore = !TheCondState.CondMet;
1949 /// ParseDirectiveElse
1951 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1952 if (getLexer().isNot(AsmToken::EndOfStatement))
1953 return TokError("unexpected token in '.else' directive");
1957 if (TheCondState.TheCond != AsmCond::IfCond &&
1958 TheCondState.TheCond != AsmCond::ElseIfCond)
1959 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1961 TheCondState.TheCond = AsmCond::ElseCond;
1962 bool LastIgnoreState = false;
1963 if (!TheCondStack.empty())
1964 LastIgnoreState = TheCondStack.back().Ignore;
1965 if (LastIgnoreState || TheCondState.CondMet)
1966 TheCondState.Ignore = true;
1968 TheCondState.Ignore = false;
1973 /// ParseDirectiveEndIf
1975 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1976 if (getLexer().isNot(AsmToken::EndOfStatement))
1977 return TokError("unexpected token in '.endif' directive");
1981 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1982 TheCondStack.empty())
1983 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1985 if (!TheCondStack.empty()) {
1986 TheCondState = TheCondStack.back();
1987 TheCondStack.pop_back();
1993 /// ParseDirectiveFile
1994 /// ::= .file [number] string
1995 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1996 // FIXME: I'm not sure what this is.
1997 int64_t FileNumber = -1;
1998 SMLoc FileNumberLoc = getLexer().getLoc();
1999 if (getLexer().is(AsmToken::Integer)) {
2000 FileNumber = getTok().getIntVal();
2004 return TokError("file number less than one");
2007 if (getLexer().isNot(AsmToken::String))
2008 return TokError("unexpected token in '.file' directive");
2010 StringRef Filename = getTok().getString();
2011 Filename = Filename.substr(1, Filename.size()-2);
2014 if (getLexer().isNot(AsmToken::EndOfStatement))
2015 return TokError("unexpected token in '.file' directive");
2017 if (FileNumber == -1)
2018 getStreamer().EmitFileDirective(Filename);
2020 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2021 Error(FileNumberLoc, "file number already allocated");
2027 /// ParseDirectiveLine
2028 /// ::= .line [number]
2029 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2030 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2031 if (getLexer().isNot(AsmToken::Integer))
2032 return TokError("unexpected token in '.line' directive");
2034 int64_t LineNumber = getTok().getIntVal();
2038 // FIXME: Do something with the .line.
2041 if (getLexer().isNot(AsmToken::EndOfStatement))
2042 return TokError("unexpected token in '.line' directive");
2048 /// ParseDirectiveLoc
2049 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2050 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2051 /// The first number is a file number, must have been previously assigned with
2052 /// a .file directive, the second number is the line number and optionally the
2053 /// third number is a column position (zero if not specified). The remaining
2054 /// optional items are .loc sub-directives.
2055 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2057 if (getLexer().isNot(AsmToken::Integer))
2058 return TokError("unexpected token in '.loc' directive");
2059 int64_t FileNumber = getTok().getIntVal();
2061 return TokError("file number less than one in '.loc' directive");
2062 if (!getContext().isValidDwarfFileNumber(FileNumber))
2063 return TokError("unassigned file number in '.loc' directive");
2066 int64_t LineNumber = 0;
2067 if (getLexer().is(AsmToken::Integer)) {
2068 LineNumber = getTok().getIntVal();
2070 return TokError("line number less than one in '.loc' directive");
2074 int64_t ColumnPos = 0;
2075 if (getLexer().is(AsmToken::Integer)) {
2076 ColumnPos = getTok().getIntVal();
2078 return TokError("column position less than zero in '.loc' directive");
2082 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2084 int64_t Discriminator = 0;
2085 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2087 if (getLexer().is(AsmToken::EndOfStatement))
2091 SMLoc Loc = getTok().getLoc();
2092 if (getParser().ParseIdentifier(Name))
2093 return TokError("unexpected token in '.loc' directive");
2095 if (Name == "basic_block")
2096 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2097 else if (Name == "prologue_end")
2098 Flags |= DWARF2_FLAG_PROLOGUE_END;
2099 else if (Name == "epilogue_begin")
2100 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2101 else if (Name == "is_stmt") {
2102 SMLoc Loc = getTok().getLoc();
2103 const MCExpr *Value;
2104 if (getParser().ParseExpression(Value))
2106 // The expression must be the constant 0 or 1.
2107 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2108 int Value = MCE->getValue();
2110 Flags &= ~DWARF2_FLAG_IS_STMT;
2111 else if (Value == 1)
2112 Flags |= DWARF2_FLAG_IS_STMT;
2114 return Error(Loc, "is_stmt value not 0 or 1");
2117 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2120 else if (Name == "isa") {
2121 SMLoc Loc = getTok().getLoc();
2122 const MCExpr *Value;
2123 if (getParser().ParseExpression(Value))
2125 // The expression must be a constant greater or equal to 0.
2126 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2127 int Value = MCE->getValue();
2129 return Error(Loc, "isa number less than zero");
2133 return Error(Loc, "isa number not a constant value");
2136 else if (Name == "discriminator") {
2137 if (getParser().ParseAbsoluteExpression(Discriminator))
2141 return Error(Loc, "unknown sub-directive in '.loc' directive");
2144 if (getLexer().is(AsmToken::EndOfStatement))
2149 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2150 Isa, Discriminator);
2155 /// ParseDirectiveStabs
2156 /// ::= .stabs string, number, number, number
2157 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2158 SMLoc DirectiveLoc) {
2159 return TokError("unsupported directive '" + Directive + "'");
2162 /// ParseDirectiveCFIStartProc
2163 /// ::= .cfi_startproc
2164 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2165 SMLoc DirectiveLoc) {
2166 return getStreamer().EmitCFIStartProc();
2169 /// ParseDirectiveCFIEndProc
2170 /// ::= .cfi_endproc
2171 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2172 return getStreamer().EmitCFIEndProc();
2175 /// ParseDirectiveCFIDefCfaOffset
2176 /// ::= .cfi_def_cfa_offset offset
2177 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2178 SMLoc DirectiveLoc) {
2180 if (getParser().ParseAbsoluteExpression(Offset))
2183 return getStreamer().EmitCFIDefCfaOffset(Offset);
2186 /// ParseDirectiveCFIDefCfaRegister
2187 /// ::= .cfi_def_cfa_register register
2188 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2189 SMLoc DirectiveLoc) {
2190 int64_t Register = 0;
2191 if (getParser().ParseAbsoluteExpression(Register))
2194 return getStreamer().EmitCFIDefCfaRegister(Register);
2197 /// ParseDirectiveCFIOffset
2198 /// ::= .cfi_off register, offset
2199 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2200 int64_t Register = 0;
2202 if (getParser().ParseAbsoluteExpression(Register))
2205 if (getLexer().isNot(AsmToken::Comma))
2206 return TokError("unexpected token in directive");
2209 if (getParser().ParseAbsoluteExpression(Offset))
2212 return getStreamer().EmitCFIOffset(Register, Offset);
2215 static bool isValidEncoding(int64_t Encoding) {
2216 if (Encoding & ~0xff)
2219 if (Encoding == dwarf::DW_EH_PE_omit)
2222 const unsigned Format = Encoding & 0xf;
2223 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2224 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2225 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2226 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2229 const unsigned Application = Encoding & 0xf0;
2230 if (Application != dwarf::DW_EH_PE_absptr &&
2231 Application != dwarf::DW_EH_PE_pcrel &&
2232 Application != dwarf::DW_EH_PE_indirect)
2238 /// ParseDirectiveCFIPersonalityOrLsda
2239 /// ::= .cfi_personality encoding, [symbol_name]
2240 /// ::= .cfi_lsda encoding, [symbol_name]
2241 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2242 SMLoc DirectiveLoc) {
2243 int64_t Encoding = 0;
2244 if (getParser().ParseAbsoluteExpression(Encoding))
2246 if (Encoding == dwarf::DW_EH_PE_omit)
2249 if (!isValidEncoding(Encoding))
2250 return TokError("unsupported encoding.");
2252 if (getLexer().isNot(AsmToken::Comma))
2253 return TokError("unexpected token in directive");
2257 if (getParser().ParseIdentifier(Name))
2258 return TokError("expected identifier in directive");
2260 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2262 if (IDVal == ".cfi_personality")
2263 return getStreamer().EmitCFIPersonality(Sym, Encoding);
2265 assert(IDVal == ".cfi_lsda");
2266 return getStreamer().EmitCFILsda(Sym, Encoding);
2270 /// ParseDirectiveCFIRememberState
2271 /// ::= .cfi_remember_state
2272 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2273 SMLoc DirectiveLoc) {
2274 return getStreamer().EmitCFIRememberState();
2277 /// ParseDirectiveCFIRestoreState
2278 /// ::= .cfi_remember_state
2279 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2280 SMLoc DirectiveLoc) {
2281 return getStreamer().EmitCFIRestoreState();
2284 /// ParseDirectiveMacrosOnOff
2287 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2288 SMLoc DirectiveLoc) {
2289 if (getLexer().isNot(AsmToken::EndOfStatement))
2290 return Error(getLexer().getLoc(),
2291 "unexpected token in '" + Directive + "' directive");
2293 getParser().MacrosEnabled = Directive == ".macros_on";
2298 /// ParseDirectiveMacro
2300 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2301 SMLoc DirectiveLoc) {
2303 if (getParser().ParseIdentifier(Name))
2304 return TokError("expected identifier in directive");
2306 if (getLexer().isNot(AsmToken::EndOfStatement))
2307 return TokError("unexpected token in '.macro' directive");
2309 // Eat the end of statement.
2312 AsmToken EndToken, StartToken = getTok();
2314 // Lex the macro definition.
2316 // Check whether we have reached the end of the file.
2317 if (getLexer().is(AsmToken::Eof))
2318 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2320 // Otherwise, check whether we have reach the .endmacro.
2321 if (getLexer().is(AsmToken::Identifier) &&
2322 (getTok().getIdentifier() == ".endm" ||
2323 getTok().getIdentifier() == ".endmacro")) {
2324 EndToken = getTok();
2326 if (getLexer().isNot(AsmToken::EndOfStatement))
2327 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2332 // Otherwise, scan til the end of the statement.
2333 getParser().EatToEndOfStatement();
2336 if (getParser().MacroMap.lookup(Name)) {
2337 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2340 const char *BodyStart = StartToken.getLoc().getPointer();
2341 const char *BodyEnd = EndToken.getLoc().getPointer();
2342 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2343 getParser().MacroMap[Name] = new Macro(Name, Body);
2347 /// ParseDirectiveEndMacro
2350 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2351 SMLoc DirectiveLoc) {
2352 if (getLexer().isNot(AsmToken::EndOfStatement))
2353 return TokError("unexpected token in '" + Directive + "' directive");
2355 // If we are inside a macro instantiation, terminate the current
2357 if (!getParser().ActiveMacros.empty()) {
2358 getParser().HandleMacroExit();
2362 // Otherwise, this .endmacro is a stray entry in the file; well formed
2363 // .endmacro directives are handled during the macro definition parsing.
2364 return TokError("unexpected '" + Directive + "' in file, "
2365 "no current macro definition");
2368 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2369 getParser().CheckForValidSection();
2371 const MCExpr *Value;
2373 if (getParser().ParseExpression(Value))
2376 if (getLexer().isNot(AsmToken::EndOfStatement))
2377 return TokError("unexpected token in directive");
2379 if (DirName[1] == 's')
2380 getStreamer().EmitSLEB128Value(Value);
2382 getStreamer().EmitULEB128Value(Value);
2388 /// \brief Create an MCAsmParser instance.
2389 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2390 MCContext &C, MCStreamer &Out,
2391 const MCAsmInfo &MAI) {
2392 return new AsmParser(T, SM, C, Out, MAI);