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/CommandLine.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetAsmParser.h"
41 FatalAssemblerWarnings("fatal-assembler-warnings",
42 cl::desc("Consider warnings as error"));
46 /// \brief Helper class for tracking macro definitions.
52 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
55 /// \brief Helper class for storing information about an active macro
57 struct MacroInstantiation {
58 /// The macro being instantiated.
59 const Macro *TheMacro;
61 /// The macro instantiation with substitutions.
62 MemoryBuffer *Instantiation;
64 /// The location of the instantiation.
65 SMLoc InstantiationLoc;
67 /// The location where parsing should resume upon instantiation completion.
71 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
72 const std::vector<std::vector<AsmToken> > &A);
75 /// \brief The concrete assembly parser instance.
76 class AsmParser : public MCAsmParser {
77 friend class GenericAsmParser;
79 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
80 void operator=(const AsmParser &); // DO NOT IMPLEMENT
86 MCAsmParserExtension *GenericParser;
87 MCAsmParserExtension *PlatformParser;
89 /// This is the current buffer index we're lexing from as managed by the
94 std::vector<AsmCond> TheCondStack;
96 /// DirectiveMap - This is a table handlers for directives. Each handler is
97 /// invoked after the directive identifier is read and is responsible for
98 /// parsing and validating the rest of the directive. The handler is passed
99 /// in the directive name and the location of the directive keyword.
100 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
102 /// MacroMap - Map of currently defined macros.
103 StringMap<Macro*> MacroMap;
105 /// ActiveMacros - Stack of active macro instantiations.
106 std::vector<MacroInstantiation*> ActiveMacros;
108 /// Boolean tracking whether macro substitution is enabled.
109 unsigned MacrosEnabled : 1;
111 /// Flag tracking whether any errors have been encountered.
112 unsigned HadError : 1;
115 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
116 const MCAsmInfo &MAI);
119 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
121 void AddDirectiveHandler(MCAsmParserExtension *Object,
123 DirectiveHandler Handler) {
124 DirectiveMap[Directive] = std::make_pair(Object, Handler);
128 /// @name MCAsmParser Interface
131 virtual SourceMgr &getSourceManager() { return SrcMgr; }
132 virtual MCAsmLexer &getLexer() { return Lexer; }
133 virtual MCContext &getContext() { return Ctx; }
134 virtual MCStreamer &getStreamer() { return Out; }
136 virtual bool Warning(SMLoc L, const Twine &Meg);
137 virtual bool Error(SMLoc L, const Twine &Msg);
139 const AsmToken &Lex();
141 bool ParseExpression(const MCExpr *&Res);
142 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
143 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
144 virtual bool ParseAbsoluteExpression(int64_t &Res);
149 void CheckForValidSection();
151 bool ParseStatement();
153 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
154 void HandleMacroExit();
156 void PrintMacroInstantiations();
157 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
158 SrcMgr.PrintMessage(Loc, Msg, Type);
161 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
162 bool EnterIncludeFile(const std::string &Filename);
164 /// \brief Reset the current lexer position to that given by \arg Loc. The
165 /// current token is not set; clients should ensure Lex() is called
167 void JumpToLoc(SMLoc Loc);
169 void EatToEndOfStatement();
171 /// \brief Parse up to the end of statement and a return the contents from the
172 /// current token until the end of the statement; the current token on exit
173 /// will be either the EndOfStatement or EOF.
174 StringRef ParseStringToEndOfStatement();
176 bool ParseAssignment(StringRef Name, bool allow_redef);
178 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
179 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
180 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
181 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
183 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
184 /// and set \arg Res to the identifier contents.
185 bool ParseIdentifier(StringRef &Res);
187 // Directive Parsing.
189 // ".ascii", ".asciiz", ".string"
190 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
191 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
192 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
193 bool ParseDirectiveFill(); // ".fill"
194 bool ParseDirectiveSpace(); // ".space"
195 bool ParseDirectiveZero(); // ".zero"
196 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
197 bool ParseDirectiveOrg(); // ".org"
198 // ".align{,32}", ".p2align{,w,l}"
199 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
201 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
202 /// accepts a single symbol (which should be a label or an external).
203 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
205 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
207 bool ParseDirectiveAbort(); // ".abort"
208 bool ParseDirectiveInclude(); // ".include"
210 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
211 // ".ifdef" or ".ifndef", depending on expect_defined
212 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
213 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
214 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
215 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
217 /// ParseEscapedString - Parse the current token as a string which may include
218 /// escaped characters and return the string contents.
219 bool ParseEscapedString(std::string &Data);
221 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
222 MCSymbolRefExpr::VariantKind Variant);
225 /// \brief Generic implementations of directive handling, etc. which is shared
226 /// (or the default, at least) for all assembler parser.
227 class GenericAsmParser : public MCAsmParserExtension {
228 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
229 void AddDirectiveHandler(StringRef Directive) {
230 getParser().AddDirectiveHandler(this, Directive,
231 HandleDirective<GenericAsmParser, Handler>);
234 GenericAsmParser() {}
236 AsmParser &getParser() {
237 return (AsmParser&) this->MCAsmParserExtension::getParser();
240 virtual void Initialize(MCAsmParser &Parser) {
241 // Call the base implementation.
242 this->MCAsmParserExtension::Initialize(Parser);
244 // Debugging directives.
245 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
246 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
247 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
248 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
251 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
253 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
255 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
257 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
259 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
260 ".cfi_def_cfa_offset");
261 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
262 ".cfi_adjust_cfa_offset");
263 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
264 ".cfi_def_cfa_register");
265 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
270 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
272 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
274 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
276 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
278 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
281 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
283 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
285 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
287 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
289 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
293 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
295 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
296 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
297 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
298 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
299 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
300 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
301 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
302 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
303 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
304 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
305 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
306 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
307 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
308 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
309 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
310 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
311 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
313 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
314 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
315 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
317 bool ParseDirectiveLEB128(StringRef, SMLoc);
324 extern MCAsmParserExtension *createDarwinAsmParser();
325 extern MCAsmParserExtension *createELFAsmParser();
326 extern MCAsmParserExtension *createCOFFAsmParser();
330 enum { DEFAULT_ADDRSPACE = 0 };
332 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
333 MCStreamer &_Out, const MCAsmInfo &_MAI)
334 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
335 GenericParser(new GenericAsmParser), PlatformParser(0),
336 CurBuffer(0), MacrosEnabled(true) {
337 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
339 // Initialize the generic parser.
340 GenericParser->Initialize(*this);
342 // Initialize the platform / file format parser.
344 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
346 if (_MAI.hasMicrosoftFastStdCallMangling()) {
347 PlatformParser = createCOFFAsmParser();
348 PlatformParser->Initialize(*this);
349 } else if (_MAI.hasSubsectionsViaSymbols()) {
350 PlatformParser = createDarwinAsmParser();
351 PlatformParser->Initialize(*this);
353 PlatformParser = createELFAsmParser();
354 PlatformParser->Initialize(*this);
358 AsmParser::~AsmParser() {
359 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
361 // Destroy any macros.
362 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
363 ie = MacroMap.end(); it != ie; ++it)
364 delete it->getValue();
366 delete PlatformParser;
367 delete GenericParser;
370 void AsmParser::PrintMacroInstantiations() {
371 // Print the active macro instantiation stack.
372 for (std::vector<MacroInstantiation*>::const_reverse_iterator
373 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
374 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
378 bool AsmParser::Warning(SMLoc L, const Twine &Msg) {
379 if (FatalAssemblerWarnings)
380 return Error(L, Msg);
381 PrintMessage(L, Msg, "warning");
382 PrintMacroInstantiations();
386 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
388 PrintMessage(L, Msg, "error");
389 PrintMacroInstantiations();
393 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
394 std::string IncludedFile;
395 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
401 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
406 void AsmParser::JumpToLoc(SMLoc Loc) {
407 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
408 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
411 const AsmToken &AsmParser::Lex() {
412 const AsmToken *tok = &Lexer.Lex();
414 if (tok->is(AsmToken::Eof)) {
415 // If this is the end of an included file, pop the parent file off the
417 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
418 if (ParentIncludeLoc != SMLoc()) {
419 JumpToLoc(ParentIncludeLoc);
424 if (tok->is(AsmToken::Error))
425 Error(Lexer.getErrLoc(), Lexer.getErr());
430 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
431 // Create the initial section, if requested.
432 if (!NoInitialTextSection)
439 AsmCond StartingCondState = TheCondState;
441 // While we have input, parse each statement.
442 while (Lexer.isNot(AsmToken::Eof)) {
443 if (!ParseStatement()) continue;
445 // We had an error, validate that one was emitted and recover by skipping to
447 assert(HadError && "Parse statement returned an error, but none emitted!");
448 EatToEndOfStatement();
451 if (TheCondState.TheCond != StartingCondState.TheCond ||
452 TheCondState.Ignore != StartingCondState.Ignore)
453 return TokError("unmatched .ifs or .elses");
455 // Check to see there are no empty DwarfFile slots.
456 const std::vector<MCDwarfFile *> &MCDwarfFiles =
457 getContext().getMCDwarfFiles();
458 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
459 if (!MCDwarfFiles[i])
460 TokError("unassigned file number: " + Twine(i) + " for .file directives");
463 // Finalize the output stream if there are no errors and if the client wants
465 if (!HadError && !NoFinalize)
471 void AsmParser::CheckForValidSection() {
472 if (!getStreamer().getCurrentSection()) {
473 TokError("expected section directive before assembly directive");
474 Out.SwitchSection(Ctx.getMachOSection(
476 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
477 0, SectionKind::getText()));
481 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
482 void AsmParser::EatToEndOfStatement() {
483 while (Lexer.isNot(AsmToken::EndOfStatement) &&
484 Lexer.isNot(AsmToken::Eof))
488 if (Lexer.is(AsmToken::EndOfStatement))
492 StringRef AsmParser::ParseStringToEndOfStatement() {
493 const char *Start = getTok().getLoc().getPointer();
495 while (Lexer.isNot(AsmToken::EndOfStatement) &&
496 Lexer.isNot(AsmToken::Eof))
499 const char *End = getTok().getLoc().getPointer();
500 return StringRef(Start, End - Start);
503 /// ParseParenExpr - Parse a paren expression and return it.
504 /// NOTE: This assumes the leading '(' has already been consumed.
506 /// parenexpr ::= expr)
508 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
509 if (ParseExpression(Res)) return true;
510 if (Lexer.isNot(AsmToken::RParen))
511 return TokError("expected ')' in parentheses expression");
512 EndLoc = Lexer.getLoc();
517 /// ParseBracketExpr - Parse a bracket expression and return it.
518 /// NOTE: This assumes the leading '[' has already been consumed.
520 /// bracketexpr ::= expr]
522 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
523 if (ParseExpression(Res)) return true;
524 if (Lexer.isNot(AsmToken::RBrac))
525 return TokError("expected ']' in brackets expression");
526 EndLoc = Lexer.getLoc();
531 /// ParsePrimaryExpr - Parse a primary expression and return it.
532 /// primaryexpr ::= (parenexpr
533 /// primaryexpr ::= symbol
534 /// primaryexpr ::= number
535 /// primaryexpr ::= '.'
536 /// primaryexpr ::= ~,+,- primaryexpr
537 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
538 switch (Lexer.getKind()) {
540 return TokError("unknown token in expression");
541 // If we have an error assume that we've already handled it.
542 case AsmToken::Error:
544 case AsmToken::Exclaim:
545 Lex(); // Eat the operator.
546 if (ParsePrimaryExpr(Res, EndLoc))
548 Res = MCUnaryExpr::CreateLNot(Res, getContext());
550 case AsmToken::Dollar:
551 case AsmToken::String:
552 case AsmToken::Identifier: {
553 EndLoc = Lexer.getLoc();
555 StringRef Identifier;
556 if (ParseIdentifier(Identifier))
559 // This is a symbol reference.
560 std::pair<StringRef, StringRef> Split = Identifier.split('@');
561 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
563 // Lookup the symbol variant if used.
564 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
565 if (Split.first.size() != Identifier.size()) {
566 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
567 if (Variant == MCSymbolRefExpr::VK_Invalid) {
568 Variant = MCSymbolRefExpr::VK_None;
569 return TokError("invalid variant '" + Split.second + "'");
573 // If this is an absolute variable reference, substitute it now to preserve
574 // semantics in the face of reassignment.
575 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
577 return Error(EndLoc, "unexpected modifier on variable reference");
579 Res = Sym->getVariableValue();
583 // Otherwise create a symbol ref.
584 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
587 case AsmToken::Integer: {
588 SMLoc Loc = getTok().getLoc();
589 int64_t IntVal = getTok().getIntVal();
590 Res = MCConstantExpr::Create(IntVal, getContext());
591 EndLoc = Lexer.getLoc();
593 // Look for 'b' or 'f' following an Integer as a directional label
594 if (Lexer.getKind() == AsmToken::Identifier) {
595 StringRef IDVal = getTok().getString();
596 if (IDVal == "f" || IDVal == "b"){
597 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
598 IDVal == "f" ? 1 : 0);
599 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
601 if(IDVal == "b" && Sym->isUndefined())
602 return Error(Loc, "invalid reference to undefined symbol");
603 EndLoc = Lexer.getLoc();
604 Lex(); // Eat identifier.
609 case AsmToken::Real: {
610 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
611 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
612 Res = MCConstantExpr::Create(IntVal, getContext());
616 case AsmToken::Dot: {
617 // This is a '.' reference, which references the current PC. Emit a
618 // temporary label to the streamer and refer to it.
619 MCSymbol *Sym = Ctx.CreateTempSymbol();
621 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
622 EndLoc = Lexer.getLoc();
623 Lex(); // Eat identifier.
626 case AsmToken::LParen:
627 Lex(); // Eat the '('.
628 return ParseParenExpr(Res, EndLoc);
629 case AsmToken::LBrac:
630 if (!PlatformParser->HasBracketExpressions())
631 return TokError("brackets expression not supported on this target");
632 Lex(); // Eat the '['.
633 return ParseBracketExpr(Res, EndLoc);
634 case AsmToken::Minus:
635 Lex(); // Eat the operator.
636 if (ParsePrimaryExpr(Res, EndLoc))
638 Res = MCUnaryExpr::CreateMinus(Res, getContext());
641 Lex(); // Eat the operator.
642 if (ParsePrimaryExpr(Res, EndLoc))
644 Res = MCUnaryExpr::CreatePlus(Res, getContext());
646 case AsmToken::Tilde:
647 Lex(); // Eat the operator.
648 if (ParsePrimaryExpr(Res, EndLoc))
650 Res = MCUnaryExpr::CreateNot(Res, getContext());
655 bool AsmParser::ParseExpression(const MCExpr *&Res) {
657 return ParseExpression(Res, EndLoc);
661 AsmParser::ApplyModifierToExpr(const MCExpr *E,
662 MCSymbolRefExpr::VariantKind Variant) {
663 // Recurse over the given expression, rebuilding it to apply the given variant
664 // if there is exactly one symbol.
665 switch (E->getKind()) {
667 case MCExpr::Constant:
670 case MCExpr::SymbolRef: {
671 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
673 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
674 TokError("invalid variant on expression '" +
675 getTok().getIdentifier() + "' (already modified)");
679 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
682 case MCExpr::Unary: {
683 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
684 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
687 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
690 case MCExpr::Binary: {
691 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
692 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
693 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
698 if (!LHS) LHS = BE->getLHS();
699 if (!RHS) RHS = BE->getRHS();
701 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
705 assert(0 && "Invalid expression kind!");
709 /// ParseExpression - Parse an expression and return it.
711 /// expr ::= expr +,- expr -> lowest.
712 /// expr ::= expr |,^,&,! expr -> middle.
713 /// expr ::= expr *,/,%,<<,>> expr -> highest.
714 /// expr ::= primaryexpr
716 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
717 // Parse the expression.
719 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
722 // As a special case, we support 'a op b @ modifier' by rewriting the
723 // expression to include the modifier. This is inefficient, but in general we
724 // expect users to use 'a@modifier op b'.
725 if (Lexer.getKind() == AsmToken::At) {
728 if (Lexer.isNot(AsmToken::Identifier))
729 return TokError("unexpected symbol modifier following '@'");
731 MCSymbolRefExpr::VariantKind Variant =
732 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
733 if (Variant == MCSymbolRefExpr::VK_Invalid)
734 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
736 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
738 return TokError("invalid modifier '" + getTok().getIdentifier() +
739 "' (no symbols present)");
747 // Try to constant fold it up front, if possible.
749 if (Res->EvaluateAsAbsolute(Value))
750 Res = MCConstantExpr::Create(Value, getContext());
755 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
757 return ParseParenExpr(Res, EndLoc) ||
758 ParseBinOpRHS(1, Res, EndLoc);
761 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
764 SMLoc StartLoc = Lexer.getLoc();
765 if (ParseExpression(Expr))
768 if (!Expr->EvaluateAsAbsolute(Res))
769 return Error(StartLoc, "expected absolute expression");
774 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
775 MCBinaryExpr::Opcode &Kind) {
778 return 0; // not a binop.
780 // Lowest Precedence: &&, ||, @
781 case AsmToken::AmpAmp:
782 Kind = MCBinaryExpr::LAnd;
784 case AsmToken::PipePipe:
785 Kind = MCBinaryExpr::LOr;
789 // Low Precedence: |, &, ^
791 // FIXME: gas seems to support '!' as an infix operator?
793 Kind = MCBinaryExpr::Or;
795 case AsmToken::Caret:
796 Kind = MCBinaryExpr::Xor;
799 Kind = MCBinaryExpr::And;
802 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
803 case AsmToken::EqualEqual:
804 Kind = MCBinaryExpr::EQ;
806 case AsmToken::ExclaimEqual:
807 case AsmToken::LessGreater:
808 Kind = MCBinaryExpr::NE;
811 Kind = MCBinaryExpr::LT;
813 case AsmToken::LessEqual:
814 Kind = MCBinaryExpr::LTE;
816 case AsmToken::Greater:
817 Kind = MCBinaryExpr::GT;
819 case AsmToken::GreaterEqual:
820 Kind = MCBinaryExpr::GTE;
823 // High Intermediate Precedence: +, -
825 Kind = MCBinaryExpr::Add;
827 case AsmToken::Minus:
828 Kind = MCBinaryExpr::Sub;
831 // Highest Precedence: *, /, %, <<, >>
833 Kind = MCBinaryExpr::Mul;
835 case AsmToken::Slash:
836 Kind = MCBinaryExpr::Div;
838 case AsmToken::Percent:
839 Kind = MCBinaryExpr::Mod;
841 case AsmToken::LessLess:
842 Kind = MCBinaryExpr::Shl;
844 case AsmToken::GreaterGreater:
845 Kind = MCBinaryExpr::Shr;
851 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
852 /// Res contains the LHS of the expression on input.
853 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
856 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
857 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
859 // If the next token is lower precedence than we are allowed to eat, return
860 // successfully with what we ate already.
861 if (TokPrec < Precedence)
866 // Eat the next primary expression.
868 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
870 // If BinOp binds less tightly with RHS than the operator after RHS, let
871 // the pending operator take RHS as its LHS.
872 MCBinaryExpr::Opcode Dummy;
873 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
874 if (TokPrec < NextTokPrec) {
875 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
878 // Merge LHS and RHS according to operator.
879 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
887 /// ::= EndOfStatement
888 /// ::= Label* Directive ...Operands... EndOfStatement
889 /// ::= Label* Identifier OperandList* EndOfStatement
890 bool AsmParser::ParseStatement() {
891 if (Lexer.is(AsmToken::EndOfStatement)) {
897 // Statements always start with an identifier or are a full line comment.
898 AsmToken ID = getTok();
899 SMLoc IDLoc = ID.getLoc();
901 int64_t LocalLabelVal = -1;
902 // A full line comment is a '#' as the first token.
903 if (Lexer.is(AsmToken::Hash)) {
904 EatToEndOfStatement();
908 // Allow an integer followed by a ':' as a directional local label.
909 if (Lexer.is(AsmToken::Integer)) {
910 LocalLabelVal = getTok().getIntVal();
911 if (LocalLabelVal < 0) {
912 if (!TheCondState.Ignore)
913 return TokError("unexpected token at start of statement");
917 IDVal = getTok().getString();
918 Lex(); // Consume the integer token to be used as an identifier token.
919 if (Lexer.getKind() != AsmToken::Colon) {
920 if (!TheCondState.Ignore)
921 return TokError("unexpected token at start of statement");
925 } else if (Lexer.is(AsmToken::Dot)) {
926 // Treat '.' as a valid identifier in this context.
930 } else if (ParseIdentifier(IDVal)) {
931 if (!TheCondState.Ignore)
932 return TokError("unexpected token at start of statement");
937 // Handle conditional assembly here before checking for skipping. We
938 // have to do this so that .endif isn't skipped in a ".if 0" block for
941 return ParseDirectiveIf(IDLoc);
942 if (IDVal == ".ifdef")
943 return ParseDirectiveIfdef(IDLoc, true);
944 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
945 return ParseDirectiveIfdef(IDLoc, false);
946 if (IDVal == ".elseif")
947 return ParseDirectiveElseIf(IDLoc);
948 if (IDVal == ".else")
949 return ParseDirectiveElse(IDLoc);
950 if (IDVal == ".endif")
951 return ParseDirectiveEndIf(IDLoc);
953 // If we are in a ".if 0" block, ignore this statement.
954 if (TheCondState.Ignore) {
955 EatToEndOfStatement();
959 // FIXME: Recurse on local labels?
961 // See what kind of statement we have.
962 switch (Lexer.getKind()) {
963 case AsmToken::Colon: {
964 CheckForValidSection();
966 // identifier ':' -> Label.
969 // Diagnose attempt to use '.' as a label.
971 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
973 // Diagnose attempt to use a variable as a label.
975 // FIXME: Diagnostics. Note the location of the definition as a label.
976 // FIXME: This doesn't diagnose assignment to a symbol which has been
977 // implicitly marked as external.
979 if (LocalLabelVal == -1)
980 Sym = getContext().GetOrCreateSymbol(IDVal);
982 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
983 if (!Sym->isUndefined() || Sym->isVariable())
984 return Error(IDLoc, "invalid symbol redefinition");
989 // Consume any end of statement token, if present, to avoid spurious
990 // AddBlankLine calls().
991 if (Lexer.is(AsmToken::EndOfStatement)) {
993 if (Lexer.is(AsmToken::Eof))
997 return ParseStatement();
1000 case AsmToken::Equal:
1001 // identifier '=' ... -> assignment statement
1004 return ParseAssignment(IDVal, true);
1006 default: // Normal instruction or directive.
1010 // If macros are enabled, check to see if this is a macro instantiation.
1012 if (const Macro *M = MacroMap.lookup(IDVal))
1013 return HandleMacroEntry(IDVal, IDLoc, M);
1015 // Otherwise, we have a normal instruction or directive.
1016 if (IDVal[0] == '.' && IDVal != ".") {
1017 // Assembler features
1018 if (IDVal == ".set" || IDVal == ".equ")
1019 return ParseDirectiveSet(IDVal, true);
1020 if (IDVal == ".equiv")
1021 return ParseDirectiveSet(IDVal, false);
1025 if (IDVal == ".ascii")
1026 return ParseDirectiveAscii(IDVal, false);
1027 if (IDVal == ".asciz" || IDVal == ".string")
1028 return ParseDirectiveAscii(IDVal, true);
1030 if (IDVal == ".byte")
1031 return ParseDirectiveValue(1);
1032 if (IDVal == ".short")
1033 return ParseDirectiveValue(2);
1034 if (IDVal == ".value")
1035 return ParseDirectiveValue(2);
1036 if (IDVal == ".2byte")
1037 return ParseDirectiveValue(2);
1038 if (IDVal == ".long")
1039 return ParseDirectiveValue(4);
1040 if (IDVal == ".int")
1041 return ParseDirectiveValue(4);
1042 if (IDVal == ".4byte")
1043 return ParseDirectiveValue(4);
1044 if (IDVal == ".quad")
1045 return ParseDirectiveValue(8);
1046 if (IDVal == ".8byte")
1047 return ParseDirectiveValue(8);
1048 if (IDVal == ".single" || IDVal == ".float")
1049 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1050 if (IDVal == ".double")
1051 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1053 if (IDVal == ".align") {
1054 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1055 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1057 if (IDVal == ".align32") {
1058 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1059 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1061 if (IDVal == ".balign")
1062 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1063 if (IDVal == ".balignw")
1064 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1065 if (IDVal == ".balignl")
1066 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1067 if (IDVal == ".p2align")
1068 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1069 if (IDVal == ".p2alignw")
1070 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1071 if (IDVal == ".p2alignl")
1072 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1074 if (IDVal == ".org")
1075 return ParseDirectiveOrg();
1077 if (IDVal == ".fill")
1078 return ParseDirectiveFill();
1079 if (IDVal == ".space" || IDVal == ".skip")
1080 return ParseDirectiveSpace();
1081 if (IDVal == ".zero")
1082 return ParseDirectiveZero();
1084 // Symbol attribute directives
1086 if (IDVal == ".globl" || IDVal == ".global")
1087 return ParseDirectiveSymbolAttribute(MCSA_Global);
1088 // ELF only? Should it be here?
1089 if (IDVal == ".local")
1090 return ParseDirectiveSymbolAttribute(MCSA_Local);
1091 if (IDVal == ".hidden")
1092 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1093 if (IDVal == ".indirect_symbol")
1094 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1095 if (IDVal == ".internal")
1096 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1097 if (IDVal == ".lazy_reference")
1098 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1099 if (IDVal == ".no_dead_strip")
1100 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1101 if (IDVal == ".symbol_resolver")
1102 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1103 if (IDVal == ".private_extern")
1104 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1105 if (IDVal == ".protected")
1106 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1107 if (IDVal == ".reference")
1108 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1109 if (IDVal == ".weak")
1110 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1111 if (IDVal == ".weak_definition")
1112 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1113 if (IDVal == ".weak_reference")
1114 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1115 if (IDVal == ".weak_def_can_be_hidden")
1116 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1118 if (IDVal == ".comm")
1119 return ParseDirectiveComm(/*IsLocal=*/false);
1120 if (IDVal == ".lcomm")
1121 return ParseDirectiveComm(/*IsLocal=*/true);
1123 if (IDVal == ".abort")
1124 return ParseDirectiveAbort();
1125 if (IDVal == ".include")
1126 return ParseDirectiveInclude();
1128 if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1129 return TokError(Twine(IDVal) + " not supported yet");
1131 // Look up the handler in the handler table.
1132 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1133 DirectiveMap.lookup(IDVal);
1135 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1137 // Target hook for parsing target specific directives.
1138 if (!getTargetParser().ParseDirective(ID))
1141 bool retval = Warning(IDLoc, "ignoring directive for now");
1142 EatToEndOfStatement();
1146 CheckForValidSection();
1148 // Canonicalize the opcode to lower case.
1149 SmallString<128> Opcode;
1150 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1151 Opcode.push_back(tolower(IDVal[i]));
1153 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1154 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1157 // Dump the parsed representation, if requested.
1158 if (getShowParsedOperands()) {
1159 SmallString<256> Str;
1160 raw_svector_ostream OS(Str);
1161 OS << "parsed instruction: [";
1162 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1165 ParsedOperands[i]->dump(OS);
1169 PrintMessage(IDLoc, OS.str(), "note");
1172 // If parsing succeeded, match the instruction.
1174 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1177 // Free any parsed operands.
1178 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1179 delete ParsedOperands[i];
1181 // Don't skip the rest of the line, the instruction parser is responsible for
1186 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1187 const std::vector<std::vector<AsmToken> > &A)
1188 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1190 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1191 // to hold the macro body with substitutions.
1192 SmallString<256> Buf;
1193 raw_svector_ostream OS(Buf);
1195 StringRef Body = M->Body;
1196 while (!Body.empty()) {
1197 // Scan for the next substitution.
1198 std::size_t End = Body.size(), Pos = 0;
1199 for (; Pos != End; ++Pos) {
1200 // Check for a substitution or escape.
1201 if (Body[Pos] != '$' || Pos + 1 == End)
1204 char Next = Body[Pos + 1];
1205 if (Next == '$' || Next == 'n' || isdigit(Next))
1210 OS << Body.slice(0, Pos);
1212 // Check if we reached the end.
1216 switch (Body[Pos+1]) {
1222 // $n => number of arguments
1227 // $[0-9] => argument
1229 // Missing arguments are ignored.
1230 unsigned Index = Body[Pos+1] - '0';
1231 if (Index >= A.size())
1234 // Otherwise substitute with the token values, with spaces eliminated.
1235 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1236 ie = A[Index].end(); it != ie; ++it)
1237 OS << it->getString();
1242 // Update the scan point.
1243 Body = Body.substr(Pos + 2);
1246 // We include the .endmacro in the buffer as our queue to exit the macro
1248 OS << ".endmacro\n";
1250 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1253 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1255 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1256 // this, although we should protect against infinite loops.
1257 if (ActiveMacros.size() == 20)
1258 return TokError("macros cannot be nested more than 20 levels deep");
1260 // Parse the macro instantiation arguments.
1261 std::vector<std::vector<AsmToken> > MacroArguments;
1262 MacroArguments.push_back(std::vector<AsmToken>());
1263 unsigned ParenLevel = 0;
1265 if (Lexer.is(AsmToken::Eof))
1266 return TokError("unexpected token in macro instantiation");
1267 if (Lexer.is(AsmToken::EndOfStatement))
1270 // If we aren't inside parentheses and this is a comma, start a new token
1272 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1273 MacroArguments.push_back(std::vector<AsmToken>());
1275 // Adjust the current parentheses level.
1276 if (Lexer.is(AsmToken::LParen))
1278 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1281 // Append the token to the current argument list.
1282 MacroArguments.back().push_back(getTok());
1287 // Create the macro instantiation object and add to the current macro
1288 // instantiation stack.
1289 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1292 ActiveMacros.push_back(MI);
1294 // Jump to the macro instantiation and prime the lexer.
1295 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1296 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1302 void AsmParser::HandleMacroExit() {
1303 // Jump to the EndOfStatement we should return to, and consume it.
1304 JumpToLoc(ActiveMacros.back()->ExitLoc);
1307 // Pop the instantiation entry.
1308 delete ActiveMacros.back();
1309 ActiveMacros.pop_back();
1312 static void MarkUsed(const MCExpr *Value) {
1313 switch (Value->getKind()) {
1314 case MCExpr::Binary:
1315 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1316 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1318 case MCExpr::Target:
1319 case MCExpr::Constant:
1321 case MCExpr::SymbolRef: {
1322 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1326 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1331 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1332 // FIXME: Use better location, we should use proper tokens.
1333 SMLoc EqualLoc = Lexer.getLoc();
1335 const MCExpr *Value;
1336 if (ParseExpression(Value))
1341 if (Lexer.isNot(AsmToken::EndOfStatement))
1342 return TokError("unexpected token in assignment");
1344 // Error on assignment to '.'.
1346 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1347 "(use '.space' or '.org').)"));
1350 // Eat the end of statement marker.
1353 // Validate that the LHS is allowed to be a variable (either it has not been
1354 // used as a symbol, or it is an absolute symbol).
1355 MCSymbol *Sym = getContext().LookupSymbol(Name);
1357 // Diagnose assignment to a label.
1359 // FIXME: Diagnostics. Note the location of the definition as a label.
1360 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1361 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1362 ; // Allow redefinitions of undefined symbols only used in directives.
1363 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1364 return Error(EqualLoc, "redefinition of '" + Name + "'");
1365 else if (!Sym->isVariable())
1366 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1367 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1368 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1371 // Don't count these checks as uses.
1372 Sym->setUsed(false);
1374 Sym = getContext().GetOrCreateSymbol(Name);
1376 // FIXME: Handle '.'.
1378 // Do the assignment.
1379 Out.EmitAssignment(Sym, Value);
1384 /// ParseIdentifier:
1387 bool AsmParser::ParseIdentifier(StringRef &Res) {
1388 // The assembler has relaxed rules for accepting identifiers, in particular we
1389 // allow things like '.globl $foo', which would normally be separate
1390 // tokens. At this level, we have already lexed so we cannot (currently)
1391 // handle this as a context dependent token, instead we detect adjacent tokens
1392 // and return the combined identifier.
1393 if (Lexer.is(AsmToken::Dollar)) {
1394 SMLoc DollarLoc = getLexer().getLoc();
1396 // Consume the dollar sign, and check for a following identifier.
1398 if (Lexer.isNot(AsmToken::Identifier))
1401 // We have a '$' followed by an identifier, make sure they are adjacent.
1402 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1405 // Construct the joined identifier and consume the token.
1406 Res = StringRef(DollarLoc.getPointer(),
1407 getTok().getIdentifier().size() + 1);
1412 if (Lexer.isNot(AsmToken::Identifier) &&
1413 Lexer.isNot(AsmToken::String))
1416 Res = getTok().getIdentifier();
1418 Lex(); // Consume the identifier token.
1423 /// ParseDirectiveSet:
1424 /// ::= .equ identifier ',' expression
1425 /// ::= .equiv identifier ',' expression
1426 /// ::= .set identifier ',' expression
1427 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1430 if (ParseIdentifier(Name))
1431 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1433 if (getLexer().isNot(AsmToken::Comma))
1434 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1437 return ParseAssignment(Name, allow_redef);
1440 bool AsmParser::ParseEscapedString(std::string &Data) {
1441 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1444 StringRef Str = getTok().getStringContents();
1445 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1446 if (Str[i] != '\\') {
1451 // Recognize escaped characters. Note that this escape semantics currently
1452 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1455 return TokError("unexpected backslash at end of string");
1457 // Recognize octal sequences.
1458 if ((unsigned) (Str[i] - '0') <= 7) {
1459 // Consume up to three octal characters.
1460 unsigned Value = Str[i] - '0';
1462 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1464 Value = Value * 8 + (Str[i] - '0');
1466 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1468 Value = Value * 8 + (Str[i] - '0');
1473 return TokError("invalid octal escape sequence (out of range)");
1475 Data += (unsigned char) Value;
1479 // Otherwise recognize individual escapes.
1482 // Just reject invalid escape sequences for now.
1483 return TokError("invalid escape sequence (unrecognized character)");
1485 case 'b': Data += '\b'; break;
1486 case 'f': Data += '\f'; break;
1487 case 'n': Data += '\n'; break;
1488 case 'r': Data += '\r'; break;
1489 case 't': Data += '\t'; break;
1490 case '"': Data += '"'; break;
1491 case '\\': Data += '\\'; break;
1498 /// ParseDirectiveAscii:
1499 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1500 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1501 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1502 CheckForValidSection();
1505 if (getLexer().isNot(AsmToken::String))
1506 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1509 if (ParseEscapedString(Data))
1512 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1514 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1518 if (getLexer().is(AsmToken::EndOfStatement))
1521 if (getLexer().isNot(AsmToken::Comma))
1522 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1531 /// ParseDirectiveValue
1532 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1533 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1534 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1535 CheckForValidSection();
1538 const MCExpr *Value;
1539 if (ParseExpression(Value))
1542 // Special case constant expressions to match code generator.
1543 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1544 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1546 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1548 if (getLexer().is(AsmToken::EndOfStatement))
1551 // FIXME: Improve diagnostic.
1552 if (getLexer().isNot(AsmToken::Comma))
1553 return TokError("unexpected token in directive");
1562 /// ParseDirectiveRealValue
1563 /// ::= (.single | .double) [ expression (, expression)* ]
1564 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1565 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1566 CheckForValidSection();
1569 // We don't truly support arithmetic on floating point expressions, so we
1570 // have to manually parse unary prefixes.
1572 if (getLexer().is(AsmToken::Minus)) {
1575 } else if (getLexer().is(AsmToken::Plus))
1578 if (getLexer().isNot(AsmToken::Integer) &&
1579 getLexer().isNot(AsmToken::Real) &&
1580 getLexer().isNot(AsmToken::Identifier))
1581 return TokError("unexpected token in directive");
1583 // Convert to an APFloat.
1584 APFloat Value(Semantics);
1585 StringRef IDVal = getTok().getString();
1586 if (getLexer().is(AsmToken::Identifier)) {
1587 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1588 Value = APFloat::getInf(Semantics);
1589 else if (!IDVal.compare_lower("nan"))
1590 Value = APFloat::getNaN(Semantics, false, ~0);
1592 return TokError("invalid floating point literal");
1593 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1594 APFloat::opInvalidOp)
1595 return TokError("invalid floating point literal");
1599 // Consume the numeric token.
1602 // Emit the value as an integer.
1603 APInt AsInt = Value.bitcastToAPInt();
1604 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1605 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1607 if (getLexer().is(AsmToken::EndOfStatement))
1610 if (getLexer().isNot(AsmToken::Comma))
1611 return TokError("unexpected token in directive");
1620 /// ParseDirectiveSpace
1621 /// ::= .space expression [ , expression ]
1622 bool AsmParser::ParseDirectiveSpace() {
1623 CheckForValidSection();
1626 if (ParseAbsoluteExpression(NumBytes))
1629 int64_t FillExpr = 0;
1630 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1631 if (getLexer().isNot(AsmToken::Comma))
1632 return TokError("unexpected token in '.space' directive");
1635 if (ParseAbsoluteExpression(FillExpr))
1638 if (getLexer().isNot(AsmToken::EndOfStatement))
1639 return TokError("unexpected token in '.space' directive");
1645 return TokError("invalid number of bytes in '.space' directive");
1647 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1648 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1653 /// ParseDirectiveZero
1654 /// ::= .zero expression
1655 bool AsmParser::ParseDirectiveZero() {
1656 CheckForValidSection();
1659 if (ParseAbsoluteExpression(NumBytes))
1663 if (getLexer().is(AsmToken::Comma)) {
1665 if (ParseAbsoluteExpression(Val))
1669 if (getLexer().isNot(AsmToken::EndOfStatement))
1670 return TokError("unexpected token in '.zero' directive");
1674 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1679 /// ParseDirectiveFill
1680 /// ::= .fill expression , expression , expression
1681 bool AsmParser::ParseDirectiveFill() {
1682 CheckForValidSection();
1685 if (ParseAbsoluteExpression(NumValues))
1688 if (getLexer().isNot(AsmToken::Comma))
1689 return TokError("unexpected token in '.fill' directive");
1693 if (ParseAbsoluteExpression(FillSize))
1696 if (getLexer().isNot(AsmToken::Comma))
1697 return TokError("unexpected token in '.fill' directive");
1701 if (ParseAbsoluteExpression(FillExpr))
1704 if (getLexer().isNot(AsmToken::EndOfStatement))
1705 return TokError("unexpected token in '.fill' directive");
1709 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1710 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1712 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1713 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1718 /// ParseDirectiveOrg
1719 /// ::= .org expression [ , expression ]
1720 bool AsmParser::ParseDirectiveOrg() {
1721 CheckForValidSection();
1723 const MCExpr *Offset;
1724 if (ParseExpression(Offset))
1727 // Parse optional fill expression.
1728 int64_t FillExpr = 0;
1729 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1730 if (getLexer().isNot(AsmToken::Comma))
1731 return TokError("unexpected token in '.org' directive");
1734 if (ParseAbsoluteExpression(FillExpr))
1737 if (getLexer().isNot(AsmToken::EndOfStatement))
1738 return TokError("unexpected token in '.org' directive");
1743 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1744 // has to be relative to the current section.
1745 getStreamer().EmitValueToOffset(Offset, FillExpr);
1750 /// ParseDirectiveAlign
1751 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1752 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1753 CheckForValidSection();
1755 SMLoc AlignmentLoc = getLexer().getLoc();
1757 if (ParseAbsoluteExpression(Alignment))
1761 bool HasFillExpr = false;
1762 int64_t FillExpr = 0;
1763 int64_t MaxBytesToFill = 0;
1764 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1765 if (getLexer().isNot(AsmToken::Comma))
1766 return TokError("unexpected token in directive");
1769 // The fill expression can be omitted while specifying a maximum number of
1770 // alignment bytes, e.g:
1772 if (getLexer().isNot(AsmToken::Comma)) {
1774 if (ParseAbsoluteExpression(FillExpr))
1778 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1779 if (getLexer().isNot(AsmToken::Comma))
1780 return TokError("unexpected token in directive");
1783 MaxBytesLoc = getLexer().getLoc();
1784 if (ParseAbsoluteExpression(MaxBytesToFill))
1787 if (getLexer().isNot(AsmToken::EndOfStatement))
1788 return TokError("unexpected token in directive");
1797 // Compute alignment in bytes.
1799 // FIXME: Diagnose overflow.
1800 if (Alignment >= 32) {
1801 Error(AlignmentLoc, "invalid alignment value");
1805 Alignment = 1ULL << Alignment;
1808 // Diagnose non-sensical max bytes to align.
1809 if (MaxBytesLoc.isValid()) {
1810 if (MaxBytesToFill < 1) {
1811 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1812 "many bytes, ignoring maximum bytes expression");
1816 if (MaxBytesToFill >= Alignment) {
1817 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1823 // Check whether we should use optimal code alignment for this .align
1825 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1826 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1827 ValueSize == 1 && UseCodeAlign) {
1828 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1830 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1831 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1838 /// ParseDirectiveSymbolAttribute
1839 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1840 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1841 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1845 if (ParseIdentifier(Name))
1846 return TokError("expected identifier in directive");
1848 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1850 getStreamer().EmitSymbolAttribute(Sym, Attr);
1852 if (getLexer().is(AsmToken::EndOfStatement))
1855 if (getLexer().isNot(AsmToken::Comma))
1856 return TokError("unexpected token in directive");
1865 /// ParseDirectiveComm
1866 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1867 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1868 CheckForValidSection();
1870 SMLoc IDLoc = getLexer().getLoc();
1872 if (ParseIdentifier(Name))
1873 return TokError("expected identifier in directive");
1875 // Handle the identifier as the key symbol.
1876 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1878 if (getLexer().isNot(AsmToken::Comma))
1879 return TokError("unexpected token in directive");
1883 SMLoc SizeLoc = getLexer().getLoc();
1884 if (ParseAbsoluteExpression(Size))
1887 int64_t Pow2Alignment = 0;
1888 SMLoc Pow2AlignmentLoc;
1889 if (getLexer().is(AsmToken::Comma)) {
1891 Pow2AlignmentLoc = getLexer().getLoc();
1892 if (ParseAbsoluteExpression(Pow2Alignment))
1895 // If this target takes alignments in bytes (not log) validate and convert.
1896 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1897 if (!isPowerOf2_64(Pow2Alignment))
1898 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1899 Pow2Alignment = Log2_64(Pow2Alignment);
1903 if (getLexer().isNot(AsmToken::EndOfStatement))
1904 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1908 // NOTE: a size of zero for a .comm should create a undefined symbol
1909 // but a size of .lcomm creates a bss symbol of size zero.
1911 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1912 "be less than zero");
1914 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1915 // may internally end up wanting an alignment in bytes.
1916 // FIXME: Diagnose overflow.
1917 if (Pow2Alignment < 0)
1918 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1919 "alignment, can't be less than zero");
1921 if (!Sym->isUndefined())
1922 return Error(IDLoc, "invalid symbol redefinition");
1924 // '.lcomm' is equivalent to '.zerofill'.
1925 // Create the Symbol as a common or local common with Size and Pow2Alignment
1927 getStreamer().EmitZerofill(Ctx.getMachOSection(
1928 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1929 0, SectionKind::getBSS()),
1930 Sym, Size, 1 << Pow2Alignment);
1934 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1938 /// ParseDirectiveAbort
1939 /// ::= .abort [... message ...]
1940 bool AsmParser::ParseDirectiveAbort() {
1941 // FIXME: Use loc from directive.
1942 SMLoc Loc = getLexer().getLoc();
1944 StringRef Str = ParseStringToEndOfStatement();
1945 if (getLexer().isNot(AsmToken::EndOfStatement))
1946 return TokError("unexpected token in '.abort' directive");
1951 Error(Loc, ".abort detected. Assembly stopping.");
1953 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1954 // FIXME: Actually abort assembly here.
1959 /// ParseDirectiveInclude
1960 /// ::= .include "filename"
1961 bool AsmParser::ParseDirectiveInclude() {
1962 if (getLexer().isNot(AsmToken::String))
1963 return TokError("expected string in '.include' directive");
1965 std::string Filename = getTok().getString();
1966 SMLoc IncludeLoc = getLexer().getLoc();
1969 if (getLexer().isNot(AsmToken::EndOfStatement))
1970 return TokError("unexpected token in '.include' directive");
1972 // Strip the quotes.
1973 Filename = Filename.substr(1, Filename.size()-2);
1975 // Attempt to switch the lexer to the included file before consuming the end
1976 // of statement to avoid losing it when we switch.
1977 if (EnterIncludeFile(Filename)) {
1978 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1985 /// ParseDirectiveIf
1986 /// ::= .if expression
1987 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1988 TheCondStack.push_back(TheCondState);
1989 TheCondState.TheCond = AsmCond::IfCond;
1990 if(TheCondState.Ignore) {
1991 EatToEndOfStatement();
1995 if (ParseAbsoluteExpression(ExprValue))
1998 if (getLexer().isNot(AsmToken::EndOfStatement))
1999 return TokError("unexpected token in '.if' directive");
2003 TheCondState.CondMet = ExprValue;
2004 TheCondState.Ignore = !TheCondState.CondMet;
2010 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2012 TheCondStack.push_back(TheCondState);
2013 TheCondState.TheCond = AsmCond::IfCond;
2015 if (TheCondState.Ignore) {
2016 EatToEndOfStatement();
2018 if (ParseIdentifier(Name))
2019 return TokError("expected identifier after '.ifdef'");
2023 MCSymbol *Sym = getContext().LookupSymbol(Name);
2026 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2028 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2029 TheCondState.Ignore = !TheCondState.CondMet;
2035 /// ParseDirectiveElseIf
2036 /// ::= .elseif expression
2037 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2038 if (TheCondState.TheCond != AsmCond::IfCond &&
2039 TheCondState.TheCond != AsmCond::ElseIfCond)
2040 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2042 TheCondState.TheCond = AsmCond::ElseIfCond;
2044 bool LastIgnoreState = false;
2045 if (!TheCondStack.empty())
2046 LastIgnoreState = TheCondStack.back().Ignore;
2047 if (LastIgnoreState || TheCondState.CondMet) {
2048 TheCondState.Ignore = true;
2049 EatToEndOfStatement();
2053 if (ParseAbsoluteExpression(ExprValue))
2056 if (getLexer().isNot(AsmToken::EndOfStatement))
2057 return TokError("unexpected token in '.elseif' directive");
2060 TheCondState.CondMet = ExprValue;
2061 TheCondState.Ignore = !TheCondState.CondMet;
2067 /// ParseDirectiveElse
2069 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2070 if (getLexer().isNot(AsmToken::EndOfStatement))
2071 return TokError("unexpected token in '.else' directive");
2075 if (TheCondState.TheCond != AsmCond::IfCond &&
2076 TheCondState.TheCond != AsmCond::ElseIfCond)
2077 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2079 TheCondState.TheCond = AsmCond::ElseCond;
2080 bool LastIgnoreState = false;
2081 if (!TheCondStack.empty())
2082 LastIgnoreState = TheCondStack.back().Ignore;
2083 if (LastIgnoreState || TheCondState.CondMet)
2084 TheCondState.Ignore = true;
2086 TheCondState.Ignore = false;
2091 /// ParseDirectiveEndIf
2093 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2094 if (getLexer().isNot(AsmToken::EndOfStatement))
2095 return TokError("unexpected token in '.endif' directive");
2099 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2100 TheCondStack.empty())
2101 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2103 if (!TheCondStack.empty()) {
2104 TheCondState = TheCondStack.back();
2105 TheCondStack.pop_back();
2111 /// ParseDirectiveFile
2112 /// ::= .file [number] string
2113 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2114 // FIXME: I'm not sure what this is.
2115 int64_t FileNumber = -1;
2116 SMLoc FileNumberLoc = getLexer().getLoc();
2117 if (getLexer().is(AsmToken::Integer)) {
2118 FileNumber = getTok().getIntVal();
2122 return TokError("file number less than one");
2125 if (getLexer().isNot(AsmToken::String))
2126 return TokError("unexpected token in '.file' directive");
2128 StringRef Filename = getTok().getString();
2129 Filename = Filename.substr(1, Filename.size()-2);
2132 if (getLexer().isNot(AsmToken::EndOfStatement))
2133 return TokError("unexpected token in '.file' directive");
2135 if (FileNumber == -1)
2136 getStreamer().EmitFileDirective(Filename);
2138 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2139 Error(FileNumberLoc, "file number already allocated");
2145 /// ParseDirectiveLine
2146 /// ::= .line [number]
2147 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2148 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2149 if (getLexer().isNot(AsmToken::Integer))
2150 return TokError("unexpected token in '.line' directive");
2152 int64_t LineNumber = getTok().getIntVal();
2156 // FIXME: Do something with the .line.
2159 if (getLexer().isNot(AsmToken::EndOfStatement))
2160 return TokError("unexpected token in '.line' directive");
2166 /// ParseDirectiveLoc
2167 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2168 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2169 /// The first number is a file number, must have been previously assigned with
2170 /// a .file directive, the second number is the line number and optionally the
2171 /// third number is a column position (zero if not specified). The remaining
2172 /// optional items are .loc sub-directives.
2173 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2175 if (getLexer().isNot(AsmToken::Integer))
2176 return TokError("unexpected token in '.loc' directive");
2177 int64_t FileNumber = getTok().getIntVal();
2179 return TokError("file number less than one in '.loc' directive");
2180 if (!getContext().isValidDwarfFileNumber(FileNumber))
2181 return TokError("unassigned file number in '.loc' directive");
2184 int64_t LineNumber = 0;
2185 if (getLexer().is(AsmToken::Integer)) {
2186 LineNumber = getTok().getIntVal();
2188 return TokError("line number less than one in '.loc' directive");
2192 int64_t ColumnPos = 0;
2193 if (getLexer().is(AsmToken::Integer)) {
2194 ColumnPos = getTok().getIntVal();
2196 return TokError("column position less than zero in '.loc' directive");
2200 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2202 int64_t Discriminator = 0;
2203 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2205 if (getLexer().is(AsmToken::EndOfStatement))
2209 SMLoc Loc = getTok().getLoc();
2210 if (getParser().ParseIdentifier(Name))
2211 return TokError("unexpected token in '.loc' directive");
2213 if (Name == "basic_block")
2214 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2215 else if (Name == "prologue_end")
2216 Flags |= DWARF2_FLAG_PROLOGUE_END;
2217 else if (Name == "epilogue_begin")
2218 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2219 else if (Name == "is_stmt") {
2220 SMLoc Loc = getTok().getLoc();
2221 const MCExpr *Value;
2222 if (getParser().ParseExpression(Value))
2224 // The expression must be the constant 0 or 1.
2225 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2226 int Value = MCE->getValue();
2228 Flags &= ~DWARF2_FLAG_IS_STMT;
2229 else if (Value == 1)
2230 Flags |= DWARF2_FLAG_IS_STMT;
2232 return Error(Loc, "is_stmt value not 0 or 1");
2235 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2238 else if (Name == "isa") {
2239 SMLoc Loc = getTok().getLoc();
2240 const MCExpr *Value;
2241 if (getParser().ParseExpression(Value))
2243 // The expression must be a constant greater or equal to 0.
2244 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2245 int Value = MCE->getValue();
2247 return Error(Loc, "isa number less than zero");
2251 return Error(Loc, "isa number not a constant value");
2254 else if (Name == "discriminator") {
2255 if (getParser().ParseAbsoluteExpression(Discriminator))
2259 return Error(Loc, "unknown sub-directive in '.loc' directive");
2262 if (getLexer().is(AsmToken::EndOfStatement))
2267 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2268 Isa, Discriminator, StringRef());
2273 /// ParseDirectiveStabs
2274 /// ::= .stabs string, number, number, number
2275 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2276 SMLoc DirectiveLoc) {
2277 return TokError("unsupported directive '" + Directive + "'");
2280 /// ParseDirectiveCFISections
2281 /// ::= .cfi_sections section [, section]
2282 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2283 SMLoc DirectiveLoc) {
2288 if (getParser().ParseIdentifier(Name))
2289 return TokError("Expected an identifier");
2291 if (Name == ".eh_frame")
2293 else if (Name == ".debug_frame")
2296 if (getLexer().is(AsmToken::Comma)) {
2299 if (getParser().ParseIdentifier(Name))
2300 return TokError("Expected an identifier");
2302 if (Name == ".eh_frame")
2304 else if (Name == ".debug_frame")
2308 getStreamer().EmitCFISections(EH, Debug);
2313 /// ParseDirectiveCFIStartProc
2314 /// ::= .cfi_startproc
2315 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2316 SMLoc DirectiveLoc) {
2317 getStreamer().EmitCFIStartProc();
2321 /// ParseDirectiveCFIEndProc
2322 /// ::= .cfi_endproc
2323 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2324 getStreamer().EmitCFIEndProc();
2328 /// ParseRegisterOrRegisterNumber - parse register name or number.
2329 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2330 SMLoc DirectiveLoc) {
2333 if (getLexer().isNot(AsmToken::Integer)) {
2334 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2337 Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2339 return getParser().ParseAbsoluteExpression(Register);
2344 /// ParseDirectiveCFIDefCfa
2345 /// ::= .cfi_def_cfa register, offset
2346 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2347 SMLoc DirectiveLoc) {
2348 int64_t Register = 0;
2349 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2352 if (getLexer().isNot(AsmToken::Comma))
2353 return TokError("unexpected token in directive");
2357 if (getParser().ParseAbsoluteExpression(Offset))
2360 getStreamer().EmitCFIDefCfa(Register, Offset);
2364 /// ParseDirectiveCFIDefCfaOffset
2365 /// ::= .cfi_def_cfa_offset offset
2366 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2367 SMLoc DirectiveLoc) {
2369 if (getParser().ParseAbsoluteExpression(Offset))
2372 getStreamer().EmitCFIDefCfaOffset(Offset);
2376 /// ParseDirectiveCFIAdjustCfaOffset
2377 /// ::= .cfi_adjust_cfa_offset adjustment
2378 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2379 SMLoc DirectiveLoc) {
2380 int64_t Adjustment = 0;
2381 if (getParser().ParseAbsoluteExpression(Adjustment))
2384 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2388 /// ParseDirectiveCFIDefCfaRegister
2389 /// ::= .cfi_def_cfa_register register
2390 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2391 SMLoc DirectiveLoc) {
2392 int64_t Register = 0;
2393 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2396 getStreamer().EmitCFIDefCfaRegister(Register);
2400 /// ParseDirectiveCFIOffset
2401 /// ::= .cfi_offset register, offset
2402 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2403 int64_t Register = 0;
2406 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2409 if (getLexer().isNot(AsmToken::Comma))
2410 return TokError("unexpected token in directive");
2413 if (getParser().ParseAbsoluteExpression(Offset))
2416 getStreamer().EmitCFIOffset(Register, Offset);
2420 /// ParseDirectiveCFIRelOffset
2421 /// ::= .cfi_rel_offset register, offset
2422 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2423 SMLoc DirectiveLoc) {
2424 int64_t Register = 0;
2426 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2429 if (getLexer().isNot(AsmToken::Comma))
2430 return TokError("unexpected token in directive");
2434 if (getParser().ParseAbsoluteExpression(Offset))
2437 getStreamer().EmitCFIRelOffset(Register, Offset);
2441 static bool isValidEncoding(int64_t Encoding) {
2442 if (Encoding & ~0xff)
2445 if (Encoding == dwarf::DW_EH_PE_omit)
2448 const unsigned Format = Encoding & 0xf;
2449 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2450 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2451 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2452 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2455 const unsigned Application = Encoding & 0x70;
2456 if (Application != dwarf::DW_EH_PE_absptr &&
2457 Application != dwarf::DW_EH_PE_pcrel)
2463 /// ParseDirectiveCFIPersonalityOrLsda
2464 /// ::= .cfi_personality encoding, [symbol_name]
2465 /// ::= .cfi_lsda encoding, [symbol_name]
2466 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2467 SMLoc DirectiveLoc) {
2468 int64_t Encoding = 0;
2469 if (getParser().ParseAbsoluteExpression(Encoding))
2471 if (Encoding == dwarf::DW_EH_PE_omit)
2474 if (!isValidEncoding(Encoding))
2475 return TokError("unsupported encoding.");
2477 if (getLexer().isNot(AsmToken::Comma))
2478 return TokError("unexpected token in directive");
2482 if (getParser().ParseIdentifier(Name))
2483 return TokError("expected identifier in directive");
2485 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2487 if (IDVal == ".cfi_personality")
2488 getStreamer().EmitCFIPersonality(Sym, Encoding);
2490 assert(IDVal == ".cfi_lsda");
2491 getStreamer().EmitCFILsda(Sym, Encoding);
2496 /// ParseDirectiveCFIRememberState
2497 /// ::= .cfi_remember_state
2498 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2499 SMLoc DirectiveLoc) {
2500 getStreamer().EmitCFIRememberState();
2504 /// ParseDirectiveCFIRestoreState
2505 /// ::= .cfi_remember_state
2506 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2507 SMLoc DirectiveLoc) {
2508 getStreamer().EmitCFIRestoreState();
2512 /// ParseDirectiveCFISameValue
2513 /// ::= .cfi_same_value register
2514 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2515 SMLoc DirectiveLoc) {
2516 int64_t Register = 0;
2518 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2521 getStreamer().EmitCFISameValue(Register);
2526 /// ParseDirectiveMacrosOnOff
2529 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2530 SMLoc DirectiveLoc) {
2531 if (getLexer().isNot(AsmToken::EndOfStatement))
2532 return Error(getLexer().getLoc(),
2533 "unexpected token in '" + Directive + "' directive");
2535 getParser().MacrosEnabled = Directive == ".macros_on";
2540 /// ParseDirectiveMacro
2542 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2543 SMLoc DirectiveLoc) {
2545 if (getParser().ParseIdentifier(Name))
2546 return TokError("expected identifier in directive");
2548 if (getLexer().isNot(AsmToken::EndOfStatement))
2549 return TokError("unexpected token in '.macro' directive");
2551 // Eat the end of statement.
2554 AsmToken EndToken, StartToken = getTok();
2556 // Lex the macro definition.
2558 // Check whether we have reached the end of the file.
2559 if (getLexer().is(AsmToken::Eof))
2560 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2562 // Otherwise, check whether we have reach the .endmacro.
2563 if (getLexer().is(AsmToken::Identifier) &&
2564 (getTok().getIdentifier() == ".endm" ||
2565 getTok().getIdentifier() == ".endmacro")) {
2566 EndToken = getTok();
2568 if (getLexer().isNot(AsmToken::EndOfStatement))
2569 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2574 // Otherwise, scan til the end of the statement.
2575 getParser().EatToEndOfStatement();
2578 if (getParser().MacroMap.lookup(Name)) {
2579 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2582 const char *BodyStart = StartToken.getLoc().getPointer();
2583 const char *BodyEnd = EndToken.getLoc().getPointer();
2584 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2585 getParser().MacroMap[Name] = new Macro(Name, Body);
2589 /// ParseDirectiveEndMacro
2592 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2593 SMLoc DirectiveLoc) {
2594 if (getLexer().isNot(AsmToken::EndOfStatement))
2595 return TokError("unexpected token in '" + Directive + "' directive");
2597 // If we are inside a macro instantiation, terminate the current
2599 if (!getParser().ActiveMacros.empty()) {
2600 getParser().HandleMacroExit();
2604 // Otherwise, this .endmacro is a stray entry in the file; well formed
2605 // .endmacro directives are handled during the macro definition parsing.
2606 return TokError("unexpected '" + Directive + "' in file, "
2607 "no current macro definition");
2610 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2611 getParser().CheckForValidSection();
2613 const MCExpr *Value;
2615 if (getParser().ParseExpression(Value))
2618 if (getLexer().isNot(AsmToken::EndOfStatement))
2619 return TokError("unexpected token in directive");
2621 if (DirName[1] == 's')
2622 getStreamer().EmitSLEB128Value(Value);
2624 getStreamer().EmitULEB128Value(Value);
2630 /// \brief Create an MCAsmParser instance.
2631 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2632 MCContext &C, MCStreamer &Out,
2633 const MCAsmInfo &MAI) {
2634 return new AsmParser(T, SM, C, Out, MAI);