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");
259 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
261 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
263 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
264 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
265 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
268 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
271 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
272 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
273 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
274 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
275 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
276 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
277 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
278 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
279 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
280 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
282 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
283 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
284 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
286 bool ParseDirectiveLEB128(StringRef, SMLoc);
293 extern MCAsmParserExtension *createDarwinAsmParser();
294 extern MCAsmParserExtension *createELFAsmParser();
295 extern MCAsmParserExtension *createCOFFAsmParser();
299 enum { DEFAULT_ADDRSPACE = 0 };
301 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
302 MCStreamer &_Out, const MCAsmInfo &_MAI)
303 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
304 GenericParser(new GenericAsmParser), PlatformParser(0),
305 CurBuffer(0), MacrosEnabled(true) {
306 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
308 // Initialize the generic parser.
309 GenericParser->Initialize(*this);
311 // Initialize the platform / file format parser.
313 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
315 if (_MAI.hasMicrosoftFastStdCallMangling()) {
316 PlatformParser = createCOFFAsmParser();
317 PlatformParser->Initialize(*this);
318 } else if (_MAI.hasSubsectionsViaSymbols()) {
319 PlatformParser = createDarwinAsmParser();
320 PlatformParser->Initialize(*this);
322 PlatformParser = createELFAsmParser();
323 PlatformParser->Initialize(*this);
327 AsmParser::~AsmParser() {
328 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
330 // Destroy any macros.
331 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
332 ie = MacroMap.end(); it != ie; ++it)
333 delete it->getValue();
335 delete PlatformParser;
336 delete GenericParser;
339 void AsmParser::PrintMacroInstantiations() {
340 // Print the active macro instantiation stack.
341 for (std::vector<MacroInstantiation*>::const_reverse_iterator
342 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
343 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
347 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
348 PrintMessage(L, Msg, "warning");
349 PrintMacroInstantiations();
352 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
354 PrintMessage(L, Msg, "error");
355 PrintMacroInstantiations();
359 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
360 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
366 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
371 void AsmParser::JumpToLoc(SMLoc Loc) {
372 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
373 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
376 const AsmToken &AsmParser::Lex() {
377 const AsmToken *tok = &Lexer.Lex();
379 if (tok->is(AsmToken::Eof)) {
380 // If this is the end of an included file, pop the parent file off the
382 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
383 if (ParentIncludeLoc != SMLoc()) {
384 JumpToLoc(ParentIncludeLoc);
389 if (tok->is(AsmToken::Error))
390 Error(Lexer.getErrLoc(), Lexer.getErr());
395 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
396 // Create the initial section, if requested.
397 if (!NoInitialTextSection)
404 AsmCond StartingCondState = TheCondState;
406 // While we have input, parse each statement.
407 while (Lexer.isNot(AsmToken::Eof)) {
408 if (!ParseStatement()) continue;
410 // We had an error, validate that one was emitted and recover by skipping to
412 assert(HadError && "Parse statement returned an error, but none emitted!");
413 EatToEndOfStatement();
416 if (TheCondState.TheCond != StartingCondState.TheCond ||
417 TheCondState.Ignore != StartingCondState.Ignore)
418 return TokError("unmatched .ifs or .elses");
420 // Check to see there are no empty DwarfFile slots.
421 const std::vector<MCDwarfFile *> &MCDwarfFiles =
422 getContext().getMCDwarfFiles();
423 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
424 if (!MCDwarfFiles[i])
425 TokError("unassigned file number: " + Twine(i) + " for .file directives");
428 // Finalize the output stream if there are no errors and if the client wants
430 if (!HadError && !NoFinalize)
436 void AsmParser::CheckForValidSection() {
437 if (!getStreamer().getCurrentSection()) {
438 TokError("expected section directive before assembly directive");
439 Out.SwitchSection(Ctx.getMachOSection(
441 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
442 0, SectionKind::getText()));
446 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
447 void AsmParser::EatToEndOfStatement() {
448 while (Lexer.isNot(AsmToken::EndOfStatement) &&
449 Lexer.isNot(AsmToken::Eof))
453 if (Lexer.is(AsmToken::EndOfStatement))
457 StringRef AsmParser::ParseStringToEndOfStatement() {
458 const char *Start = getTok().getLoc().getPointer();
460 while (Lexer.isNot(AsmToken::EndOfStatement) &&
461 Lexer.isNot(AsmToken::Eof))
464 const char *End = getTok().getLoc().getPointer();
465 return StringRef(Start, End - Start);
468 /// ParseParenExpr - Parse a paren expression and return it.
469 /// NOTE: This assumes the leading '(' has already been consumed.
471 /// parenexpr ::= expr)
473 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
474 if (ParseExpression(Res)) return true;
475 if (Lexer.isNot(AsmToken::RParen))
476 return TokError("expected ')' in parentheses expression");
477 EndLoc = Lexer.getLoc();
482 /// ParsePrimaryExpr - Parse a primary expression and return it.
483 /// primaryexpr ::= (parenexpr
484 /// primaryexpr ::= symbol
485 /// primaryexpr ::= number
486 /// primaryexpr ::= '.'
487 /// primaryexpr ::= ~,+,- primaryexpr
488 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
489 switch (Lexer.getKind()) {
491 return TokError("unknown token in expression");
492 case AsmToken::Exclaim:
493 Lex(); // Eat the operator.
494 if (ParsePrimaryExpr(Res, EndLoc))
496 Res = MCUnaryExpr::CreateLNot(Res, getContext());
498 case AsmToken::Dollar:
499 case AsmToken::String:
500 case AsmToken::Identifier: {
501 EndLoc = Lexer.getLoc();
503 StringRef Identifier;
504 if (ParseIdentifier(Identifier))
507 // This is a symbol reference.
508 std::pair<StringRef, StringRef> Split = Identifier.split('@');
509 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
511 // Lookup the symbol variant if used.
512 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
513 if (Split.first.size() != Identifier.size()) {
514 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
515 if (Variant == MCSymbolRefExpr::VK_Invalid) {
516 Variant = MCSymbolRefExpr::VK_None;
517 TokError("invalid variant '" + Split.second + "'");
521 // If this is an absolute variable reference, substitute it now to preserve
522 // semantics in the face of reassignment.
523 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
525 return Error(EndLoc, "unexpected modifier on variable reference");
527 Res = Sym->getVariableValue();
531 // Otherwise create a symbol ref.
532 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
535 case AsmToken::Integer: {
536 SMLoc Loc = getTok().getLoc();
537 int64_t IntVal = getTok().getIntVal();
538 Res = MCConstantExpr::Create(IntVal, getContext());
539 EndLoc = Lexer.getLoc();
541 // Look for 'b' or 'f' following an Integer as a directional label
542 if (Lexer.getKind() == AsmToken::Identifier) {
543 StringRef IDVal = getTok().getString();
544 if (IDVal == "f" || IDVal == "b"){
545 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
546 IDVal == "f" ? 1 : 0);
547 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
549 if(IDVal == "b" && Sym->isUndefined())
550 return Error(Loc, "invalid reference to undefined symbol");
551 EndLoc = Lexer.getLoc();
552 Lex(); // Eat identifier.
557 case AsmToken::Dot: {
558 // This is a '.' reference, which references the current PC. Emit a
559 // temporary label to the streamer and refer to it.
560 MCSymbol *Sym = Ctx.CreateTempSymbol();
562 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
563 EndLoc = Lexer.getLoc();
564 Lex(); // Eat identifier.
568 case AsmToken::LParen:
569 Lex(); // Eat the '('.
570 return ParseParenExpr(Res, EndLoc);
571 case AsmToken::Minus:
572 Lex(); // Eat the operator.
573 if (ParsePrimaryExpr(Res, EndLoc))
575 Res = MCUnaryExpr::CreateMinus(Res, getContext());
578 Lex(); // Eat the operator.
579 if (ParsePrimaryExpr(Res, EndLoc))
581 Res = MCUnaryExpr::CreatePlus(Res, getContext());
583 case AsmToken::Tilde:
584 Lex(); // Eat the operator.
585 if (ParsePrimaryExpr(Res, EndLoc))
587 Res = MCUnaryExpr::CreateNot(Res, getContext());
592 bool AsmParser::ParseExpression(const MCExpr *&Res) {
594 return ParseExpression(Res, EndLoc);
598 AsmParser::ApplyModifierToExpr(const MCExpr *E,
599 MCSymbolRefExpr::VariantKind Variant) {
600 // Recurse over the given expression, rebuilding it to apply the given variant
601 // if there is exactly one symbol.
602 switch (E->getKind()) {
604 case MCExpr::Constant:
607 case MCExpr::SymbolRef: {
608 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
610 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
611 TokError("invalid variant on expression '" +
612 getTok().getIdentifier() + "' (already modified)");
616 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
619 case MCExpr::Unary: {
620 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
621 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
624 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
627 case MCExpr::Binary: {
628 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
629 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
630 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
635 if (!LHS) LHS = BE->getLHS();
636 if (!RHS) RHS = BE->getRHS();
638 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
642 assert(0 && "Invalid expression kind!");
646 /// ParseExpression - Parse an expression and return it.
648 /// expr ::= expr +,- expr -> lowest.
649 /// expr ::= expr |,^,&,! expr -> middle.
650 /// expr ::= expr *,/,%,<<,>> expr -> highest.
651 /// expr ::= primaryexpr
653 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
654 // Parse the expression.
656 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
659 // As a special case, we support 'a op b @ modifier' by rewriting the
660 // expression to include the modifier. This is inefficient, but in general we
661 // expect users to use 'a@modifier op b'.
662 if (Lexer.getKind() == AsmToken::At) {
665 if (Lexer.isNot(AsmToken::Identifier))
666 return TokError("unexpected symbol modifier following '@'");
668 MCSymbolRefExpr::VariantKind Variant =
669 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
670 if (Variant == MCSymbolRefExpr::VK_Invalid)
671 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
673 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
675 return TokError("invalid modifier '" + getTok().getIdentifier() +
676 "' (no symbols present)");
684 // Try to constant fold it up front, if possible.
686 if (Res->EvaluateAsAbsolute(Value))
687 Res = MCConstantExpr::Create(Value, getContext());
692 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
694 return ParseParenExpr(Res, EndLoc) ||
695 ParseBinOpRHS(1, Res, EndLoc);
698 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
701 SMLoc StartLoc = Lexer.getLoc();
702 if (ParseExpression(Expr))
705 if (!Expr->EvaluateAsAbsolute(Res))
706 return Error(StartLoc, "expected absolute expression");
711 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
712 MCBinaryExpr::Opcode &Kind) {
715 return 0; // not a binop.
717 // Lowest Precedence: &&, ||, @
718 case AsmToken::AmpAmp:
719 Kind = MCBinaryExpr::LAnd;
721 case AsmToken::PipePipe:
722 Kind = MCBinaryExpr::LOr;
726 // Low Precedence: |, &, ^
728 // FIXME: gas seems to support '!' as an infix operator?
730 Kind = MCBinaryExpr::Or;
732 case AsmToken::Caret:
733 Kind = MCBinaryExpr::Xor;
736 Kind = MCBinaryExpr::And;
739 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
740 case AsmToken::EqualEqual:
741 Kind = MCBinaryExpr::EQ;
743 case AsmToken::ExclaimEqual:
744 case AsmToken::LessGreater:
745 Kind = MCBinaryExpr::NE;
748 Kind = MCBinaryExpr::LT;
750 case AsmToken::LessEqual:
751 Kind = MCBinaryExpr::LTE;
753 case AsmToken::Greater:
754 Kind = MCBinaryExpr::GT;
756 case AsmToken::GreaterEqual:
757 Kind = MCBinaryExpr::GTE;
760 // High Intermediate Precedence: +, -
762 Kind = MCBinaryExpr::Add;
764 case AsmToken::Minus:
765 Kind = MCBinaryExpr::Sub;
768 // Highest Precedence: *, /, %, <<, >>
770 Kind = MCBinaryExpr::Mul;
772 case AsmToken::Slash:
773 Kind = MCBinaryExpr::Div;
775 case AsmToken::Percent:
776 Kind = MCBinaryExpr::Mod;
778 case AsmToken::LessLess:
779 Kind = MCBinaryExpr::Shl;
781 case AsmToken::GreaterGreater:
782 Kind = MCBinaryExpr::Shr;
788 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
789 /// Res contains the LHS of the expression on input.
790 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
793 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
794 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
796 // If the next token is lower precedence than we are allowed to eat, return
797 // successfully with what we ate already.
798 if (TokPrec < Precedence)
803 // Eat the next primary expression.
805 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
807 // If BinOp binds less tightly with RHS than the operator after RHS, let
808 // the pending operator take RHS as its LHS.
809 MCBinaryExpr::Opcode Dummy;
810 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
811 if (TokPrec < NextTokPrec) {
812 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
815 // Merge LHS and RHS according to operator.
816 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
824 /// ::= EndOfStatement
825 /// ::= Label* Directive ...Operands... EndOfStatement
826 /// ::= Label* Identifier OperandList* EndOfStatement
827 bool AsmParser::ParseStatement() {
828 if (Lexer.is(AsmToken::EndOfStatement)) {
834 // Statements always start with an identifier or are a full line comment.
835 AsmToken ID = getTok();
836 SMLoc IDLoc = ID.getLoc();
838 int64_t LocalLabelVal = -1;
839 // A full line comment is a '#' as the first token.
840 if (Lexer.is(AsmToken::Hash)) {
841 EatToEndOfStatement();
844 // Allow an integer followed by a ':' as a directional local label.
845 if (Lexer.is(AsmToken::Integer)) {
846 LocalLabelVal = getTok().getIntVal();
847 if (LocalLabelVal < 0) {
848 if (!TheCondState.Ignore)
849 return TokError("unexpected token at start of statement");
853 IDVal = getTok().getString();
854 Lex(); // Consume the integer token to be used as an identifier token.
855 if (Lexer.getKind() != AsmToken::Colon) {
856 if (!TheCondState.Ignore)
857 return TokError("unexpected token at start of statement");
861 else if (ParseIdentifier(IDVal)) {
862 if (!TheCondState.Ignore)
863 return TokError("unexpected token at start of statement");
867 // Handle conditional assembly here before checking for skipping. We
868 // have to do this so that .endif isn't skipped in a ".if 0" block for
871 return ParseDirectiveIf(IDLoc);
872 if (IDVal == ".elseif")
873 return ParseDirectiveElseIf(IDLoc);
874 if (IDVal == ".else")
875 return ParseDirectiveElse(IDLoc);
876 if (IDVal == ".endif")
877 return ParseDirectiveEndIf(IDLoc);
879 // If we are in a ".if 0" block, ignore this statement.
880 if (TheCondState.Ignore) {
881 EatToEndOfStatement();
885 // FIXME: Recurse on local labels?
887 // See what kind of statement we have.
888 switch (Lexer.getKind()) {
889 case AsmToken::Colon: {
890 CheckForValidSection();
892 // identifier ':' -> Label.
895 // Diagnose attempt to use a variable as a label.
897 // FIXME: Diagnostics. Note the location of the definition as a label.
898 // FIXME: This doesn't diagnose assignment to a symbol which has been
899 // implicitly marked as external.
901 if (LocalLabelVal == -1)
902 Sym = getContext().GetOrCreateSymbol(IDVal);
904 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
905 if (!Sym->isUndefined() || Sym->isVariable())
906 return Error(IDLoc, "invalid symbol redefinition");
911 // Consume any end of statement token, if present, to avoid spurious
912 // AddBlankLine calls().
913 if (Lexer.is(AsmToken::EndOfStatement)) {
915 if (Lexer.is(AsmToken::Eof))
919 return ParseStatement();
922 case AsmToken::Equal:
923 // identifier '=' ... -> assignment statement
926 return ParseAssignment(IDVal);
928 default: // Normal instruction or directive.
932 // If macros are enabled, check to see if this is a macro instantiation.
934 if (const Macro *M = MacroMap.lookup(IDVal))
935 return HandleMacroEntry(IDVal, IDLoc, M);
937 // Otherwise, we have a normal instruction or directive.
938 if (IDVal[0] == '.') {
939 // Assembler features
940 if (IDVal == ".set" || IDVal == ".equ")
941 return ParseDirectiveSet(IDVal);
945 if (IDVal == ".ascii")
946 return ParseDirectiveAscii(IDVal, false);
947 if (IDVal == ".asciz" || IDVal == ".string")
948 return ParseDirectiveAscii(IDVal, true);
950 if (IDVal == ".byte")
951 return ParseDirectiveValue(1);
952 if (IDVal == ".short")
953 return ParseDirectiveValue(2);
954 if (IDVal == ".value")
955 return ParseDirectiveValue(2);
956 if (IDVal == ".2byte")
957 return ParseDirectiveValue(2);
958 if (IDVal == ".long")
959 return ParseDirectiveValue(4);
961 return ParseDirectiveValue(4);
962 if (IDVal == ".4byte")
963 return ParseDirectiveValue(4);
964 if (IDVal == ".quad")
965 return ParseDirectiveValue(8);
966 if (IDVal == ".8byte")
967 return ParseDirectiveValue(8);
968 if (IDVal == ".single")
969 return ParseDirectiveRealValue(APFloat::IEEEsingle);
970 if (IDVal == ".double")
971 return ParseDirectiveRealValue(APFloat::IEEEdouble);
973 if (IDVal == ".align") {
974 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
975 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
977 if (IDVal == ".align32") {
978 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
979 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
981 if (IDVal == ".balign")
982 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
983 if (IDVal == ".balignw")
984 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
985 if (IDVal == ".balignl")
986 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
987 if (IDVal == ".p2align")
988 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
989 if (IDVal == ".p2alignw")
990 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
991 if (IDVal == ".p2alignl")
992 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
995 return ParseDirectiveOrg();
997 if (IDVal == ".fill")
998 return ParseDirectiveFill();
999 if (IDVal == ".space")
1000 return ParseDirectiveSpace();
1001 if (IDVal == ".zero")
1002 return ParseDirectiveZero();
1004 // Symbol attribute directives
1006 if (IDVal == ".globl" || IDVal == ".global")
1007 return ParseDirectiveSymbolAttribute(MCSA_Global);
1008 // ELF only? Should it be here?
1009 if (IDVal == ".local")
1010 return ParseDirectiveSymbolAttribute(MCSA_Local);
1011 if (IDVal == ".hidden")
1012 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1013 if (IDVal == ".indirect_symbol")
1014 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1015 if (IDVal == ".internal")
1016 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1017 if (IDVal == ".lazy_reference")
1018 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1019 if (IDVal == ".no_dead_strip")
1020 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1021 if (IDVal == ".symbol_resolver")
1022 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1023 if (IDVal == ".private_extern")
1024 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1025 if (IDVal == ".protected")
1026 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1027 if (IDVal == ".reference")
1028 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1029 if (IDVal == ".weak")
1030 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1031 if (IDVal == ".weak_definition")
1032 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1033 if (IDVal == ".weak_reference")
1034 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1035 if (IDVal == ".weak_def_can_be_hidden")
1036 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1038 if (IDVal == ".comm")
1039 return ParseDirectiveComm(/*IsLocal=*/false);
1040 if (IDVal == ".lcomm")
1041 return ParseDirectiveComm(/*IsLocal=*/true);
1043 if (IDVal == ".abort")
1044 return ParseDirectiveAbort();
1045 if (IDVal == ".include")
1046 return ParseDirectiveInclude();
1048 // Look up the handler in the handler table.
1049 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1050 DirectiveMap.lookup(IDVal);
1052 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1054 // Target hook for parsing target specific directives.
1055 if (!getTargetParser().ParseDirective(ID))
1058 Warning(IDLoc, "ignoring directive for now");
1059 EatToEndOfStatement();
1063 CheckForValidSection();
1065 // Canonicalize the opcode to lower case.
1066 SmallString<128> Opcode;
1067 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1068 Opcode.push_back(tolower(IDVal[i]));
1070 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1071 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1074 // Dump the parsed representation, if requested.
1075 if (getShowParsedOperands()) {
1076 SmallString<256> Str;
1077 raw_svector_ostream OS(Str);
1078 OS << "parsed instruction: [";
1079 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1082 ParsedOperands[i]->dump(OS);
1086 PrintMessage(IDLoc, OS.str(), "note");
1089 // If parsing succeeded, match the instruction.
1091 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1094 // Free any parsed operands.
1095 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1096 delete ParsedOperands[i];
1098 // Don't skip the rest of the line, the instruction parser is responsible for
1103 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1104 const std::vector<std::vector<AsmToken> > &A)
1105 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1107 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1108 // to hold the macro body with substitutions.
1109 SmallString<256> Buf;
1110 raw_svector_ostream OS(Buf);
1112 StringRef Body = M->Body;
1113 while (!Body.empty()) {
1114 // Scan for the next substitution.
1115 std::size_t End = Body.size(), Pos = 0;
1116 for (; Pos != End; ++Pos) {
1117 // Check for a substitution or escape.
1118 if (Body[Pos] != '$' || Pos + 1 == End)
1121 char Next = Body[Pos + 1];
1122 if (Next == '$' || Next == 'n' || isdigit(Next))
1127 OS << Body.slice(0, Pos);
1129 // Check if we reached the end.
1133 switch (Body[Pos+1]) {
1139 // $n => number of arguments
1144 // $[0-9] => argument
1146 // Missing arguments are ignored.
1147 unsigned Index = Body[Pos+1] - '0';
1148 if (Index >= A.size())
1151 // Otherwise substitute with the token values, with spaces eliminated.
1152 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1153 ie = A[Index].end(); it != ie; ++it)
1154 OS << it->getString();
1159 // Update the scan point.
1160 Body = Body.substr(Pos + 2);
1163 // We include the .endmacro in the buffer as our queue to exit the macro
1165 OS << ".endmacro\n";
1167 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1170 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1172 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1173 // this, although we should protect against infinite loops.
1174 if (ActiveMacros.size() == 20)
1175 return TokError("macros cannot be nested more than 20 levels deep");
1177 // Parse the macro instantiation arguments.
1178 std::vector<std::vector<AsmToken> > MacroArguments;
1179 MacroArguments.push_back(std::vector<AsmToken>());
1180 unsigned ParenLevel = 0;
1182 if (Lexer.is(AsmToken::Eof))
1183 return TokError("unexpected token in macro instantiation");
1184 if (Lexer.is(AsmToken::EndOfStatement))
1187 // If we aren't inside parentheses and this is a comma, start a new token
1189 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1190 MacroArguments.push_back(std::vector<AsmToken>());
1192 // Adjust the current parentheses level.
1193 if (Lexer.is(AsmToken::LParen))
1195 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1198 // Append the token to the current argument list.
1199 MacroArguments.back().push_back(getTok());
1204 // Create the macro instantiation object and add to the current macro
1205 // instantiation stack.
1206 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1209 ActiveMacros.push_back(MI);
1211 // Jump to the macro instantiation and prime the lexer.
1212 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1213 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1219 void AsmParser::HandleMacroExit() {
1220 // Jump to the EndOfStatement we should return to, and consume it.
1221 JumpToLoc(ActiveMacros.back()->ExitLoc);
1224 // Pop the instantiation entry.
1225 delete ActiveMacros.back();
1226 ActiveMacros.pop_back();
1229 static void MarkUsed(const MCExpr *Value) {
1230 switch (Value->getKind()) {
1231 case MCExpr::Binary:
1232 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1233 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1235 case MCExpr::Target:
1236 case MCExpr::Constant:
1238 case MCExpr::SymbolRef: {
1239 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1243 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1248 bool AsmParser::ParseAssignment(StringRef Name) {
1249 // FIXME: Use better location, we should use proper tokens.
1250 SMLoc EqualLoc = Lexer.getLoc();
1252 const MCExpr *Value;
1253 if (ParseExpression(Value))
1258 if (Lexer.isNot(AsmToken::EndOfStatement))
1259 return TokError("unexpected token in assignment");
1261 // Eat the end of statement marker.
1264 // Validate that the LHS is allowed to be a variable (either it has not been
1265 // used as a symbol, or it is an absolute symbol).
1266 MCSymbol *Sym = getContext().LookupSymbol(Name);
1268 // Diagnose assignment to a label.
1270 // FIXME: Diagnostics. Note the location of the definition as a label.
1271 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1272 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1273 ; // Allow redefinitions of undefined symbols only used in directives.
1274 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1275 return Error(EqualLoc, "redefinition of '" + Name + "'");
1276 else if (!Sym->isVariable())
1277 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1278 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1279 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1282 // Don't count these checks as uses.
1283 Sym->setUsed(false);
1285 Sym = getContext().GetOrCreateSymbol(Name);
1287 // FIXME: Handle '.'.
1289 // Do the assignment.
1290 Out.EmitAssignment(Sym, Value);
1295 /// ParseIdentifier:
1298 bool AsmParser::ParseIdentifier(StringRef &Res) {
1299 // The assembler has relaxed rules for accepting identifiers, in particular we
1300 // allow things like '.globl $foo', which would normally be separate
1301 // tokens. At this level, we have already lexed so we cannot (currently)
1302 // handle this as a context dependent token, instead we detect adjacent tokens
1303 // and return the combined identifier.
1304 if (Lexer.is(AsmToken::Dollar)) {
1305 SMLoc DollarLoc = getLexer().getLoc();
1307 // Consume the dollar sign, and check for a following identifier.
1309 if (Lexer.isNot(AsmToken::Identifier))
1312 // We have a '$' followed by an identifier, make sure they are adjacent.
1313 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1316 // Construct the joined identifier and consume the token.
1317 Res = StringRef(DollarLoc.getPointer(),
1318 getTok().getIdentifier().size() + 1);
1323 if (Lexer.isNot(AsmToken::Identifier) &&
1324 Lexer.isNot(AsmToken::String))
1327 Res = getTok().getIdentifier();
1329 Lex(); // Consume the identifier token.
1334 /// ParseDirectiveSet:
1335 /// ::= .set identifier ',' expression
1336 bool AsmParser::ParseDirectiveSet(StringRef IDVal) {
1339 if (ParseIdentifier(Name))
1340 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1342 if (getLexer().isNot(AsmToken::Comma))
1343 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1346 return ParseAssignment(Name);
1349 bool AsmParser::ParseEscapedString(std::string &Data) {
1350 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1353 StringRef Str = getTok().getStringContents();
1354 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1355 if (Str[i] != '\\') {
1360 // Recognize escaped characters. Note that this escape semantics currently
1361 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1364 return TokError("unexpected backslash at end of string");
1366 // Recognize octal sequences.
1367 if ((unsigned) (Str[i] - '0') <= 7) {
1368 // Consume up to three octal characters.
1369 unsigned Value = Str[i] - '0';
1371 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1373 Value = Value * 8 + (Str[i] - '0');
1375 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1377 Value = Value * 8 + (Str[i] - '0');
1382 return TokError("invalid octal escape sequence (out of range)");
1384 Data += (unsigned char) Value;
1388 // Otherwise recognize individual escapes.
1391 // Just reject invalid escape sequences for now.
1392 return TokError("invalid escape sequence (unrecognized character)");
1394 case 'b': Data += '\b'; break;
1395 case 'f': Data += '\f'; break;
1396 case 'n': Data += '\n'; break;
1397 case 'r': Data += '\r'; break;
1398 case 't': Data += '\t'; break;
1399 case '"': Data += '"'; break;
1400 case '\\': Data += '\\'; break;
1407 /// ParseDirectiveAscii:
1408 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1409 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1410 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1411 CheckForValidSection();
1414 if (getLexer().isNot(AsmToken::String))
1415 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1418 if (ParseEscapedString(Data))
1421 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1423 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1427 if (getLexer().is(AsmToken::EndOfStatement))
1430 if (getLexer().isNot(AsmToken::Comma))
1431 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1440 /// ParseDirectiveValue
1441 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1442 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1443 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1444 CheckForValidSection();
1447 const MCExpr *Value;
1448 if (ParseExpression(Value))
1451 // Special case constant expressions to match code generator.
1452 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1453 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1455 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1457 if (getLexer().is(AsmToken::EndOfStatement))
1460 // FIXME: Improve diagnostic.
1461 if (getLexer().isNot(AsmToken::Comma))
1462 return TokError("unexpected token in directive");
1471 /// ParseDirectiveRealValue
1472 /// ::= (.single | .double) [ expression (, expression)* ]
1473 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1474 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1475 CheckForValidSection();
1478 // We don't truly support arithmetic on floating point expressions, so we
1479 // have to manually parse unary prefixes.
1481 if (getLexer().is(AsmToken::Minus)) {
1484 } else if (getLexer().is(AsmToken::Plus))
1487 if (getLexer().isNot(AsmToken::Integer) &&
1488 getLexer().isNot(AsmToken::Real))
1489 return TokError("unexpected token in directive");
1491 // Convert to an APFloat.
1492 APFloat Value(Semantics);
1493 if (Value.convertFromString(getTok().getString(),
1494 APFloat::rmNearestTiesToEven) ==
1495 APFloat::opInvalidOp)
1496 return TokError("invalid floating point literal");
1500 // Consume the numeric token.
1503 // Emit the value as an integer.
1504 APInt AsInt = Value.bitcastToAPInt();
1505 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1506 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1508 if (getLexer().is(AsmToken::EndOfStatement))
1511 if (getLexer().isNot(AsmToken::Comma))
1512 return TokError("unexpected token in directive");
1521 /// ParseDirectiveSpace
1522 /// ::= .space expression [ , expression ]
1523 bool AsmParser::ParseDirectiveSpace() {
1524 CheckForValidSection();
1527 if (ParseAbsoluteExpression(NumBytes))
1530 int64_t FillExpr = 0;
1531 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1532 if (getLexer().isNot(AsmToken::Comma))
1533 return TokError("unexpected token in '.space' directive");
1536 if (ParseAbsoluteExpression(FillExpr))
1539 if (getLexer().isNot(AsmToken::EndOfStatement))
1540 return TokError("unexpected token in '.space' directive");
1546 return TokError("invalid number of bytes in '.space' directive");
1548 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1549 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1554 /// ParseDirectiveZero
1555 /// ::= .zero expression
1556 bool AsmParser::ParseDirectiveZero() {
1557 CheckForValidSection();
1560 if (ParseAbsoluteExpression(NumBytes))
1564 if (getLexer().is(AsmToken::Comma)) {
1566 if (ParseAbsoluteExpression(Val))
1570 if (getLexer().isNot(AsmToken::EndOfStatement))
1571 return TokError("unexpected token in '.zero' directive");
1575 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1580 /// ParseDirectiveFill
1581 /// ::= .fill expression , expression , expression
1582 bool AsmParser::ParseDirectiveFill() {
1583 CheckForValidSection();
1586 if (ParseAbsoluteExpression(NumValues))
1589 if (getLexer().isNot(AsmToken::Comma))
1590 return TokError("unexpected token in '.fill' directive");
1594 if (ParseAbsoluteExpression(FillSize))
1597 if (getLexer().isNot(AsmToken::Comma))
1598 return TokError("unexpected token in '.fill' directive");
1602 if (ParseAbsoluteExpression(FillExpr))
1605 if (getLexer().isNot(AsmToken::EndOfStatement))
1606 return TokError("unexpected token in '.fill' directive");
1610 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1611 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1613 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1614 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1619 /// ParseDirectiveOrg
1620 /// ::= .org expression [ , expression ]
1621 bool AsmParser::ParseDirectiveOrg() {
1622 CheckForValidSection();
1624 const MCExpr *Offset;
1625 if (ParseExpression(Offset))
1628 // Parse optional fill expression.
1629 int64_t FillExpr = 0;
1630 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1631 if (getLexer().isNot(AsmToken::Comma))
1632 return TokError("unexpected token in '.org' directive");
1635 if (ParseAbsoluteExpression(FillExpr))
1638 if (getLexer().isNot(AsmToken::EndOfStatement))
1639 return TokError("unexpected token in '.org' directive");
1644 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1645 // has to be relative to the current section.
1646 getStreamer().EmitValueToOffset(Offset, FillExpr);
1651 /// ParseDirectiveAlign
1652 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1653 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1654 CheckForValidSection();
1656 SMLoc AlignmentLoc = getLexer().getLoc();
1658 if (ParseAbsoluteExpression(Alignment))
1662 bool HasFillExpr = false;
1663 int64_t FillExpr = 0;
1664 int64_t MaxBytesToFill = 0;
1665 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1666 if (getLexer().isNot(AsmToken::Comma))
1667 return TokError("unexpected token in directive");
1670 // The fill expression can be omitted while specifying a maximum number of
1671 // alignment bytes, e.g:
1673 if (getLexer().isNot(AsmToken::Comma)) {
1675 if (ParseAbsoluteExpression(FillExpr))
1679 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1680 if (getLexer().isNot(AsmToken::Comma))
1681 return TokError("unexpected token in directive");
1684 MaxBytesLoc = getLexer().getLoc();
1685 if (ParseAbsoluteExpression(MaxBytesToFill))
1688 if (getLexer().isNot(AsmToken::EndOfStatement))
1689 return TokError("unexpected token in directive");
1698 // Compute alignment in bytes.
1700 // FIXME: Diagnose overflow.
1701 if (Alignment >= 32) {
1702 Error(AlignmentLoc, "invalid alignment value");
1706 Alignment = 1ULL << Alignment;
1709 // Diagnose non-sensical max bytes to align.
1710 if (MaxBytesLoc.isValid()) {
1711 if (MaxBytesToFill < 1) {
1712 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1713 "many bytes, ignoring maximum bytes expression");
1717 if (MaxBytesToFill >= Alignment) {
1718 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1724 // Check whether we should use optimal code alignment for this .align
1726 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1727 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1728 ValueSize == 1 && UseCodeAlign) {
1729 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1731 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1732 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1739 /// ParseDirectiveSymbolAttribute
1740 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1741 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1742 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1746 if (ParseIdentifier(Name))
1747 return TokError("expected identifier in directive");
1749 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1751 getStreamer().EmitSymbolAttribute(Sym, Attr);
1753 if (getLexer().is(AsmToken::EndOfStatement))
1756 if (getLexer().isNot(AsmToken::Comma))
1757 return TokError("unexpected token in directive");
1766 /// ParseDirectiveComm
1767 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1768 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1769 CheckForValidSection();
1771 SMLoc IDLoc = getLexer().getLoc();
1773 if (ParseIdentifier(Name))
1774 return TokError("expected identifier in directive");
1776 // Handle the identifier as the key symbol.
1777 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1779 if (getLexer().isNot(AsmToken::Comma))
1780 return TokError("unexpected token in directive");
1784 SMLoc SizeLoc = getLexer().getLoc();
1785 if (ParseAbsoluteExpression(Size))
1788 int64_t Pow2Alignment = 0;
1789 SMLoc Pow2AlignmentLoc;
1790 if (getLexer().is(AsmToken::Comma)) {
1792 Pow2AlignmentLoc = getLexer().getLoc();
1793 if (ParseAbsoluteExpression(Pow2Alignment))
1796 // If this target takes alignments in bytes (not log) validate and convert.
1797 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1798 if (!isPowerOf2_64(Pow2Alignment))
1799 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1800 Pow2Alignment = Log2_64(Pow2Alignment);
1804 if (getLexer().isNot(AsmToken::EndOfStatement))
1805 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1809 // NOTE: a size of zero for a .comm should create a undefined symbol
1810 // but a size of .lcomm creates a bss symbol of size zero.
1812 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1813 "be less than zero");
1815 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1816 // may internally end up wanting an alignment in bytes.
1817 // FIXME: Diagnose overflow.
1818 if (Pow2Alignment < 0)
1819 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1820 "alignment, can't be less than zero");
1822 if (!Sym->isUndefined())
1823 return Error(IDLoc, "invalid symbol redefinition");
1825 // '.lcomm' is equivalent to '.zerofill'.
1826 // Create the Symbol as a common or local common with Size and Pow2Alignment
1828 getStreamer().EmitZerofill(Ctx.getMachOSection(
1829 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1830 0, SectionKind::getBSS()),
1831 Sym, Size, 1 << Pow2Alignment);
1835 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1839 /// ParseDirectiveAbort
1840 /// ::= .abort [... message ...]
1841 bool AsmParser::ParseDirectiveAbort() {
1842 // FIXME: Use loc from directive.
1843 SMLoc Loc = getLexer().getLoc();
1845 StringRef Str = ParseStringToEndOfStatement();
1846 if (getLexer().isNot(AsmToken::EndOfStatement))
1847 return TokError("unexpected token in '.abort' directive");
1852 Error(Loc, ".abort detected. Assembly stopping.");
1854 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1855 // FIXME: Actually abort assembly here.
1860 /// ParseDirectiveInclude
1861 /// ::= .include "filename"
1862 bool AsmParser::ParseDirectiveInclude() {
1863 if (getLexer().isNot(AsmToken::String))
1864 return TokError("expected string in '.include' directive");
1866 std::string Filename = getTok().getString();
1867 SMLoc IncludeLoc = getLexer().getLoc();
1870 if (getLexer().isNot(AsmToken::EndOfStatement))
1871 return TokError("unexpected token in '.include' directive");
1873 // Strip the quotes.
1874 Filename = Filename.substr(1, Filename.size()-2);
1876 // Attempt to switch the lexer to the included file before consuming the end
1877 // of statement to avoid losing it when we switch.
1878 if (EnterIncludeFile(Filename)) {
1879 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1886 /// ParseDirectiveIf
1887 /// ::= .if expression
1888 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1889 TheCondStack.push_back(TheCondState);
1890 TheCondState.TheCond = AsmCond::IfCond;
1891 if(TheCondState.Ignore) {
1892 EatToEndOfStatement();
1896 if (ParseAbsoluteExpression(ExprValue))
1899 if (getLexer().isNot(AsmToken::EndOfStatement))
1900 return TokError("unexpected token in '.if' directive");
1904 TheCondState.CondMet = ExprValue;
1905 TheCondState.Ignore = !TheCondState.CondMet;
1911 /// ParseDirectiveElseIf
1912 /// ::= .elseif expression
1913 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1914 if (TheCondState.TheCond != AsmCond::IfCond &&
1915 TheCondState.TheCond != AsmCond::ElseIfCond)
1916 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1918 TheCondState.TheCond = AsmCond::ElseIfCond;
1920 bool LastIgnoreState = false;
1921 if (!TheCondStack.empty())
1922 LastIgnoreState = TheCondStack.back().Ignore;
1923 if (LastIgnoreState || TheCondState.CondMet) {
1924 TheCondState.Ignore = true;
1925 EatToEndOfStatement();
1929 if (ParseAbsoluteExpression(ExprValue))
1932 if (getLexer().isNot(AsmToken::EndOfStatement))
1933 return TokError("unexpected token in '.elseif' directive");
1936 TheCondState.CondMet = ExprValue;
1937 TheCondState.Ignore = !TheCondState.CondMet;
1943 /// ParseDirectiveElse
1945 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1946 if (getLexer().isNot(AsmToken::EndOfStatement))
1947 return TokError("unexpected token in '.else' directive");
1951 if (TheCondState.TheCond != AsmCond::IfCond &&
1952 TheCondState.TheCond != AsmCond::ElseIfCond)
1953 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1955 TheCondState.TheCond = AsmCond::ElseCond;
1956 bool LastIgnoreState = false;
1957 if (!TheCondStack.empty())
1958 LastIgnoreState = TheCondStack.back().Ignore;
1959 if (LastIgnoreState || TheCondState.CondMet)
1960 TheCondState.Ignore = true;
1962 TheCondState.Ignore = false;
1967 /// ParseDirectiveEndIf
1969 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1970 if (getLexer().isNot(AsmToken::EndOfStatement))
1971 return TokError("unexpected token in '.endif' directive");
1975 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1976 TheCondStack.empty())
1977 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1979 if (!TheCondStack.empty()) {
1980 TheCondState = TheCondStack.back();
1981 TheCondStack.pop_back();
1987 /// ParseDirectiveFile
1988 /// ::= .file [number] string
1989 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1990 // FIXME: I'm not sure what this is.
1991 int64_t FileNumber = -1;
1992 SMLoc FileNumberLoc = getLexer().getLoc();
1993 if (getLexer().is(AsmToken::Integer)) {
1994 FileNumber = getTok().getIntVal();
1998 return TokError("file number less than one");
2001 if (getLexer().isNot(AsmToken::String))
2002 return TokError("unexpected token in '.file' directive");
2004 StringRef Filename = getTok().getString();
2005 Filename = Filename.substr(1, Filename.size()-2);
2008 if (getLexer().isNot(AsmToken::EndOfStatement))
2009 return TokError("unexpected token in '.file' directive");
2011 if (FileNumber == -1)
2012 getStreamer().EmitFileDirective(Filename);
2014 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2015 Error(FileNumberLoc, "file number already allocated");
2021 /// ParseDirectiveLine
2022 /// ::= .line [number]
2023 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2024 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2025 if (getLexer().isNot(AsmToken::Integer))
2026 return TokError("unexpected token in '.line' directive");
2028 int64_t LineNumber = getTok().getIntVal();
2032 // FIXME: Do something with the .line.
2035 if (getLexer().isNot(AsmToken::EndOfStatement))
2036 return TokError("unexpected token in '.line' directive");
2042 /// ParseDirectiveLoc
2043 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2044 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2045 /// The first number is a file number, must have been previously assigned with
2046 /// a .file directive, the second number is the line number and optionally the
2047 /// third number is a column position (zero if not specified). The remaining
2048 /// optional items are .loc sub-directives.
2049 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2051 if (getLexer().isNot(AsmToken::Integer))
2052 return TokError("unexpected token in '.loc' directive");
2053 int64_t FileNumber = getTok().getIntVal();
2055 return TokError("file number less than one in '.loc' directive");
2056 if (!getContext().isValidDwarfFileNumber(FileNumber))
2057 return TokError("unassigned file number in '.loc' directive");
2060 int64_t LineNumber = 0;
2061 if (getLexer().is(AsmToken::Integer)) {
2062 LineNumber = getTok().getIntVal();
2064 return TokError("line number less than one in '.loc' directive");
2068 int64_t ColumnPos = 0;
2069 if (getLexer().is(AsmToken::Integer)) {
2070 ColumnPos = getTok().getIntVal();
2072 return TokError("column position less than zero in '.loc' directive");
2076 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2078 int64_t Discriminator = 0;
2079 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2081 if (getLexer().is(AsmToken::EndOfStatement))
2085 SMLoc Loc = getTok().getLoc();
2086 if (getParser().ParseIdentifier(Name))
2087 return TokError("unexpected token in '.loc' directive");
2089 if (Name == "basic_block")
2090 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2091 else if (Name == "prologue_end")
2092 Flags |= DWARF2_FLAG_PROLOGUE_END;
2093 else if (Name == "epilogue_begin")
2094 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2095 else if (Name == "is_stmt") {
2096 SMLoc Loc = getTok().getLoc();
2097 const MCExpr *Value;
2098 if (getParser().ParseExpression(Value))
2100 // The expression must be the constant 0 or 1.
2101 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2102 int Value = MCE->getValue();
2104 Flags &= ~DWARF2_FLAG_IS_STMT;
2105 else if (Value == 1)
2106 Flags |= DWARF2_FLAG_IS_STMT;
2108 return Error(Loc, "is_stmt value not 0 or 1");
2111 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2114 else if (Name == "isa") {
2115 SMLoc Loc = getTok().getLoc();
2116 const MCExpr *Value;
2117 if (getParser().ParseExpression(Value))
2119 // The expression must be a constant greater or equal to 0.
2120 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2121 int Value = MCE->getValue();
2123 return Error(Loc, "isa number less than zero");
2127 return Error(Loc, "isa number not a constant value");
2130 else if (Name == "discriminator") {
2131 if (getParser().ParseAbsoluteExpression(Discriminator))
2135 return Error(Loc, "unknown sub-directive in '.loc' directive");
2138 if (getLexer().is(AsmToken::EndOfStatement))
2143 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2144 Isa, Discriminator);
2149 /// ParseDirectiveStabs
2150 /// ::= .stabs string, number, number, number
2151 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2152 SMLoc DirectiveLoc) {
2153 return TokError("unsupported directive '" + Directive + "'");
2156 /// ParseDirectiveCFIStartProc
2157 /// ::= .cfi_startproc
2158 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2159 SMLoc DirectiveLoc) {
2160 return getStreamer().EmitCFIStartProc();
2163 /// ParseDirectiveCFIEndProc
2164 /// ::= .cfi_endproc
2165 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2166 return getStreamer().EmitCFIEndProc();
2169 /// ParseDirectiveCFIDefCfaOffset
2170 /// ::= .cfi_def_cfa_offset offset
2171 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2172 SMLoc DirectiveLoc) {
2174 if (getParser().ParseAbsoluteExpression(Offset))
2177 return getStreamer().EmitCFIDefCfaOffset(Offset);
2180 /// ParseDirectiveCFIDefCfaRegister
2181 /// ::= .cfi_def_cfa_register register
2182 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2183 SMLoc DirectiveLoc) {
2184 int64_t Register = 0;
2185 if (getParser().ParseAbsoluteExpression(Register))
2188 return getStreamer().EmitCFIDefCfaRegister(Register);
2191 /// ParseDirectiveCFIOffset
2192 /// ::= .cfi_off register, offset
2193 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2194 int64_t Register = 0;
2196 if (getParser().ParseAbsoluteExpression(Register))
2199 if (getLexer().isNot(AsmToken::Comma))
2200 return TokError("unexpected token in directive");
2203 if (getParser().ParseAbsoluteExpression(Offset))
2206 return getStreamer().EmitCFIOffset(Register, Offset);
2209 static bool isValidEncoding(int64_t Encoding) {
2210 if (Encoding & ~0xff)
2213 if (Encoding == dwarf::DW_EH_PE_omit)
2216 const unsigned Format = Encoding & 0xf;
2217 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2218 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2219 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2220 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2223 const unsigned Application = Encoding & 0xf0;
2224 if (Application != dwarf::DW_EH_PE_absptr &&
2225 Application != dwarf::DW_EH_PE_pcrel &&
2226 Application != dwarf::DW_EH_PE_indirect)
2232 /// ParseDirectiveCFIPersonalityOrLsda
2233 /// ::= .cfi_personality encoding, [symbol_name]
2234 /// ::= .cfi_lsda encoding, [symbol_name]
2235 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2236 SMLoc DirectiveLoc) {
2237 int64_t Encoding = 0;
2238 if (getParser().ParseAbsoluteExpression(Encoding))
2240 if (Encoding == dwarf::DW_EH_PE_omit)
2243 if (!isValidEncoding(Encoding))
2244 return TokError("unsupported encoding.");
2246 if (getLexer().isNot(AsmToken::Comma))
2247 return TokError("unexpected token in directive");
2251 if (getParser().ParseIdentifier(Name))
2252 return TokError("expected identifier in directive");
2254 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2256 if (IDVal == ".cfi_personality")
2257 return getStreamer().EmitCFIPersonality(Sym, Encoding);
2259 assert(IDVal == ".cfi_lsda");
2260 return getStreamer().EmitCFILsda(Sym);
2264 /// ParseDirectiveMacrosOnOff
2267 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2268 SMLoc DirectiveLoc) {
2269 if (getLexer().isNot(AsmToken::EndOfStatement))
2270 return Error(getLexer().getLoc(),
2271 "unexpected token in '" + Directive + "' directive");
2273 getParser().MacrosEnabled = Directive == ".macros_on";
2278 /// ParseDirectiveMacro
2280 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2281 SMLoc DirectiveLoc) {
2283 if (getParser().ParseIdentifier(Name))
2284 return TokError("expected identifier in directive");
2286 if (getLexer().isNot(AsmToken::EndOfStatement))
2287 return TokError("unexpected token in '.macro' directive");
2289 // Eat the end of statement.
2292 AsmToken EndToken, StartToken = getTok();
2294 // Lex the macro definition.
2296 // Check whether we have reached the end of the file.
2297 if (getLexer().is(AsmToken::Eof))
2298 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2300 // Otherwise, check whether we have reach the .endmacro.
2301 if (getLexer().is(AsmToken::Identifier) &&
2302 (getTok().getIdentifier() == ".endm" ||
2303 getTok().getIdentifier() == ".endmacro")) {
2304 EndToken = getTok();
2306 if (getLexer().isNot(AsmToken::EndOfStatement))
2307 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2312 // Otherwise, scan til the end of the statement.
2313 getParser().EatToEndOfStatement();
2316 if (getParser().MacroMap.lookup(Name)) {
2317 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2320 const char *BodyStart = StartToken.getLoc().getPointer();
2321 const char *BodyEnd = EndToken.getLoc().getPointer();
2322 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2323 getParser().MacroMap[Name] = new Macro(Name, Body);
2327 /// ParseDirectiveEndMacro
2330 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2331 SMLoc DirectiveLoc) {
2332 if (getLexer().isNot(AsmToken::EndOfStatement))
2333 return TokError("unexpected token in '" + Directive + "' directive");
2335 // If we are inside a macro instantiation, terminate the current
2337 if (!getParser().ActiveMacros.empty()) {
2338 getParser().HandleMacroExit();
2342 // Otherwise, this .endmacro is a stray entry in the file; well formed
2343 // .endmacro directives are handled during the macro definition parsing.
2344 return TokError("unexpected '" + Directive + "' in file, "
2345 "no current macro definition");
2348 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2349 getParser().CheckForValidSection();
2351 const MCExpr *Value;
2353 if (getParser().ParseExpression(Value))
2356 if (getLexer().isNot(AsmToken::EndOfStatement))
2357 return TokError("unexpected token in directive");
2359 if (DirName[1] == 's')
2360 getStreamer().EmitSLEB128Value(Value);
2362 getStreamer().EmitULEB128Value(Value);
2368 /// \brief Create an MCAsmParser instance.
2369 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2370 MCContext &C, MCStreamer &Out,
2371 const MCAsmInfo &MAI) {
2372 return new AsmParser(T, SM, C, Out, MAI);