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::ParseDirectiveCFIDefCfa>(
249 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
250 ".cfi_def_cfa_offset");
251 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
252 ".cfi_def_cfa_register");
253 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
256 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
258 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
260 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
262 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
265 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
269 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
277 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
278 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
279 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
280 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
281 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
282 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
283 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
284 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
285 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
286 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
287 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
288 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
289 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
291 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
292 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
293 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
295 bool ParseDirectiveLEB128(StringRef, SMLoc);
302 extern MCAsmParserExtension *createDarwinAsmParser();
303 extern MCAsmParserExtension *createELFAsmParser();
304 extern MCAsmParserExtension *createCOFFAsmParser();
308 enum { DEFAULT_ADDRSPACE = 0 };
310 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
311 MCStreamer &_Out, const MCAsmInfo &_MAI)
312 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
313 GenericParser(new GenericAsmParser), PlatformParser(0),
314 CurBuffer(0), MacrosEnabled(true) {
315 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
317 // Initialize the generic parser.
318 GenericParser->Initialize(*this);
320 // Initialize the platform / file format parser.
322 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
324 if (_MAI.hasMicrosoftFastStdCallMangling()) {
325 PlatformParser = createCOFFAsmParser();
326 PlatformParser->Initialize(*this);
327 } else if (_MAI.hasSubsectionsViaSymbols()) {
328 PlatformParser = createDarwinAsmParser();
329 PlatformParser->Initialize(*this);
331 PlatformParser = createELFAsmParser();
332 PlatformParser->Initialize(*this);
336 AsmParser::~AsmParser() {
337 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
339 // Destroy any macros.
340 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
341 ie = MacroMap.end(); it != ie; ++it)
342 delete it->getValue();
344 delete PlatformParser;
345 delete GenericParser;
348 void AsmParser::PrintMacroInstantiations() {
349 // Print the active macro instantiation stack.
350 for (std::vector<MacroInstantiation*>::const_reverse_iterator
351 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
352 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
356 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
357 PrintMessage(L, Msg, "warning");
358 PrintMacroInstantiations();
361 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
363 PrintMessage(L, Msg, "error");
364 PrintMacroInstantiations();
368 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
369 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
375 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
380 void AsmParser::JumpToLoc(SMLoc Loc) {
381 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
382 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
385 const AsmToken &AsmParser::Lex() {
386 const AsmToken *tok = &Lexer.Lex();
388 if (tok->is(AsmToken::Eof)) {
389 // If this is the end of an included file, pop the parent file off the
391 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
392 if (ParentIncludeLoc != SMLoc()) {
393 JumpToLoc(ParentIncludeLoc);
398 if (tok->is(AsmToken::Error))
399 Error(Lexer.getErrLoc(), Lexer.getErr());
404 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
405 // Create the initial section, if requested.
406 if (!NoInitialTextSection)
413 AsmCond StartingCondState = TheCondState;
415 // While we have input, parse each statement.
416 while (Lexer.isNot(AsmToken::Eof)) {
417 if (!ParseStatement()) continue;
419 // We had an error, validate that one was emitted and recover by skipping to
421 assert(HadError && "Parse statement returned an error, but none emitted!");
422 EatToEndOfStatement();
425 if (TheCondState.TheCond != StartingCondState.TheCond ||
426 TheCondState.Ignore != StartingCondState.Ignore)
427 return TokError("unmatched .ifs or .elses");
429 // Check to see there are no empty DwarfFile slots.
430 const std::vector<MCDwarfFile *> &MCDwarfFiles =
431 getContext().getMCDwarfFiles();
432 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
433 if (!MCDwarfFiles[i])
434 TokError("unassigned file number: " + Twine(i) + " for .file directives");
437 // Finalize the output stream if there are no errors and if the client wants
439 if (!HadError && !NoFinalize)
445 void AsmParser::CheckForValidSection() {
446 if (!getStreamer().getCurrentSection()) {
447 TokError("expected section directive before assembly directive");
448 Out.SwitchSection(Ctx.getMachOSection(
450 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
451 0, SectionKind::getText()));
455 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
456 void AsmParser::EatToEndOfStatement() {
457 while (Lexer.isNot(AsmToken::EndOfStatement) &&
458 Lexer.isNot(AsmToken::Eof))
462 if (Lexer.is(AsmToken::EndOfStatement))
466 StringRef AsmParser::ParseStringToEndOfStatement() {
467 const char *Start = getTok().getLoc().getPointer();
469 while (Lexer.isNot(AsmToken::EndOfStatement) &&
470 Lexer.isNot(AsmToken::Eof))
473 const char *End = getTok().getLoc().getPointer();
474 return StringRef(Start, End - Start);
477 /// ParseParenExpr - Parse a paren expression and return it.
478 /// NOTE: This assumes the leading '(' has already been consumed.
480 /// parenexpr ::= expr)
482 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
483 if (ParseExpression(Res)) return true;
484 if (Lexer.isNot(AsmToken::RParen))
485 return TokError("expected ')' in parentheses expression");
486 EndLoc = Lexer.getLoc();
491 /// ParsePrimaryExpr - Parse a primary expression and return it.
492 /// primaryexpr ::= (parenexpr
493 /// primaryexpr ::= symbol
494 /// primaryexpr ::= number
495 /// primaryexpr ::= '.'
496 /// primaryexpr ::= ~,+,- primaryexpr
497 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
498 switch (Lexer.getKind()) {
500 return TokError("unknown token in expression");
501 case AsmToken::Exclaim:
502 Lex(); // Eat the operator.
503 if (ParsePrimaryExpr(Res, EndLoc))
505 Res = MCUnaryExpr::CreateLNot(Res, getContext());
507 case AsmToken::Dollar:
508 case AsmToken::String:
509 case AsmToken::Identifier: {
510 EndLoc = Lexer.getLoc();
512 StringRef Identifier;
513 if (ParseIdentifier(Identifier))
516 // This is a symbol reference.
517 std::pair<StringRef, StringRef> Split = Identifier.split('@');
518 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
520 // Lookup the symbol variant if used.
521 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
522 if (Split.first.size() != Identifier.size()) {
523 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
524 if (Variant == MCSymbolRefExpr::VK_Invalid) {
525 Variant = MCSymbolRefExpr::VK_None;
526 return TokError("invalid variant '" + Split.second + "'");
530 // If this is an absolute variable reference, substitute it now to preserve
531 // semantics in the face of reassignment.
532 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
534 return Error(EndLoc, "unexpected modifier on variable reference");
536 Res = Sym->getVariableValue();
540 // Otherwise create a symbol ref.
541 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
544 case AsmToken::Integer: {
545 SMLoc Loc = getTok().getLoc();
546 int64_t IntVal = getTok().getIntVal();
547 Res = MCConstantExpr::Create(IntVal, getContext());
548 EndLoc = Lexer.getLoc();
550 // Look for 'b' or 'f' following an Integer as a directional label
551 if (Lexer.getKind() == AsmToken::Identifier) {
552 StringRef IDVal = getTok().getString();
553 if (IDVal == "f" || IDVal == "b"){
554 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
555 IDVal == "f" ? 1 : 0);
556 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
558 if(IDVal == "b" && Sym->isUndefined())
559 return Error(Loc, "invalid reference to undefined symbol");
560 EndLoc = Lexer.getLoc();
561 Lex(); // Eat identifier.
566 case AsmToken::Dot: {
567 // This is a '.' reference, which references the current PC. Emit a
568 // temporary label to the streamer and refer to it.
569 MCSymbol *Sym = Ctx.CreateTempSymbol();
571 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
572 EndLoc = Lexer.getLoc();
573 Lex(); // Eat identifier.
577 case AsmToken::LParen:
578 Lex(); // Eat the '('.
579 return ParseParenExpr(Res, EndLoc);
580 case AsmToken::Minus:
581 Lex(); // Eat the operator.
582 if (ParsePrimaryExpr(Res, EndLoc))
584 Res = MCUnaryExpr::CreateMinus(Res, getContext());
587 Lex(); // Eat the operator.
588 if (ParsePrimaryExpr(Res, EndLoc))
590 Res = MCUnaryExpr::CreatePlus(Res, getContext());
592 case AsmToken::Tilde:
593 Lex(); // Eat the operator.
594 if (ParsePrimaryExpr(Res, EndLoc))
596 Res = MCUnaryExpr::CreateNot(Res, getContext());
601 bool AsmParser::ParseExpression(const MCExpr *&Res) {
603 return ParseExpression(Res, EndLoc);
607 AsmParser::ApplyModifierToExpr(const MCExpr *E,
608 MCSymbolRefExpr::VariantKind Variant) {
609 // Recurse over the given expression, rebuilding it to apply the given variant
610 // if there is exactly one symbol.
611 switch (E->getKind()) {
613 case MCExpr::Constant:
616 case MCExpr::SymbolRef: {
617 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
619 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
620 TokError("invalid variant on expression '" +
621 getTok().getIdentifier() + "' (already modified)");
625 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
628 case MCExpr::Unary: {
629 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
630 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
633 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
636 case MCExpr::Binary: {
637 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
638 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
639 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
644 if (!LHS) LHS = BE->getLHS();
645 if (!RHS) RHS = BE->getRHS();
647 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
651 assert(0 && "Invalid expression kind!");
655 /// ParseExpression - Parse an expression and return it.
657 /// expr ::= expr +,- expr -> lowest.
658 /// expr ::= expr |,^,&,! expr -> middle.
659 /// expr ::= expr *,/,%,<<,>> expr -> highest.
660 /// expr ::= primaryexpr
662 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
663 // Parse the expression.
665 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
668 // As a special case, we support 'a op b @ modifier' by rewriting the
669 // expression to include the modifier. This is inefficient, but in general we
670 // expect users to use 'a@modifier op b'.
671 if (Lexer.getKind() == AsmToken::At) {
674 if (Lexer.isNot(AsmToken::Identifier))
675 return TokError("unexpected symbol modifier following '@'");
677 MCSymbolRefExpr::VariantKind Variant =
678 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
679 if (Variant == MCSymbolRefExpr::VK_Invalid)
680 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
682 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
684 return TokError("invalid modifier '" + getTok().getIdentifier() +
685 "' (no symbols present)");
693 // Try to constant fold it up front, if possible.
695 if (Res->EvaluateAsAbsolute(Value))
696 Res = MCConstantExpr::Create(Value, getContext());
701 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
703 return ParseParenExpr(Res, EndLoc) ||
704 ParseBinOpRHS(1, Res, EndLoc);
707 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
710 SMLoc StartLoc = Lexer.getLoc();
711 if (ParseExpression(Expr))
714 if (!Expr->EvaluateAsAbsolute(Res))
715 return Error(StartLoc, "expected absolute expression");
720 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
721 MCBinaryExpr::Opcode &Kind) {
724 return 0; // not a binop.
726 // Lowest Precedence: &&, ||, @
727 case AsmToken::AmpAmp:
728 Kind = MCBinaryExpr::LAnd;
730 case AsmToken::PipePipe:
731 Kind = MCBinaryExpr::LOr;
735 // Low Precedence: |, &, ^
737 // FIXME: gas seems to support '!' as an infix operator?
739 Kind = MCBinaryExpr::Or;
741 case AsmToken::Caret:
742 Kind = MCBinaryExpr::Xor;
745 Kind = MCBinaryExpr::And;
748 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
749 case AsmToken::EqualEqual:
750 Kind = MCBinaryExpr::EQ;
752 case AsmToken::ExclaimEqual:
753 case AsmToken::LessGreater:
754 Kind = MCBinaryExpr::NE;
757 Kind = MCBinaryExpr::LT;
759 case AsmToken::LessEqual:
760 Kind = MCBinaryExpr::LTE;
762 case AsmToken::Greater:
763 Kind = MCBinaryExpr::GT;
765 case AsmToken::GreaterEqual:
766 Kind = MCBinaryExpr::GTE;
769 // High Intermediate Precedence: +, -
771 Kind = MCBinaryExpr::Add;
773 case AsmToken::Minus:
774 Kind = MCBinaryExpr::Sub;
777 // Highest Precedence: *, /, %, <<, >>
779 Kind = MCBinaryExpr::Mul;
781 case AsmToken::Slash:
782 Kind = MCBinaryExpr::Div;
784 case AsmToken::Percent:
785 Kind = MCBinaryExpr::Mod;
787 case AsmToken::LessLess:
788 Kind = MCBinaryExpr::Shl;
790 case AsmToken::GreaterGreater:
791 Kind = MCBinaryExpr::Shr;
797 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
798 /// Res contains the LHS of the expression on input.
799 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
802 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
803 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
805 // If the next token is lower precedence than we are allowed to eat, return
806 // successfully with what we ate already.
807 if (TokPrec < Precedence)
812 // Eat the next primary expression.
814 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
816 // If BinOp binds less tightly with RHS than the operator after RHS, let
817 // the pending operator take RHS as its LHS.
818 MCBinaryExpr::Opcode Dummy;
819 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
820 if (TokPrec < NextTokPrec) {
821 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
824 // Merge LHS and RHS according to operator.
825 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
833 /// ::= EndOfStatement
834 /// ::= Label* Directive ...Operands... EndOfStatement
835 /// ::= Label* Identifier OperandList* EndOfStatement
836 bool AsmParser::ParseStatement() {
837 if (Lexer.is(AsmToken::EndOfStatement)) {
843 // Statements always start with an identifier or are a full line comment.
844 AsmToken ID = getTok();
845 SMLoc IDLoc = ID.getLoc();
847 int64_t LocalLabelVal = -1;
848 // A full line comment is a '#' as the first token.
849 if (Lexer.is(AsmToken::Hash)) {
850 EatToEndOfStatement();
853 // Allow an integer followed by a ':' as a directional local label.
854 if (Lexer.is(AsmToken::Integer)) {
855 LocalLabelVal = getTok().getIntVal();
856 if (LocalLabelVal < 0) {
857 if (!TheCondState.Ignore)
858 return TokError("unexpected token at start of statement");
862 IDVal = getTok().getString();
863 Lex(); // Consume the integer token to be used as an identifier token.
864 if (Lexer.getKind() != AsmToken::Colon) {
865 if (!TheCondState.Ignore)
866 return TokError("unexpected token at start of statement");
870 else if (ParseIdentifier(IDVal)) {
871 if (!TheCondState.Ignore)
872 return TokError("unexpected token at start of statement");
876 // Handle conditional assembly here before checking for skipping. We
877 // have to do this so that .endif isn't skipped in a ".if 0" block for
880 return ParseDirectiveIf(IDLoc);
881 if (IDVal == ".elseif")
882 return ParseDirectiveElseIf(IDLoc);
883 if (IDVal == ".else")
884 return ParseDirectiveElse(IDLoc);
885 if (IDVal == ".endif")
886 return ParseDirectiveEndIf(IDLoc);
888 // If we are in a ".if 0" block, ignore this statement.
889 if (TheCondState.Ignore) {
890 EatToEndOfStatement();
894 // FIXME: Recurse on local labels?
896 // See what kind of statement we have.
897 switch (Lexer.getKind()) {
898 case AsmToken::Colon: {
899 CheckForValidSection();
901 // identifier ':' -> Label.
904 // Diagnose attempt to use a variable as a label.
906 // FIXME: Diagnostics. Note the location of the definition as a label.
907 // FIXME: This doesn't diagnose assignment to a symbol which has been
908 // implicitly marked as external.
910 if (LocalLabelVal == -1)
911 Sym = getContext().GetOrCreateSymbol(IDVal);
913 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
914 if (!Sym->isUndefined() || Sym->isVariable())
915 return Error(IDLoc, "invalid symbol redefinition");
920 // Consume any end of statement token, if present, to avoid spurious
921 // AddBlankLine calls().
922 if (Lexer.is(AsmToken::EndOfStatement)) {
924 if (Lexer.is(AsmToken::Eof))
928 return ParseStatement();
931 case AsmToken::Equal:
932 // identifier '=' ... -> assignment statement
935 return ParseAssignment(IDVal);
937 default: // Normal instruction or directive.
941 // If macros are enabled, check to see if this is a macro instantiation.
943 if (const Macro *M = MacroMap.lookup(IDVal))
944 return HandleMacroEntry(IDVal, IDLoc, M);
946 // Otherwise, we have a normal instruction or directive.
947 if (IDVal[0] == '.') {
948 // Assembler features
949 if (IDVal == ".set" || IDVal == ".equ")
950 return ParseDirectiveSet(IDVal);
954 if (IDVal == ".ascii")
955 return ParseDirectiveAscii(IDVal, false);
956 if (IDVal == ".asciz" || IDVal == ".string")
957 return ParseDirectiveAscii(IDVal, true);
959 if (IDVal == ".byte")
960 return ParseDirectiveValue(1);
961 if (IDVal == ".short")
962 return ParseDirectiveValue(2);
963 if (IDVal == ".value")
964 return ParseDirectiveValue(2);
965 if (IDVal == ".2byte")
966 return ParseDirectiveValue(2);
967 if (IDVal == ".long")
968 return ParseDirectiveValue(4);
970 return ParseDirectiveValue(4);
971 if (IDVal == ".4byte")
972 return ParseDirectiveValue(4);
973 if (IDVal == ".quad")
974 return ParseDirectiveValue(8);
975 if (IDVal == ".8byte")
976 return ParseDirectiveValue(8);
977 if (IDVal == ".single")
978 return ParseDirectiveRealValue(APFloat::IEEEsingle);
979 if (IDVal == ".double")
980 return ParseDirectiveRealValue(APFloat::IEEEdouble);
982 if (IDVal == ".align") {
983 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
984 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
986 if (IDVal == ".align32") {
987 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
988 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
990 if (IDVal == ".balign")
991 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
992 if (IDVal == ".balignw")
993 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
994 if (IDVal == ".balignl")
995 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
996 if (IDVal == ".p2align")
997 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
998 if (IDVal == ".p2alignw")
999 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1000 if (IDVal == ".p2alignl")
1001 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1003 if (IDVal == ".org")
1004 return ParseDirectiveOrg();
1006 if (IDVal == ".fill")
1007 return ParseDirectiveFill();
1008 if (IDVal == ".space")
1009 return ParseDirectiveSpace();
1010 if (IDVal == ".zero")
1011 return ParseDirectiveZero();
1013 // Symbol attribute directives
1015 if (IDVal == ".globl" || IDVal == ".global")
1016 return ParseDirectiveSymbolAttribute(MCSA_Global);
1017 // ELF only? Should it be here?
1018 if (IDVal == ".local")
1019 return ParseDirectiveSymbolAttribute(MCSA_Local);
1020 if (IDVal == ".hidden")
1021 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1022 if (IDVal == ".indirect_symbol")
1023 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1024 if (IDVal == ".internal")
1025 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1026 if (IDVal == ".lazy_reference")
1027 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1028 if (IDVal == ".no_dead_strip")
1029 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1030 if (IDVal == ".symbol_resolver")
1031 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1032 if (IDVal == ".private_extern")
1033 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1034 if (IDVal == ".protected")
1035 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1036 if (IDVal == ".reference")
1037 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1038 if (IDVal == ".weak")
1039 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1040 if (IDVal == ".weak_definition")
1041 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1042 if (IDVal == ".weak_reference")
1043 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1044 if (IDVal == ".weak_def_can_be_hidden")
1045 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1047 if (IDVal == ".comm")
1048 return ParseDirectiveComm(/*IsLocal=*/false);
1049 if (IDVal == ".lcomm")
1050 return ParseDirectiveComm(/*IsLocal=*/true);
1052 if (IDVal == ".abort")
1053 return ParseDirectiveAbort();
1054 if (IDVal == ".include")
1055 return ParseDirectiveInclude();
1057 // Look up the handler in the handler table.
1058 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1059 DirectiveMap.lookup(IDVal);
1061 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1063 // Target hook for parsing target specific directives.
1064 if (!getTargetParser().ParseDirective(ID))
1067 Warning(IDLoc, "ignoring directive for now");
1068 EatToEndOfStatement();
1072 CheckForValidSection();
1074 // Canonicalize the opcode to lower case.
1075 SmallString<128> Opcode;
1076 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1077 Opcode.push_back(tolower(IDVal[i]));
1079 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1080 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1083 // Dump the parsed representation, if requested.
1084 if (getShowParsedOperands()) {
1085 SmallString<256> Str;
1086 raw_svector_ostream OS(Str);
1087 OS << "parsed instruction: [";
1088 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1091 ParsedOperands[i]->dump(OS);
1095 PrintMessage(IDLoc, OS.str(), "note");
1098 // If parsing succeeded, match the instruction.
1100 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1103 // Free any parsed operands.
1104 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1105 delete ParsedOperands[i];
1107 // Don't skip the rest of the line, the instruction parser is responsible for
1112 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1113 const std::vector<std::vector<AsmToken> > &A)
1114 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1116 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1117 // to hold the macro body with substitutions.
1118 SmallString<256> Buf;
1119 raw_svector_ostream OS(Buf);
1121 StringRef Body = M->Body;
1122 while (!Body.empty()) {
1123 // Scan for the next substitution.
1124 std::size_t End = Body.size(), Pos = 0;
1125 for (; Pos != End; ++Pos) {
1126 // Check for a substitution or escape.
1127 if (Body[Pos] != '$' || Pos + 1 == End)
1130 char Next = Body[Pos + 1];
1131 if (Next == '$' || Next == 'n' || isdigit(Next))
1136 OS << Body.slice(0, Pos);
1138 // Check if we reached the end.
1142 switch (Body[Pos+1]) {
1148 // $n => number of arguments
1153 // $[0-9] => argument
1155 // Missing arguments are ignored.
1156 unsigned Index = Body[Pos+1] - '0';
1157 if (Index >= A.size())
1160 // Otherwise substitute with the token values, with spaces eliminated.
1161 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1162 ie = A[Index].end(); it != ie; ++it)
1163 OS << it->getString();
1168 // Update the scan point.
1169 Body = Body.substr(Pos + 2);
1172 // We include the .endmacro in the buffer as our queue to exit the macro
1174 OS << ".endmacro\n";
1176 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1179 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1181 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1182 // this, although we should protect against infinite loops.
1183 if (ActiveMacros.size() == 20)
1184 return TokError("macros cannot be nested more than 20 levels deep");
1186 // Parse the macro instantiation arguments.
1187 std::vector<std::vector<AsmToken> > MacroArguments;
1188 MacroArguments.push_back(std::vector<AsmToken>());
1189 unsigned ParenLevel = 0;
1191 if (Lexer.is(AsmToken::Eof))
1192 return TokError("unexpected token in macro instantiation");
1193 if (Lexer.is(AsmToken::EndOfStatement))
1196 // If we aren't inside parentheses and this is a comma, start a new token
1198 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1199 MacroArguments.push_back(std::vector<AsmToken>());
1201 // Adjust the current parentheses level.
1202 if (Lexer.is(AsmToken::LParen))
1204 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1207 // Append the token to the current argument list.
1208 MacroArguments.back().push_back(getTok());
1213 // Create the macro instantiation object and add to the current macro
1214 // instantiation stack.
1215 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1218 ActiveMacros.push_back(MI);
1220 // Jump to the macro instantiation and prime the lexer.
1221 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1222 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1228 void AsmParser::HandleMacroExit() {
1229 // Jump to the EndOfStatement we should return to, and consume it.
1230 JumpToLoc(ActiveMacros.back()->ExitLoc);
1233 // Pop the instantiation entry.
1234 delete ActiveMacros.back();
1235 ActiveMacros.pop_back();
1238 static void MarkUsed(const MCExpr *Value) {
1239 switch (Value->getKind()) {
1240 case MCExpr::Binary:
1241 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1242 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1244 case MCExpr::Target:
1245 case MCExpr::Constant:
1247 case MCExpr::SymbolRef: {
1248 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1252 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1257 bool AsmParser::ParseAssignment(StringRef Name) {
1258 // FIXME: Use better location, we should use proper tokens.
1259 SMLoc EqualLoc = Lexer.getLoc();
1261 const MCExpr *Value;
1262 if (ParseExpression(Value))
1267 if (Lexer.isNot(AsmToken::EndOfStatement))
1268 return TokError("unexpected token in assignment");
1270 // Eat the end of statement marker.
1273 // Validate that the LHS is allowed to be a variable (either it has not been
1274 // used as a symbol, or it is an absolute symbol).
1275 MCSymbol *Sym = getContext().LookupSymbol(Name);
1277 // Diagnose assignment to a label.
1279 // FIXME: Diagnostics. Note the location of the definition as a label.
1280 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1281 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1282 ; // Allow redefinitions of undefined symbols only used in directives.
1283 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1284 return Error(EqualLoc, "redefinition of '" + Name + "'");
1285 else if (!Sym->isVariable())
1286 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1287 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1288 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1291 // Don't count these checks as uses.
1292 Sym->setUsed(false);
1294 Sym = getContext().GetOrCreateSymbol(Name);
1296 // FIXME: Handle '.'.
1298 // Do the assignment.
1299 Out.EmitAssignment(Sym, Value);
1304 /// ParseIdentifier:
1307 bool AsmParser::ParseIdentifier(StringRef &Res) {
1308 // The assembler has relaxed rules for accepting identifiers, in particular we
1309 // allow things like '.globl $foo', which would normally be separate
1310 // tokens. At this level, we have already lexed so we cannot (currently)
1311 // handle this as a context dependent token, instead we detect adjacent tokens
1312 // and return the combined identifier.
1313 if (Lexer.is(AsmToken::Dollar)) {
1314 SMLoc DollarLoc = getLexer().getLoc();
1316 // Consume the dollar sign, and check for a following identifier.
1318 if (Lexer.isNot(AsmToken::Identifier))
1321 // We have a '$' followed by an identifier, make sure they are adjacent.
1322 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1325 // Construct the joined identifier and consume the token.
1326 Res = StringRef(DollarLoc.getPointer(),
1327 getTok().getIdentifier().size() + 1);
1332 if (Lexer.isNot(AsmToken::Identifier) &&
1333 Lexer.isNot(AsmToken::String))
1336 Res = getTok().getIdentifier();
1338 Lex(); // Consume the identifier token.
1343 /// ParseDirectiveSet:
1344 /// ::= .set identifier ',' expression
1345 bool AsmParser::ParseDirectiveSet(StringRef IDVal) {
1348 if (ParseIdentifier(Name))
1349 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1351 if (getLexer().isNot(AsmToken::Comma))
1352 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1355 return ParseAssignment(Name);
1358 bool AsmParser::ParseEscapedString(std::string &Data) {
1359 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1362 StringRef Str = getTok().getStringContents();
1363 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1364 if (Str[i] != '\\') {
1369 // Recognize escaped characters. Note that this escape semantics currently
1370 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1373 return TokError("unexpected backslash at end of string");
1375 // Recognize octal sequences.
1376 if ((unsigned) (Str[i] - '0') <= 7) {
1377 // Consume up to three octal characters.
1378 unsigned Value = Str[i] - '0';
1380 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1382 Value = Value * 8 + (Str[i] - '0');
1384 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1386 Value = Value * 8 + (Str[i] - '0');
1391 return TokError("invalid octal escape sequence (out of range)");
1393 Data += (unsigned char) Value;
1397 // Otherwise recognize individual escapes.
1400 // Just reject invalid escape sequences for now.
1401 return TokError("invalid escape sequence (unrecognized character)");
1403 case 'b': Data += '\b'; break;
1404 case 'f': Data += '\f'; break;
1405 case 'n': Data += '\n'; break;
1406 case 'r': Data += '\r'; break;
1407 case 't': Data += '\t'; break;
1408 case '"': Data += '"'; break;
1409 case '\\': Data += '\\'; break;
1416 /// ParseDirectiveAscii:
1417 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1418 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1419 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1420 CheckForValidSection();
1423 if (getLexer().isNot(AsmToken::String))
1424 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1427 if (ParseEscapedString(Data))
1430 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1432 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1436 if (getLexer().is(AsmToken::EndOfStatement))
1439 if (getLexer().isNot(AsmToken::Comma))
1440 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1449 /// ParseDirectiveValue
1450 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1451 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1452 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1453 CheckForValidSection();
1456 const MCExpr *Value;
1457 if (ParseExpression(Value))
1460 // Special case constant expressions to match code generator.
1461 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1462 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1464 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1466 if (getLexer().is(AsmToken::EndOfStatement))
1469 // FIXME: Improve diagnostic.
1470 if (getLexer().isNot(AsmToken::Comma))
1471 return TokError("unexpected token in directive");
1480 /// ParseDirectiveRealValue
1481 /// ::= (.single | .double) [ expression (, expression)* ]
1482 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1483 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1484 CheckForValidSection();
1487 // We don't truly support arithmetic on floating point expressions, so we
1488 // have to manually parse unary prefixes.
1490 if (getLexer().is(AsmToken::Minus)) {
1493 } else if (getLexer().is(AsmToken::Plus))
1496 if (getLexer().isNot(AsmToken::Integer) &&
1497 getLexer().isNot(AsmToken::Real))
1498 return TokError("unexpected token in directive");
1500 // Convert to an APFloat.
1501 APFloat Value(Semantics);
1502 if (Value.convertFromString(getTok().getString(),
1503 APFloat::rmNearestTiesToEven) ==
1504 APFloat::opInvalidOp)
1505 return TokError("invalid floating point literal");
1509 // Consume the numeric token.
1512 // Emit the value as an integer.
1513 APInt AsInt = Value.bitcastToAPInt();
1514 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1515 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1517 if (getLexer().is(AsmToken::EndOfStatement))
1520 if (getLexer().isNot(AsmToken::Comma))
1521 return TokError("unexpected token in directive");
1530 /// ParseDirectiveSpace
1531 /// ::= .space expression [ , expression ]
1532 bool AsmParser::ParseDirectiveSpace() {
1533 CheckForValidSection();
1536 if (ParseAbsoluteExpression(NumBytes))
1539 int64_t FillExpr = 0;
1540 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1541 if (getLexer().isNot(AsmToken::Comma))
1542 return TokError("unexpected token in '.space' directive");
1545 if (ParseAbsoluteExpression(FillExpr))
1548 if (getLexer().isNot(AsmToken::EndOfStatement))
1549 return TokError("unexpected token in '.space' directive");
1555 return TokError("invalid number of bytes in '.space' directive");
1557 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1558 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1563 /// ParseDirectiveZero
1564 /// ::= .zero expression
1565 bool AsmParser::ParseDirectiveZero() {
1566 CheckForValidSection();
1569 if (ParseAbsoluteExpression(NumBytes))
1573 if (getLexer().is(AsmToken::Comma)) {
1575 if (ParseAbsoluteExpression(Val))
1579 if (getLexer().isNot(AsmToken::EndOfStatement))
1580 return TokError("unexpected token in '.zero' directive");
1584 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1589 /// ParseDirectiveFill
1590 /// ::= .fill expression , expression , expression
1591 bool AsmParser::ParseDirectiveFill() {
1592 CheckForValidSection();
1595 if (ParseAbsoluteExpression(NumValues))
1598 if (getLexer().isNot(AsmToken::Comma))
1599 return TokError("unexpected token in '.fill' directive");
1603 if (ParseAbsoluteExpression(FillSize))
1606 if (getLexer().isNot(AsmToken::Comma))
1607 return TokError("unexpected token in '.fill' directive");
1611 if (ParseAbsoluteExpression(FillExpr))
1614 if (getLexer().isNot(AsmToken::EndOfStatement))
1615 return TokError("unexpected token in '.fill' directive");
1619 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1620 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1622 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1623 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1628 /// ParseDirectiveOrg
1629 /// ::= .org expression [ , expression ]
1630 bool AsmParser::ParseDirectiveOrg() {
1631 CheckForValidSection();
1633 const MCExpr *Offset;
1634 if (ParseExpression(Offset))
1637 // Parse optional fill expression.
1638 int64_t FillExpr = 0;
1639 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1640 if (getLexer().isNot(AsmToken::Comma))
1641 return TokError("unexpected token in '.org' directive");
1644 if (ParseAbsoluteExpression(FillExpr))
1647 if (getLexer().isNot(AsmToken::EndOfStatement))
1648 return TokError("unexpected token in '.org' directive");
1653 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1654 // has to be relative to the current section.
1655 getStreamer().EmitValueToOffset(Offset, FillExpr);
1660 /// ParseDirectiveAlign
1661 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1662 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1663 CheckForValidSection();
1665 SMLoc AlignmentLoc = getLexer().getLoc();
1667 if (ParseAbsoluteExpression(Alignment))
1671 bool HasFillExpr = false;
1672 int64_t FillExpr = 0;
1673 int64_t MaxBytesToFill = 0;
1674 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1675 if (getLexer().isNot(AsmToken::Comma))
1676 return TokError("unexpected token in directive");
1679 // The fill expression can be omitted while specifying a maximum number of
1680 // alignment bytes, e.g:
1682 if (getLexer().isNot(AsmToken::Comma)) {
1684 if (ParseAbsoluteExpression(FillExpr))
1688 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1689 if (getLexer().isNot(AsmToken::Comma))
1690 return TokError("unexpected token in directive");
1693 MaxBytesLoc = getLexer().getLoc();
1694 if (ParseAbsoluteExpression(MaxBytesToFill))
1697 if (getLexer().isNot(AsmToken::EndOfStatement))
1698 return TokError("unexpected token in directive");
1707 // Compute alignment in bytes.
1709 // FIXME: Diagnose overflow.
1710 if (Alignment >= 32) {
1711 Error(AlignmentLoc, "invalid alignment value");
1715 Alignment = 1ULL << Alignment;
1718 // Diagnose non-sensical max bytes to align.
1719 if (MaxBytesLoc.isValid()) {
1720 if (MaxBytesToFill < 1) {
1721 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1722 "many bytes, ignoring maximum bytes expression");
1726 if (MaxBytesToFill >= Alignment) {
1727 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1733 // Check whether we should use optimal code alignment for this .align
1735 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1736 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1737 ValueSize == 1 && UseCodeAlign) {
1738 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1740 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1741 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1748 /// ParseDirectiveSymbolAttribute
1749 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1750 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1751 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1755 if (ParseIdentifier(Name))
1756 return TokError("expected identifier in directive");
1758 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1760 getStreamer().EmitSymbolAttribute(Sym, Attr);
1762 if (getLexer().is(AsmToken::EndOfStatement))
1765 if (getLexer().isNot(AsmToken::Comma))
1766 return TokError("unexpected token in directive");
1775 /// ParseDirectiveComm
1776 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1777 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1778 CheckForValidSection();
1780 SMLoc IDLoc = getLexer().getLoc();
1782 if (ParseIdentifier(Name))
1783 return TokError("expected identifier in directive");
1785 // Handle the identifier as the key symbol.
1786 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1788 if (getLexer().isNot(AsmToken::Comma))
1789 return TokError("unexpected token in directive");
1793 SMLoc SizeLoc = getLexer().getLoc();
1794 if (ParseAbsoluteExpression(Size))
1797 int64_t Pow2Alignment = 0;
1798 SMLoc Pow2AlignmentLoc;
1799 if (getLexer().is(AsmToken::Comma)) {
1801 Pow2AlignmentLoc = getLexer().getLoc();
1802 if (ParseAbsoluteExpression(Pow2Alignment))
1805 // If this target takes alignments in bytes (not log) validate and convert.
1806 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1807 if (!isPowerOf2_64(Pow2Alignment))
1808 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1809 Pow2Alignment = Log2_64(Pow2Alignment);
1813 if (getLexer().isNot(AsmToken::EndOfStatement))
1814 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1818 // NOTE: a size of zero for a .comm should create a undefined symbol
1819 // but a size of .lcomm creates a bss symbol of size zero.
1821 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1822 "be less than zero");
1824 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1825 // may internally end up wanting an alignment in bytes.
1826 // FIXME: Diagnose overflow.
1827 if (Pow2Alignment < 0)
1828 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1829 "alignment, can't be less than zero");
1831 if (!Sym->isUndefined())
1832 return Error(IDLoc, "invalid symbol redefinition");
1834 // '.lcomm' is equivalent to '.zerofill'.
1835 // Create the Symbol as a common or local common with Size and Pow2Alignment
1837 getStreamer().EmitZerofill(Ctx.getMachOSection(
1838 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1839 0, SectionKind::getBSS()),
1840 Sym, Size, 1 << Pow2Alignment);
1844 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1848 /// ParseDirectiveAbort
1849 /// ::= .abort [... message ...]
1850 bool AsmParser::ParseDirectiveAbort() {
1851 // FIXME: Use loc from directive.
1852 SMLoc Loc = getLexer().getLoc();
1854 StringRef Str = ParseStringToEndOfStatement();
1855 if (getLexer().isNot(AsmToken::EndOfStatement))
1856 return TokError("unexpected token in '.abort' directive");
1861 Error(Loc, ".abort detected. Assembly stopping.");
1863 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1864 // FIXME: Actually abort assembly here.
1869 /// ParseDirectiveInclude
1870 /// ::= .include "filename"
1871 bool AsmParser::ParseDirectiveInclude() {
1872 if (getLexer().isNot(AsmToken::String))
1873 return TokError("expected string in '.include' directive");
1875 std::string Filename = getTok().getString();
1876 SMLoc IncludeLoc = getLexer().getLoc();
1879 if (getLexer().isNot(AsmToken::EndOfStatement))
1880 return TokError("unexpected token in '.include' directive");
1882 // Strip the quotes.
1883 Filename = Filename.substr(1, Filename.size()-2);
1885 // Attempt to switch the lexer to the included file before consuming the end
1886 // of statement to avoid losing it when we switch.
1887 if (EnterIncludeFile(Filename)) {
1888 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1895 /// ParseDirectiveIf
1896 /// ::= .if expression
1897 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1898 TheCondStack.push_back(TheCondState);
1899 TheCondState.TheCond = AsmCond::IfCond;
1900 if(TheCondState.Ignore) {
1901 EatToEndOfStatement();
1905 if (ParseAbsoluteExpression(ExprValue))
1908 if (getLexer().isNot(AsmToken::EndOfStatement))
1909 return TokError("unexpected token in '.if' directive");
1913 TheCondState.CondMet = ExprValue;
1914 TheCondState.Ignore = !TheCondState.CondMet;
1920 /// ParseDirectiveElseIf
1921 /// ::= .elseif expression
1922 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1923 if (TheCondState.TheCond != AsmCond::IfCond &&
1924 TheCondState.TheCond != AsmCond::ElseIfCond)
1925 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1927 TheCondState.TheCond = AsmCond::ElseIfCond;
1929 bool LastIgnoreState = false;
1930 if (!TheCondStack.empty())
1931 LastIgnoreState = TheCondStack.back().Ignore;
1932 if (LastIgnoreState || TheCondState.CondMet) {
1933 TheCondState.Ignore = true;
1934 EatToEndOfStatement();
1938 if (ParseAbsoluteExpression(ExprValue))
1941 if (getLexer().isNot(AsmToken::EndOfStatement))
1942 return TokError("unexpected token in '.elseif' directive");
1945 TheCondState.CondMet = ExprValue;
1946 TheCondState.Ignore = !TheCondState.CondMet;
1952 /// ParseDirectiveElse
1954 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1955 if (getLexer().isNot(AsmToken::EndOfStatement))
1956 return TokError("unexpected token in '.else' directive");
1960 if (TheCondState.TheCond != AsmCond::IfCond &&
1961 TheCondState.TheCond != AsmCond::ElseIfCond)
1962 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1964 TheCondState.TheCond = AsmCond::ElseCond;
1965 bool LastIgnoreState = false;
1966 if (!TheCondStack.empty())
1967 LastIgnoreState = TheCondStack.back().Ignore;
1968 if (LastIgnoreState || TheCondState.CondMet)
1969 TheCondState.Ignore = true;
1971 TheCondState.Ignore = false;
1976 /// ParseDirectiveEndIf
1978 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1979 if (getLexer().isNot(AsmToken::EndOfStatement))
1980 return TokError("unexpected token in '.endif' directive");
1984 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1985 TheCondStack.empty())
1986 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1988 if (!TheCondStack.empty()) {
1989 TheCondState = TheCondStack.back();
1990 TheCondStack.pop_back();
1996 /// ParseDirectiveFile
1997 /// ::= .file [number] string
1998 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1999 // FIXME: I'm not sure what this is.
2000 int64_t FileNumber = -1;
2001 SMLoc FileNumberLoc = getLexer().getLoc();
2002 if (getLexer().is(AsmToken::Integer)) {
2003 FileNumber = getTok().getIntVal();
2007 return TokError("file number less than one");
2010 if (getLexer().isNot(AsmToken::String))
2011 return TokError("unexpected token in '.file' directive");
2013 StringRef Filename = getTok().getString();
2014 Filename = Filename.substr(1, Filename.size()-2);
2017 if (getLexer().isNot(AsmToken::EndOfStatement))
2018 return TokError("unexpected token in '.file' directive");
2020 if (FileNumber == -1)
2021 getStreamer().EmitFileDirective(Filename);
2023 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2024 Error(FileNumberLoc, "file number already allocated");
2030 /// ParseDirectiveLine
2031 /// ::= .line [number]
2032 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2033 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2034 if (getLexer().isNot(AsmToken::Integer))
2035 return TokError("unexpected token in '.line' directive");
2037 int64_t LineNumber = getTok().getIntVal();
2041 // FIXME: Do something with the .line.
2044 if (getLexer().isNot(AsmToken::EndOfStatement))
2045 return TokError("unexpected token in '.line' directive");
2051 /// ParseDirectiveLoc
2052 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2053 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2054 /// The first number is a file number, must have been previously assigned with
2055 /// a .file directive, the second number is the line number and optionally the
2056 /// third number is a column position (zero if not specified). The remaining
2057 /// optional items are .loc sub-directives.
2058 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2060 if (getLexer().isNot(AsmToken::Integer))
2061 return TokError("unexpected token in '.loc' directive");
2062 int64_t FileNumber = getTok().getIntVal();
2064 return TokError("file number less than one in '.loc' directive");
2065 if (!getContext().isValidDwarfFileNumber(FileNumber))
2066 return TokError("unassigned file number in '.loc' directive");
2069 int64_t LineNumber = 0;
2070 if (getLexer().is(AsmToken::Integer)) {
2071 LineNumber = getTok().getIntVal();
2073 return TokError("line number less than one in '.loc' directive");
2077 int64_t ColumnPos = 0;
2078 if (getLexer().is(AsmToken::Integer)) {
2079 ColumnPos = getTok().getIntVal();
2081 return TokError("column position less than zero in '.loc' directive");
2085 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2087 int64_t Discriminator = 0;
2088 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2090 if (getLexer().is(AsmToken::EndOfStatement))
2094 SMLoc Loc = getTok().getLoc();
2095 if (getParser().ParseIdentifier(Name))
2096 return TokError("unexpected token in '.loc' directive");
2098 if (Name == "basic_block")
2099 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2100 else if (Name == "prologue_end")
2101 Flags |= DWARF2_FLAG_PROLOGUE_END;
2102 else if (Name == "epilogue_begin")
2103 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2104 else if (Name == "is_stmt") {
2105 SMLoc Loc = getTok().getLoc();
2106 const MCExpr *Value;
2107 if (getParser().ParseExpression(Value))
2109 // The expression must be the constant 0 or 1.
2110 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2111 int Value = MCE->getValue();
2113 Flags &= ~DWARF2_FLAG_IS_STMT;
2114 else if (Value == 1)
2115 Flags |= DWARF2_FLAG_IS_STMT;
2117 return Error(Loc, "is_stmt value not 0 or 1");
2120 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2123 else if (Name == "isa") {
2124 SMLoc Loc = getTok().getLoc();
2125 const MCExpr *Value;
2126 if (getParser().ParseExpression(Value))
2128 // The expression must be a constant greater or equal to 0.
2129 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2130 int Value = MCE->getValue();
2132 return Error(Loc, "isa number less than zero");
2136 return Error(Loc, "isa number not a constant value");
2139 else if (Name == "discriminator") {
2140 if (getParser().ParseAbsoluteExpression(Discriminator))
2144 return Error(Loc, "unknown sub-directive in '.loc' directive");
2147 if (getLexer().is(AsmToken::EndOfStatement))
2152 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2153 Isa, Discriminator);
2158 /// ParseDirectiveStabs
2159 /// ::= .stabs string, number, number, number
2160 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2161 SMLoc DirectiveLoc) {
2162 return TokError("unsupported directive '" + Directive + "'");
2165 /// ParseDirectiveCFIStartProc
2166 /// ::= .cfi_startproc
2167 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2168 SMLoc DirectiveLoc) {
2169 return getStreamer().EmitCFIStartProc();
2172 /// ParseDirectiveCFIEndProc
2173 /// ::= .cfi_endproc
2174 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2175 return getStreamer().EmitCFIEndProc();
2178 /// ParseDirectiveCFIDefCfa
2179 /// ::= .cfi_def_cfa register, offset
2180 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2181 SMLoc DirectiveLoc) {
2182 int64_t Register = 0;
2183 if (getParser().ParseAbsoluteExpression(Register))
2186 if (getLexer().isNot(AsmToken::Comma))
2187 return TokError("unexpected token in directive");
2191 if (getParser().ParseAbsoluteExpression(Offset))
2194 return getStreamer().EmitCFIDefCfa(Register, Offset);
2197 /// ParseDirectiveCFIDefCfaOffset
2198 /// ::= .cfi_def_cfa_offset offset
2199 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2200 SMLoc DirectiveLoc) {
2202 if (getParser().ParseAbsoluteExpression(Offset))
2205 return getStreamer().EmitCFIDefCfaOffset(Offset);
2208 /// ParseDirectiveCFIDefCfaRegister
2209 /// ::= .cfi_def_cfa_register register
2210 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2211 SMLoc DirectiveLoc) {
2212 int64_t Register = 0;
2213 if (getParser().ParseAbsoluteExpression(Register))
2216 return getStreamer().EmitCFIDefCfaRegister(Register);
2219 /// ParseDirectiveCFIOffset
2220 /// ::= .cfi_off register, offset
2221 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2222 int64_t Register = 0;
2224 if (getParser().ParseAbsoluteExpression(Register))
2227 if (getLexer().isNot(AsmToken::Comma))
2228 return TokError("unexpected token in directive");
2231 if (getParser().ParseAbsoluteExpression(Offset))
2234 return getStreamer().EmitCFIOffset(Register, Offset);
2237 static bool isValidEncoding(int64_t Encoding) {
2238 if (Encoding & ~0xff)
2241 if (Encoding == dwarf::DW_EH_PE_omit)
2244 const unsigned Format = Encoding & 0xf;
2245 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2246 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2247 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2248 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2251 const unsigned Application = Encoding & 0x70;
2252 if (Application != dwarf::DW_EH_PE_absptr &&
2253 Application != dwarf::DW_EH_PE_pcrel)
2259 /// ParseDirectiveCFIPersonalityOrLsda
2260 /// ::= .cfi_personality encoding, [symbol_name]
2261 /// ::= .cfi_lsda encoding, [symbol_name]
2262 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2263 SMLoc DirectiveLoc) {
2264 int64_t Encoding = 0;
2265 if (getParser().ParseAbsoluteExpression(Encoding))
2267 if (Encoding == dwarf::DW_EH_PE_omit)
2270 if (!isValidEncoding(Encoding))
2271 return TokError("unsupported encoding.");
2273 if (getLexer().isNot(AsmToken::Comma))
2274 return TokError("unexpected token in directive");
2278 if (getParser().ParseIdentifier(Name))
2279 return TokError("expected identifier in directive");
2281 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2283 if (IDVal == ".cfi_personality")
2284 return getStreamer().EmitCFIPersonality(Sym, Encoding);
2286 assert(IDVal == ".cfi_lsda");
2287 return getStreamer().EmitCFILsda(Sym, Encoding);
2291 /// ParseDirectiveCFIRememberState
2292 /// ::= .cfi_remember_state
2293 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2294 SMLoc DirectiveLoc) {
2295 return getStreamer().EmitCFIRememberState();
2298 /// ParseDirectiveCFIRestoreState
2299 /// ::= .cfi_remember_state
2300 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2301 SMLoc DirectiveLoc) {
2302 return getStreamer().EmitCFIRestoreState();
2305 /// ParseDirectiveMacrosOnOff
2308 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2309 SMLoc DirectiveLoc) {
2310 if (getLexer().isNot(AsmToken::EndOfStatement))
2311 return Error(getLexer().getLoc(),
2312 "unexpected token in '" + Directive + "' directive");
2314 getParser().MacrosEnabled = Directive == ".macros_on";
2319 /// ParseDirectiveMacro
2321 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2322 SMLoc DirectiveLoc) {
2324 if (getParser().ParseIdentifier(Name))
2325 return TokError("expected identifier in directive");
2327 if (getLexer().isNot(AsmToken::EndOfStatement))
2328 return TokError("unexpected token in '.macro' directive");
2330 // Eat the end of statement.
2333 AsmToken EndToken, StartToken = getTok();
2335 // Lex the macro definition.
2337 // Check whether we have reached the end of the file.
2338 if (getLexer().is(AsmToken::Eof))
2339 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2341 // Otherwise, check whether we have reach the .endmacro.
2342 if (getLexer().is(AsmToken::Identifier) &&
2343 (getTok().getIdentifier() == ".endm" ||
2344 getTok().getIdentifier() == ".endmacro")) {
2345 EndToken = getTok();
2347 if (getLexer().isNot(AsmToken::EndOfStatement))
2348 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2353 // Otherwise, scan til the end of the statement.
2354 getParser().EatToEndOfStatement();
2357 if (getParser().MacroMap.lookup(Name)) {
2358 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2361 const char *BodyStart = StartToken.getLoc().getPointer();
2362 const char *BodyEnd = EndToken.getLoc().getPointer();
2363 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2364 getParser().MacroMap[Name] = new Macro(Name, Body);
2368 /// ParseDirectiveEndMacro
2371 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2372 SMLoc DirectiveLoc) {
2373 if (getLexer().isNot(AsmToken::EndOfStatement))
2374 return TokError("unexpected token in '" + Directive + "' directive");
2376 // If we are inside a macro instantiation, terminate the current
2378 if (!getParser().ActiveMacros.empty()) {
2379 getParser().HandleMacroExit();
2383 // Otherwise, this .endmacro is a stray entry in the file; well formed
2384 // .endmacro directives are handled during the macro definition parsing.
2385 return TokError("unexpected '" + Directive + "' in file, "
2386 "no current macro definition");
2389 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2390 getParser().CheckForValidSection();
2392 const MCExpr *Value;
2394 if (getParser().ParseExpression(Value))
2397 if (getLexer().isNot(AsmToken::EndOfStatement))
2398 return TokError("unexpected token in directive");
2400 if (DirName[1] == 's')
2401 getStreamer().EmitSLEB128Value(Value);
2403 getStreamer().EmitULEB128Value(Value);
2409 /// \brief Create an MCAsmParser instance.
2410 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2411 MCContext &C, MCStreamer &Out,
2412 const MCAsmInfo &MAI) {
2413 return new AsmParser(T, SM, C, Out, MAI);