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.
50 std::vector<StringRef> Parameters;
53 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
54 Name(N), Body(B), Parameters(P) {}
57 /// \brief Helper class for storing information about an active macro
59 struct MacroInstantiation {
60 /// The macro being instantiated.
61 const Macro *TheMacro;
63 /// The macro instantiation with substitutions.
64 MemoryBuffer *Instantiation;
66 /// The location of the instantiation.
67 SMLoc InstantiationLoc;
69 /// The location where parsing should resume upon instantiation completion.
73 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
77 /// \brief The concrete assembly parser instance.
78 class AsmParser : public MCAsmParser {
79 friend class GenericAsmParser;
81 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
82 void operator=(const AsmParser &); // DO NOT IMPLEMENT
89 MCAsmParserExtension *GenericParser;
90 MCAsmParserExtension *PlatformParser;
92 /// This is the current buffer index we're lexing from as managed by the
97 std::vector<AsmCond> TheCondStack;
99 /// DirectiveMap - This is a table handlers for directives. Each handler is
100 /// invoked after the directive identifier is read and is responsible for
101 /// parsing and validating the rest of the directive. The handler is passed
102 /// in the directive name and the location of the directive keyword.
103 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
105 /// MacroMap - Map of currently defined macros.
106 StringMap<Macro*> MacroMap;
108 /// ActiveMacros - Stack of active macro instantiations.
109 std::vector<MacroInstantiation*> ActiveMacros;
111 /// Boolean tracking whether macro substitution is enabled.
112 unsigned MacrosEnabled : 1;
114 /// Flag tracking whether any errors have been encountered.
115 unsigned HadError : 1;
118 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
119 const MCAsmInfo &MAI);
122 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
124 void AddDirectiveHandler(MCAsmParserExtension *Object,
126 DirectiveHandler Handler) {
127 DirectiveMap[Directive] = std::make_pair(Object, Handler);
131 /// @name MCAsmParser Interface
134 virtual SourceMgr &getSourceManager() { return SrcMgr; }
135 virtual MCAsmLexer &getLexer() { return Lexer; }
136 virtual MCContext &getContext() { return Ctx; }
137 virtual MCStreamer &getStreamer() { return Out; }
139 virtual bool Warning(SMLoc L, const Twine &Msg);
140 virtual bool Error(SMLoc L, const Twine &Msg);
142 const AsmToken &Lex();
144 bool ParseExpression(const MCExpr *&Res);
145 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
146 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
147 virtual bool ParseAbsoluteExpression(int64_t &Res);
152 void CheckForValidSection();
154 bool ParseStatement();
156 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
157 bool expandMacro(SmallString<256> &Buf, StringRef Body,
158 const std::vector<StringRef> &Parameters,
159 const std::vector<std::vector<AsmToken> > &A,
161 void HandleMacroExit();
163 void PrintMacroInstantiations();
164 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type,
165 bool ShowLine = true) const {
166 SrcMgr.PrintMessage(Loc, Msg, Type, ShowLine);
169 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
170 bool EnterIncludeFile(const std::string &Filename);
172 /// \brief Reset the current lexer position to that given by \arg Loc. The
173 /// current token is not set; clients should ensure Lex() is called
175 void JumpToLoc(SMLoc Loc);
177 void EatToEndOfStatement();
179 /// \brief Parse up to the end of statement and a return the contents from the
180 /// current token until the end of the statement; the current token on exit
181 /// will be either the EndOfStatement or EOF.
182 StringRef ParseStringToEndOfStatement();
184 bool ParseAssignment(StringRef Name, bool allow_redef);
186 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
187 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
188 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
189 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
191 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
192 /// and set \arg Res to the identifier contents.
193 bool ParseIdentifier(StringRef &Res);
195 // Directive Parsing.
197 // ".ascii", ".asciiz", ".string"
198 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
199 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
200 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
201 bool ParseDirectiveFill(); // ".fill"
202 bool ParseDirectiveSpace(); // ".space"
203 bool ParseDirectiveZero(); // ".zero"
204 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
205 bool ParseDirectiveOrg(); // ".org"
206 // ".align{,32}", ".p2align{,w,l}"
207 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
209 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
210 /// accepts a single symbol (which should be a label or an external).
211 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
213 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
215 bool ParseDirectiveAbort(); // ".abort"
216 bool ParseDirectiveInclude(); // ".include"
218 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
219 // ".ifdef" or ".ifndef", depending on expect_defined
220 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
221 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
222 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
223 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
225 /// ParseEscapedString - Parse the current token as a string which may include
226 /// escaped characters and return the string contents.
227 bool ParseEscapedString(std::string &Data);
229 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
230 MCSymbolRefExpr::VariantKind Variant);
233 /// \brief Generic implementations of directive handling, etc. which is shared
234 /// (or the default, at least) for all assembler parser.
235 class GenericAsmParser : public MCAsmParserExtension {
236 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
237 void AddDirectiveHandler(StringRef Directive) {
238 getParser().AddDirectiveHandler(this, Directive,
239 HandleDirective<GenericAsmParser, Handler>);
242 GenericAsmParser() {}
244 AsmParser &getParser() {
245 return (AsmParser&) this->MCAsmParserExtension::getParser();
248 virtual void Initialize(MCAsmParser &Parser) {
249 // Call the base implementation.
250 this->MCAsmParserExtension::Initialize(Parser);
252 // Debugging directives.
253 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
254 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
255 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
256 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
259 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
261 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
263 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
265 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
268 ".cfi_def_cfa_offset");
269 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
270 ".cfi_adjust_cfa_offset");
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
272 ".cfi_def_cfa_register");
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
275 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
278 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
280 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
282 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
284 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
286 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
289 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
291 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
293 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
294 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
295 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
297 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
298 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
301 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
303 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
304 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
305 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
306 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
307 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
308 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
309 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
310 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
311 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
312 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
313 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
314 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
315 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
316 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
317 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
318 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
319 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
321 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
322 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
323 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
325 bool ParseDirectiveLEB128(StringRef, SMLoc);
332 extern MCAsmParserExtension *createDarwinAsmParser();
333 extern MCAsmParserExtension *createELFAsmParser();
334 extern MCAsmParserExtension *createCOFFAsmParser();
338 enum { DEFAULT_ADDRSPACE = 0 };
340 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
341 MCStreamer &_Out, const MCAsmInfo &_MAI)
342 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
343 GenericParser(new GenericAsmParser), PlatformParser(0),
344 CurBuffer(0), MacrosEnabled(true) {
345 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
347 // Initialize the generic parser.
348 GenericParser->Initialize(*this);
350 // Initialize the platform / file format parser.
352 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
354 if (_MAI.hasMicrosoftFastStdCallMangling()) {
355 PlatformParser = createCOFFAsmParser();
356 PlatformParser->Initialize(*this);
357 } else if (_MAI.hasSubsectionsViaSymbols()) {
358 PlatformParser = createDarwinAsmParser();
359 PlatformParser->Initialize(*this);
361 PlatformParser = createELFAsmParser();
362 PlatformParser->Initialize(*this);
366 AsmParser::~AsmParser() {
367 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
369 // Destroy any macros.
370 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
371 ie = MacroMap.end(); it != ie; ++it)
372 delete it->getValue();
374 delete PlatformParser;
375 delete GenericParser;
378 void AsmParser::PrintMacroInstantiations() {
379 // Print the active macro instantiation stack.
380 for (std::vector<MacroInstantiation*>::const_reverse_iterator
381 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
382 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
386 bool AsmParser::Warning(SMLoc L, const Twine &Msg) {
387 if (FatalAssemblerWarnings)
388 return Error(L, Msg);
389 PrintMessage(L, Msg, "warning");
390 PrintMacroInstantiations();
394 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
396 PrintMessage(L, Msg, "error");
397 PrintMacroInstantiations();
401 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
402 std::string IncludedFile;
403 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
409 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
414 void AsmParser::JumpToLoc(SMLoc Loc) {
415 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
416 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
419 const AsmToken &AsmParser::Lex() {
420 const AsmToken *tok = &Lexer.Lex();
422 if (tok->is(AsmToken::Eof)) {
423 // If this is the end of an included file, pop the parent file off the
425 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
426 if (ParentIncludeLoc != SMLoc()) {
427 JumpToLoc(ParentIncludeLoc);
432 if (tok->is(AsmToken::Error))
433 Error(Lexer.getErrLoc(), Lexer.getErr());
438 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
439 // Create the initial section, if requested.
440 if (!NoInitialTextSection)
447 AsmCond StartingCondState = TheCondState;
449 // While we have input, parse each statement.
450 while (Lexer.isNot(AsmToken::Eof)) {
451 if (!ParseStatement()) continue;
453 // We had an error, validate that one was emitted and recover by skipping to
455 assert(HadError && "Parse statement returned an error, but none emitted!");
456 EatToEndOfStatement();
459 if (TheCondState.TheCond != StartingCondState.TheCond ||
460 TheCondState.Ignore != StartingCondState.Ignore)
461 return TokError("unmatched .ifs or .elses");
463 // Check to see there are no empty DwarfFile slots.
464 const std::vector<MCDwarfFile *> &MCDwarfFiles =
465 getContext().getMCDwarfFiles();
466 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
467 if (!MCDwarfFiles[i])
468 TokError("unassigned file number: " + Twine(i) + " for .file directives");
471 // Check to see that all assembler local symbols were actually defined.
472 // Targets that don't do subsections via symbols may not want this, though,
473 // so conservatively exclude them. Only do this if we're finalizing, though,
474 // as otherwise we won't necessarilly have seen everything yet.
475 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
476 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
477 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
480 MCSymbol *Sym = i->getValue();
481 // Variable symbols may not be marked as defined, so check those
482 // explicitly. If we know it's a variable, we have a definition for
483 // the purposes of this check.
484 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
485 // FIXME: We would really like to refer back to where the symbol was
486 // first referenced for a source location. We need to add something
487 // to track that. Currently, we just point to the end of the file.
488 PrintMessage(getLexer().getLoc(), "assembler local symbol '" +
489 Sym->getName() + "' not defined", "error", false);
494 // Finalize the output stream if there are no errors and if the client wants
496 if (!HadError && !NoFinalize)
502 void AsmParser::CheckForValidSection() {
503 if (!getStreamer().getCurrentSection()) {
504 TokError("expected section directive before assembly directive");
505 Out.SwitchSection(Ctx.getMachOSection(
507 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
508 0, SectionKind::getText()));
512 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
513 void AsmParser::EatToEndOfStatement() {
514 while (Lexer.isNot(AsmToken::EndOfStatement) &&
515 Lexer.isNot(AsmToken::Eof))
519 if (Lexer.is(AsmToken::EndOfStatement))
523 StringRef AsmParser::ParseStringToEndOfStatement() {
524 const char *Start = getTok().getLoc().getPointer();
526 while (Lexer.isNot(AsmToken::EndOfStatement) &&
527 Lexer.isNot(AsmToken::Eof))
530 const char *End = getTok().getLoc().getPointer();
531 return StringRef(Start, End - Start);
534 /// ParseParenExpr - Parse a paren expression and return it.
535 /// NOTE: This assumes the leading '(' has already been consumed.
537 /// parenexpr ::= expr)
539 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
540 if (ParseExpression(Res)) return true;
541 if (Lexer.isNot(AsmToken::RParen))
542 return TokError("expected ')' in parentheses expression");
543 EndLoc = Lexer.getLoc();
548 /// ParseBracketExpr - Parse a bracket expression and return it.
549 /// NOTE: This assumes the leading '[' has already been consumed.
551 /// bracketexpr ::= expr]
553 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
554 if (ParseExpression(Res)) return true;
555 if (Lexer.isNot(AsmToken::RBrac))
556 return TokError("expected ']' in brackets expression");
557 EndLoc = Lexer.getLoc();
562 /// ParsePrimaryExpr - Parse a primary expression and return it.
563 /// primaryexpr ::= (parenexpr
564 /// primaryexpr ::= symbol
565 /// primaryexpr ::= number
566 /// primaryexpr ::= '.'
567 /// primaryexpr ::= ~,+,- primaryexpr
568 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
569 switch (Lexer.getKind()) {
571 return TokError("unknown token in expression");
572 // If we have an error assume that we've already handled it.
573 case AsmToken::Error:
575 case AsmToken::Exclaim:
576 Lex(); // Eat the operator.
577 if (ParsePrimaryExpr(Res, EndLoc))
579 Res = MCUnaryExpr::CreateLNot(Res, getContext());
581 case AsmToken::Dollar:
582 case AsmToken::String:
583 case AsmToken::Identifier: {
584 EndLoc = Lexer.getLoc();
586 StringRef Identifier;
587 if (ParseIdentifier(Identifier))
590 // This is a symbol reference.
591 std::pair<StringRef, StringRef> Split = Identifier.split('@');
592 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
594 // Lookup the symbol variant if used.
595 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
596 if (Split.first.size() != Identifier.size()) {
597 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
598 if (Variant == MCSymbolRefExpr::VK_Invalid) {
599 Variant = MCSymbolRefExpr::VK_None;
600 return TokError("invalid variant '" + Split.second + "'");
604 // If this is an absolute variable reference, substitute it now to preserve
605 // semantics in the face of reassignment.
606 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
608 return Error(EndLoc, "unexpected modifier on variable reference");
610 Res = Sym->getVariableValue();
614 // Otherwise create a symbol ref.
615 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
618 case AsmToken::Integer: {
619 SMLoc Loc = getTok().getLoc();
620 int64_t IntVal = getTok().getIntVal();
621 Res = MCConstantExpr::Create(IntVal, getContext());
622 EndLoc = Lexer.getLoc();
624 // Look for 'b' or 'f' following an Integer as a directional label
625 if (Lexer.getKind() == AsmToken::Identifier) {
626 StringRef IDVal = getTok().getString();
627 if (IDVal == "f" || IDVal == "b"){
628 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
629 IDVal == "f" ? 1 : 0);
630 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
632 if(IDVal == "b" && Sym->isUndefined())
633 return Error(Loc, "invalid reference to undefined symbol");
634 EndLoc = Lexer.getLoc();
635 Lex(); // Eat identifier.
640 case AsmToken::Real: {
641 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
642 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
643 Res = MCConstantExpr::Create(IntVal, getContext());
647 case AsmToken::Dot: {
648 // This is a '.' reference, which references the current PC. Emit a
649 // temporary label to the streamer and refer to it.
650 MCSymbol *Sym = Ctx.CreateTempSymbol();
652 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
653 EndLoc = Lexer.getLoc();
654 Lex(); // Eat identifier.
657 case AsmToken::LParen:
658 Lex(); // Eat the '('.
659 return ParseParenExpr(Res, EndLoc);
660 case AsmToken::LBrac:
661 if (!PlatformParser->HasBracketExpressions())
662 return TokError("brackets expression not supported on this target");
663 Lex(); // Eat the '['.
664 return ParseBracketExpr(Res, EndLoc);
665 case AsmToken::Minus:
666 Lex(); // Eat the operator.
667 if (ParsePrimaryExpr(Res, EndLoc))
669 Res = MCUnaryExpr::CreateMinus(Res, getContext());
672 Lex(); // Eat the operator.
673 if (ParsePrimaryExpr(Res, EndLoc))
675 Res = MCUnaryExpr::CreatePlus(Res, getContext());
677 case AsmToken::Tilde:
678 Lex(); // Eat the operator.
679 if (ParsePrimaryExpr(Res, EndLoc))
681 Res = MCUnaryExpr::CreateNot(Res, getContext());
686 bool AsmParser::ParseExpression(const MCExpr *&Res) {
688 return ParseExpression(Res, EndLoc);
692 AsmParser::ApplyModifierToExpr(const MCExpr *E,
693 MCSymbolRefExpr::VariantKind Variant) {
694 // Recurse over the given expression, rebuilding it to apply the given variant
695 // if there is exactly one symbol.
696 switch (E->getKind()) {
698 case MCExpr::Constant:
701 case MCExpr::SymbolRef: {
702 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
704 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
705 TokError("invalid variant on expression '" +
706 getTok().getIdentifier() + "' (already modified)");
710 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
713 case MCExpr::Unary: {
714 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
715 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
718 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
721 case MCExpr::Binary: {
722 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
723 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
724 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
729 if (!LHS) LHS = BE->getLHS();
730 if (!RHS) RHS = BE->getRHS();
732 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
736 assert(0 && "Invalid expression kind!");
740 /// ParseExpression - Parse an expression and return it.
742 /// expr ::= expr +,- expr -> lowest.
743 /// expr ::= expr |,^,&,! expr -> middle.
744 /// expr ::= expr *,/,%,<<,>> expr -> highest.
745 /// expr ::= primaryexpr
747 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
748 // Parse the expression.
750 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
753 // As a special case, we support 'a op b @ modifier' by rewriting the
754 // expression to include the modifier. This is inefficient, but in general we
755 // expect users to use 'a@modifier op b'.
756 if (Lexer.getKind() == AsmToken::At) {
759 if (Lexer.isNot(AsmToken::Identifier))
760 return TokError("unexpected symbol modifier following '@'");
762 MCSymbolRefExpr::VariantKind Variant =
763 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
764 if (Variant == MCSymbolRefExpr::VK_Invalid)
765 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
767 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
769 return TokError("invalid modifier '" + getTok().getIdentifier() +
770 "' (no symbols present)");
778 // Try to constant fold it up front, if possible.
780 if (Res->EvaluateAsAbsolute(Value))
781 Res = MCConstantExpr::Create(Value, getContext());
786 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
788 return ParseParenExpr(Res, EndLoc) ||
789 ParseBinOpRHS(1, Res, EndLoc);
792 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
795 SMLoc StartLoc = Lexer.getLoc();
796 if (ParseExpression(Expr))
799 if (!Expr->EvaluateAsAbsolute(Res))
800 return Error(StartLoc, "expected absolute expression");
805 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
806 MCBinaryExpr::Opcode &Kind) {
809 return 0; // not a binop.
811 // Lowest Precedence: &&, ||, @
812 case AsmToken::AmpAmp:
813 Kind = MCBinaryExpr::LAnd;
815 case AsmToken::PipePipe:
816 Kind = MCBinaryExpr::LOr;
820 // Low Precedence: |, &, ^
822 // FIXME: gas seems to support '!' as an infix operator?
824 Kind = MCBinaryExpr::Or;
826 case AsmToken::Caret:
827 Kind = MCBinaryExpr::Xor;
830 Kind = MCBinaryExpr::And;
833 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
834 case AsmToken::EqualEqual:
835 Kind = MCBinaryExpr::EQ;
837 case AsmToken::ExclaimEqual:
838 case AsmToken::LessGreater:
839 Kind = MCBinaryExpr::NE;
842 Kind = MCBinaryExpr::LT;
844 case AsmToken::LessEqual:
845 Kind = MCBinaryExpr::LTE;
847 case AsmToken::Greater:
848 Kind = MCBinaryExpr::GT;
850 case AsmToken::GreaterEqual:
851 Kind = MCBinaryExpr::GTE;
854 // High Intermediate Precedence: +, -
856 Kind = MCBinaryExpr::Add;
858 case AsmToken::Minus:
859 Kind = MCBinaryExpr::Sub;
862 // Highest Precedence: *, /, %, <<, >>
864 Kind = MCBinaryExpr::Mul;
866 case AsmToken::Slash:
867 Kind = MCBinaryExpr::Div;
869 case AsmToken::Percent:
870 Kind = MCBinaryExpr::Mod;
872 case AsmToken::LessLess:
873 Kind = MCBinaryExpr::Shl;
875 case AsmToken::GreaterGreater:
876 Kind = MCBinaryExpr::Shr;
882 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
883 /// Res contains the LHS of the expression on input.
884 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
887 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
888 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
890 // If the next token is lower precedence than we are allowed to eat, return
891 // successfully with what we ate already.
892 if (TokPrec < Precedence)
897 // Eat the next primary expression.
899 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
901 // If BinOp binds less tightly with RHS than the operator after RHS, let
902 // the pending operator take RHS as its LHS.
903 MCBinaryExpr::Opcode Dummy;
904 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
905 if (TokPrec < NextTokPrec) {
906 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
909 // Merge LHS and RHS according to operator.
910 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
918 /// ::= EndOfStatement
919 /// ::= Label* Directive ...Operands... EndOfStatement
920 /// ::= Label* Identifier OperandList* EndOfStatement
921 bool AsmParser::ParseStatement() {
922 if (Lexer.is(AsmToken::EndOfStatement)) {
928 // Statements always start with an identifier or are a full line comment.
929 AsmToken ID = getTok();
930 SMLoc IDLoc = ID.getLoc();
932 int64_t LocalLabelVal = -1;
933 // A full line comment is a '#' as the first token.
934 if (Lexer.is(AsmToken::Hash)) {
935 EatToEndOfStatement();
939 // Allow an integer followed by a ':' as a directional local label.
940 if (Lexer.is(AsmToken::Integer)) {
941 LocalLabelVal = getTok().getIntVal();
942 if (LocalLabelVal < 0) {
943 if (!TheCondState.Ignore)
944 return TokError("unexpected token at start of statement");
948 IDVal = getTok().getString();
949 Lex(); // Consume the integer token to be used as an identifier token.
950 if (Lexer.getKind() != AsmToken::Colon) {
951 if (!TheCondState.Ignore)
952 return TokError("unexpected token at start of statement");
956 } else if (Lexer.is(AsmToken::Dot)) {
957 // Treat '.' as a valid identifier in this context.
961 } else if (ParseIdentifier(IDVal)) {
962 if (!TheCondState.Ignore)
963 return TokError("unexpected token at start of statement");
968 // Handle conditional assembly here before checking for skipping. We
969 // have to do this so that .endif isn't skipped in a ".if 0" block for
972 return ParseDirectiveIf(IDLoc);
973 if (IDVal == ".ifdef")
974 return ParseDirectiveIfdef(IDLoc, true);
975 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
976 return ParseDirectiveIfdef(IDLoc, false);
977 if (IDVal == ".elseif")
978 return ParseDirectiveElseIf(IDLoc);
979 if (IDVal == ".else")
980 return ParseDirectiveElse(IDLoc);
981 if (IDVal == ".endif")
982 return ParseDirectiveEndIf(IDLoc);
984 // If we are in a ".if 0" block, ignore this statement.
985 if (TheCondState.Ignore) {
986 EatToEndOfStatement();
990 // FIXME: Recurse on local labels?
992 // See what kind of statement we have.
993 switch (Lexer.getKind()) {
994 case AsmToken::Colon: {
995 CheckForValidSection();
997 // identifier ':' -> Label.
1000 // Diagnose attempt to use '.' as a label.
1002 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1004 // Diagnose attempt to use a variable as a label.
1006 // FIXME: Diagnostics. Note the location of the definition as a label.
1007 // FIXME: This doesn't diagnose assignment to a symbol which has been
1008 // implicitly marked as external.
1010 if (LocalLabelVal == -1)
1011 Sym = getContext().GetOrCreateSymbol(IDVal);
1013 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1014 if (!Sym->isUndefined() || Sym->isVariable())
1015 return Error(IDLoc, "invalid symbol redefinition");
1020 // Consume any end of statement token, if present, to avoid spurious
1021 // AddBlankLine calls().
1022 if (Lexer.is(AsmToken::EndOfStatement)) {
1024 if (Lexer.is(AsmToken::Eof))
1028 return ParseStatement();
1031 case AsmToken::Equal:
1032 // identifier '=' ... -> assignment statement
1035 return ParseAssignment(IDVal, true);
1037 default: // Normal instruction or directive.
1041 // If macros are enabled, check to see if this is a macro instantiation.
1043 if (const Macro *M = MacroMap.lookup(IDVal))
1044 return HandleMacroEntry(IDVal, IDLoc, M);
1046 // Otherwise, we have a normal instruction or directive.
1047 if (IDVal[0] == '.' && IDVal != ".") {
1048 // Assembler features
1049 if (IDVal == ".set" || IDVal == ".equ")
1050 return ParseDirectiveSet(IDVal, true);
1051 if (IDVal == ".equiv")
1052 return ParseDirectiveSet(IDVal, false);
1056 if (IDVal == ".ascii")
1057 return ParseDirectiveAscii(IDVal, false);
1058 if (IDVal == ".asciz" || IDVal == ".string")
1059 return ParseDirectiveAscii(IDVal, true);
1061 if (IDVal == ".byte")
1062 return ParseDirectiveValue(1);
1063 if (IDVal == ".short")
1064 return ParseDirectiveValue(2);
1065 if (IDVal == ".value")
1066 return ParseDirectiveValue(2);
1067 if (IDVal == ".2byte")
1068 return ParseDirectiveValue(2);
1069 if (IDVal == ".long")
1070 return ParseDirectiveValue(4);
1071 if (IDVal == ".int")
1072 return ParseDirectiveValue(4);
1073 if (IDVal == ".4byte")
1074 return ParseDirectiveValue(4);
1075 if (IDVal == ".quad")
1076 return ParseDirectiveValue(8);
1077 if (IDVal == ".8byte")
1078 return ParseDirectiveValue(8);
1079 if (IDVal == ".single" || IDVal == ".float")
1080 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1081 if (IDVal == ".double")
1082 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1084 if (IDVal == ".align") {
1085 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1086 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1088 if (IDVal == ".align32") {
1089 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1090 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1092 if (IDVal == ".balign")
1093 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1094 if (IDVal == ".balignw")
1095 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1096 if (IDVal == ".balignl")
1097 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1098 if (IDVal == ".p2align")
1099 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1100 if (IDVal == ".p2alignw")
1101 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1102 if (IDVal == ".p2alignl")
1103 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1105 if (IDVal == ".org")
1106 return ParseDirectiveOrg();
1108 if (IDVal == ".fill")
1109 return ParseDirectiveFill();
1110 if (IDVal == ".space" || IDVal == ".skip")
1111 return ParseDirectiveSpace();
1112 if (IDVal == ".zero")
1113 return ParseDirectiveZero();
1115 // Symbol attribute directives
1117 if (IDVal == ".globl" || IDVal == ".global")
1118 return ParseDirectiveSymbolAttribute(MCSA_Global);
1119 // ELF only? Should it be here?
1120 if (IDVal == ".local")
1121 return ParseDirectiveSymbolAttribute(MCSA_Local);
1122 if (IDVal == ".hidden")
1123 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1124 if (IDVal == ".indirect_symbol")
1125 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1126 if (IDVal == ".internal")
1127 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1128 if (IDVal == ".lazy_reference")
1129 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1130 if (IDVal == ".no_dead_strip")
1131 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1132 if (IDVal == ".symbol_resolver")
1133 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1134 if (IDVal == ".private_extern")
1135 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1136 if (IDVal == ".protected")
1137 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1138 if (IDVal == ".reference")
1139 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1140 if (IDVal == ".weak")
1141 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1142 if (IDVal == ".weak_definition")
1143 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1144 if (IDVal == ".weak_reference")
1145 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1146 if (IDVal == ".weak_def_can_be_hidden")
1147 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1149 if (IDVal == ".comm" || IDVal == ".common")
1150 return ParseDirectiveComm(/*IsLocal=*/false);
1151 if (IDVal == ".lcomm")
1152 return ParseDirectiveComm(/*IsLocal=*/true);
1154 if (IDVal == ".abort")
1155 return ParseDirectiveAbort();
1156 if (IDVal == ".include")
1157 return ParseDirectiveInclude();
1159 if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1160 return TokError(Twine(IDVal) + " not supported yet");
1162 // Look up the handler in the handler table.
1163 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1164 DirectiveMap.lookup(IDVal);
1166 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1168 // Target hook for parsing target specific directives.
1169 if (!getTargetParser().ParseDirective(ID))
1172 bool retval = Warning(IDLoc, "ignoring directive for now");
1173 EatToEndOfStatement();
1177 CheckForValidSection();
1179 // Canonicalize the opcode to lower case.
1180 SmallString<128> Opcode;
1181 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1182 Opcode.push_back(tolower(IDVal[i]));
1184 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1185 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1188 // Dump the parsed representation, if requested.
1189 if (getShowParsedOperands()) {
1190 SmallString<256> Str;
1191 raw_svector_ostream OS(Str);
1192 OS << "parsed instruction: [";
1193 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1196 ParsedOperands[i]->dump(OS);
1200 PrintMessage(IDLoc, OS.str(), "note");
1203 // If parsing succeeded, match the instruction.
1205 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1208 // Free any parsed operands.
1209 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1210 delete ParsedOperands[i];
1212 // Don't skip the rest of the line, the instruction parser is responsible for
1217 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1218 const std::vector<StringRef> &Parameters,
1219 const std::vector<std::vector<AsmToken> > &A,
1221 raw_svector_ostream OS(Buf);
1222 unsigned NParameters = Parameters.size();
1223 if (NParameters != 0 && NParameters != A.size())
1224 return Error(L, "Wrong number of arguments");
1226 while (!Body.empty()) {
1227 // Scan for the next substitution.
1228 std::size_t End = Body.size(), Pos = 0;
1229 for (; Pos != End; ++Pos) {
1230 // Check for a substitution or escape.
1232 // This macro has no parameters, look for $0, $1, etc.
1233 if (Body[Pos] != '$' || Pos + 1 == End)
1236 char Next = Body[Pos + 1];
1237 if (Next == '$' || Next == 'n' || isdigit(Next))
1240 // This macro has parameters, look for \foo, \bar, etc.
1241 if (Body[Pos] == '\\' && Pos + 1 != End)
1247 OS << Body.slice(0, Pos);
1249 // Check if we reached the end.
1254 switch (Body[Pos+1]) {
1260 // $n => number of arguments
1265 // $[0-9] => argument
1267 // Missing arguments are ignored.
1268 unsigned Index = Body[Pos+1] - '0';
1269 if (Index >= A.size())
1272 // Otherwise substitute with the token values, with spaces eliminated.
1273 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1274 ie = A[Index].end(); it != ie; ++it)
1275 OS << it->getString();
1281 unsigned I = Pos + 1;
1282 while (isalnum(Body[I]) && I + 1 != End)
1285 const char *Begin = Body.data() + Pos +1;
1286 StringRef Argument(Begin, I - (Pos +1));
1288 for (; Index < NParameters; ++Index)
1289 if (Parameters[Index] == Argument)
1292 // FIXME: We should error at the macro definition.
1293 if (Index == NParameters)
1294 return Error(L, "Parameter not found");
1296 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1297 ie = A[Index].end(); it != ie; ++it)
1298 OS << it->getString();
1300 Pos += 1 + Argument.size();
1302 // Update the scan point.
1303 Body = Body.substr(Pos);
1306 // We include the .endmacro in the buffer as our queue to exit the macro
1308 OS << ".endmacro\n";
1312 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1314 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1318 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1320 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1321 // this, although we should protect against infinite loops.
1322 if (ActiveMacros.size() == 20)
1323 return TokError("macros cannot be nested more than 20 levels deep");
1325 // Parse the macro instantiation arguments.
1326 std::vector<std::vector<AsmToken> > MacroArguments;
1327 MacroArguments.push_back(std::vector<AsmToken>());
1328 unsigned ParenLevel = 0;
1330 if (Lexer.is(AsmToken::Eof))
1331 return TokError("unexpected token in macro instantiation");
1332 if (Lexer.is(AsmToken::EndOfStatement))
1335 // If we aren't inside parentheses and this is a comma, start a new token
1337 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1338 MacroArguments.push_back(std::vector<AsmToken>());
1340 // Adjust the current parentheses level.
1341 if (Lexer.is(AsmToken::LParen))
1343 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1346 // Append the token to the current argument list.
1347 MacroArguments.back().push_back(getTok());
1352 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1353 // to hold the macro body with substitutions.
1354 SmallString<256> Buf;
1355 StringRef Body = M->Body;
1357 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1360 MemoryBuffer *Instantiation =
1361 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1363 // Create the macro instantiation object and add to the current macro
1364 // instantiation stack.
1365 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1368 ActiveMacros.push_back(MI);
1370 // Jump to the macro instantiation and prime the lexer.
1371 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1372 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1378 void AsmParser::HandleMacroExit() {
1379 // Jump to the EndOfStatement we should return to, and consume it.
1380 JumpToLoc(ActiveMacros.back()->ExitLoc);
1383 // Pop the instantiation entry.
1384 delete ActiveMacros.back();
1385 ActiveMacros.pop_back();
1388 static void MarkUsed(const MCExpr *Value) {
1389 switch (Value->getKind()) {
1390 case MCExpr::Binary:
1391 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1392 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1394 case MCExpr::Target:
1395 case MCExpr::Constant:
1397 case MCExpr::SymbolRef: {
1398 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1402 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1407 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1408 // FIXME: Use better location, we should use proper tokens.
1409 SMLoc EqualLoc = Lexer.getLoc();
1411 const MCExpr *Value;
1412 if (ParseExpression(Value))
1417 if (Lexer.isNot(AsmToken::EndOfStatement))
1418 return TokError("unexpected token in assignment");
1420 // Error on assignment to '.'.
1422 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1423 "(use '.space' or '.org').)"));
1426 // Eat the end of statement marker.
1429 // Validate that the LHS is allowed to be a variable (either it has not been
1430 // used as a symbol, or it is an absolute symbol).
1431 MCSymbol *Sym = getContext().LookupSymbol(Name);
1433 // Diagnose assignment to a label.
1435 // FIXME: Diagnostics. Note the location of the definition as a label.
1436 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1437 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1438 ; // Allow redefinitions of undefined symbols only used in directives.
1439 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1440 return Error(EqualLoc, "redefinition of '" + Name + "'");
1441 else if (!Sym->isVariable())
1442 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1443 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1444 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1447 // Don't count these checks as uses.
1448 Sym->setUsed(false);
1450 Sym = getContext().GetOrCreateSymbol(Name);
1452 // FIXME: Handle '.'.
1454 // Do the assignment.
1455 Out.EmitAssignment(Sym, Value);
1460 /// ParseIdentifier:
1463 bool AsmParser::ParseIdentifier(StringRef &Res) {
1464 // The assembler has relaxed rules for accepting identifiers, in particular we
1465 // allow things like '.globl $foo', which would normally be separate
1466 // tokens. At this level, we have already lexed so we cannot (currently)
1467 // handle this as a context dependent token, instead we detect adjacent tokens
1468 // and return the combined identifier.
1469 if (Lexer.is(AsmToken::Dollar)) {
1470 SMLoc DollarLoc = getLexer().getLoc();
1472 // Consume the dollar sign, and check for a following identifier.
1474 if (Lexer.isNot(AsmToken::Identifier))
1477 // We have a '$' followed by an identifier, make sure they are adjacent.
1478 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1481 // Construct the joined identifier and consume the token.
1482 Res = StringRef(DollarLoc.getPointer(),
1483 getTok().getIdentifier().size() + 1);
1488 if (Lexer.isNot(AsmToken::Identifier) &&
1489 Lexer.isNot(AsmToken::String))
1492 Res = getTok().getIdentifier();
1494 Lex(); // Consume the identifier token.
1499 /// ParseDirectiveSet:
1500 /// ::= .equ identifier ',' expression
1501 /// ::= .equiv identifier ',' expression
1502 /// ::= .set identifier ',' expression
1503 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1506 if (ParseIdentifier(Name))
1507 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1509 if (getLexer().isNot(AsmToken::Comma))
1510 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1513 return ParseAssignment(Name, allow_redef);
1516 bool AsmParser::ParseEscapedString(std::string &Data) {
1517 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1520 StringRef Str = getTok().getStringContents();
1521 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1522 if (Str[i] != '\\') {
1527 // Recognize escaped characters. Note that this escape semantics currently
1528 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1531 return TokError("unexpected backslash at end of string");
1533 // Recognize octal sequences.
1534 if ((unsigned) (Str[i] - '0') <= 7) {
1535 // Consume up to three octal characters.
1536 unsigned Value = Str[i] - '0';
1538 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1540 Value = Value * 8 + (Str[i] - '0');
1542 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1544 Value = Value * 8 + (Str[i] - '0');
1549 return TokError("invalid octal escape sequence (out of range)");
1551 Data += (unsigned char) Value;
1555 // Otherwise recognize individual escapes.
1558 // Just reject invalid escape sequences for now.
1559 return TokError("invalid escape sequence (unrecognized character)");
1561 case 'b': Data += '\b'; break;
1562 case 'f': Data += '\f'; break;
1563 case 'n': Data += '\n'; break;
1564 case 'r': Data += '\r'; break;
1565 case 't': Data += '\t'; break;
1566 case '"': Data += '"'; break;
1567 case '\\': Data += '\\'; break;
1574 /// ParseDirectiveAscii:
1575 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1576 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1577 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1578 CheckForValidSection();
1581 if (getLexer().isNot(AsmToken::String))
1582 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1585 if (ParseEscapedString(Data))
1588 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1590 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1594 if (getLexer().is(AsmToken::EndOfStatement))
1597 if (getLexer().isNot(AsmToken::Comma))
1598 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1607 /// ParseDirectiveValue
1608 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1609 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1610 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1611 CheckForValidSection();
1614 const MCExpr *Value;
1615 if (ParseExpression(Value))
1618 // Special case constant expressions to match code generator.
1619 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1620 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1622 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1624 if (getLexer().is(AsmToken::EndOfStatement))
1627 // FIXME: Improve diagnostic.
1628 if (getLexer().isNot(AsmToken::Comma))
1629 return TokError("unexpected token in directive");
1638 /// ParseDirectiveRealValue
1639 /// ::= (.single | .double) [ expression (, expression)* ]
1640 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1641 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1642 CheckForValidSection();
1645 // We don't truly support arithmetic on floating point expressions, so we
1646 // have to manually parse unary prefixes.
1648 if (getLexer().is(AsmToken::Minus)) {
1651 } else if (getLexer().is(AsmToken::Plus))
1654 if (getLexer().isNot(AsmToken::Integer) &&
1655 getLexer().isNot(AsmToken::Real) &&
1656 getLexer().isNot(AsmToken::Identifier))
1657 return TokError("unexpected token in directive");
1659 // Convert to an APFloat.
1660 APFloat Value(Semantics);
1661 StringRef IDVal = getTok().getString();
1662 if (getLexer().is(AsmToken::Identifier)) {
1663 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1664 Value = APFloat::getInf(Semantics);
1665 else if (!IDVal.compare_lower("nan"))
1666 Value = APFloat::getNaN(Semantics, false, ~0);
1668 return TokError("invalid floating point literal");
1669 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1670 APFloat::opInvalidOp)
1671 return TokError("invalid floating point literal");
1675 // Consume the numeric token.
1678 // Emit the value as an integer.
1679 APInt AsInt = Value.bitcastToAPInt();
1680 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1681 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1683 if (getLexer().is(AsmToken::EndOfStatement))
1686 if (getLexer().isNot(AsmToken::Comma))
1687 return TokError("unexpected token in directive");
1696 /// ParseDirectiveSpace
1697 /// ::= .space expression [ , expression ]
1698 bool AsmParser::ParseDirectiveSpace() {
1699 CheckForValidSection();
1702 if (ParseAbsoluteExpression(NumBytes))
1705 int64_t FillExpr = 0;
1706 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1707 if (getLexer().isNot(AsmToken::Comma))
1708 return TokError("unexpected token in '.space' directive");
1711 if (ParseAbsoluteExpression(FillExpr))
1714 if (getLexer().isNot(AsmToken::EndOfStatement))
1715 return TokError("unexpected token in '.space' directive");
1721 return TokError("invalid number of bytes in '.space' directive");
1723 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1724 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1729 /// ParseDirectiveZero
1730 /// ::= .zero expression
1731 bool AsmParser::ParseDirectiveZero() {
1732 CheckForValidSection();
1735 if (ParseAbsoluteExpression(NumBytes))
1739 if (getLexer().is(AsmToken::Comma)) {
1741 if (ParseAbsoluteExpression(Val))
1745 if (getLexer().isNot(AsmToken::EndOfStatement))
1746 return TokError("unexpected token in '.zero' directive");
1750 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1755 /// ParseDirectiveFill
1756 /// ::= .fill expression , expression , expression
1757 bool AsmParser::ParseDirectiveFill() {
1758 CheckForValidSection();
1761 if (ParseAbsoluteExpression(NumValues))
1764 if (getLexer().isNot(AsmToken::Comma))
1765 return TokError("unexpected token in '.fill' directive");
1769 if (ParseAbsoluteExpression(FillSize))
1772 if (getLexer().isNot(AsmToken::Comma))
1773 return TokError("unexpected token in '.fill' directive");
1777 if (ParseAbsoluteExpression(FillExpr))
1780 if (getLexer().isNot(AsmToken::EndOfStatement))
1781 return TokError("unexpected token in '.fill' directive");
1785 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1786 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1788 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1789 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1794 /// ParseDirectiveOrg
1795 /// ::= .org expression [ , expression ]
1796 bool AsmParser::ParseDirectiveOrg() {
1797 CheckForValidSection();
1799 const MCExpr *Offset;
1800 if (ParseExpression(Offset))
1803 // Parse optional fill expression.
1804 int64_t FillExpr = 0;
1805 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1806 if (getLexer().isNot(AsmToken::Comma))
1807 return TokError("unexpected token in '.org' directive");
1810 if (ParseAbsoluteExpression(FillExpr))
1813 if (getLexer().isNot(AsmToken::EndOfStatement))
1814 return TokError("unexpected token in '.org' directive");
1819 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1820 // has to be relative to the current section.
1821 getStreamer().EmitValueToOffset(Offset, FillExpr);
1826 /// ParseDirectiveAlign
1827 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1828 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1829 CheckForValidSection();
1831 SMLoc AlignmentLoc = getLexer().getLoc();
1833 if (ParseAbsoluteExpression(Alignment))
1837 bool HasFillExpr = false;
1838 int64_t FillExpr = 0;
1839 int64_t MaxBytesToFill = 0;
1840 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1841 if (getLexer().isNot(AsmToken::Comma))
1842 return TokError("unexpected token in directive");
1845 // The fill expression can be omitted while specifying a maximum number of
1846 // alignment bytes, e.g:
1848 if (getLexer().isNot(AsmToken::Comma)) {
1850 if (ParseAbsoluteExpression(FillExpr))
1854 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1855 if (getLexer().isNot(AsmToken::Comma))
1856 return TokError("unexpected token in directive");
1859 MaxBytesLoc = getLexer().getLoc();
1860 if (ParseAbsoluteExpression(MaxBytesToFill))
1863 if (getLexer().isNot(AsmToken::EndOfStatement))
1864 return TokError("unexpected token in directive");
1873 // Compute alignment in bytes.
1875 // FIXME: Diagnose overflow.
1876 if (Alignment >= 32) {
1877 Error(AlignmentLoc, "invalid alignment value");
1881 Alignment = 1ULL << Alignment;
1884 // Diagnose non-sensical max bytes to align.
1885 if (MaxBytesLoc.isValid()) {
1886 if (MaxBytesToFill < 1) {
1887 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1888 "many bytes, ignoring maximum bytes expression");
1892 if (MaxBytesToFill >= Alignment) {
1893 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1899 // Check whether we should use optimal code alignment for this .align
1901 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1902 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1903 ValueSize == 1 && UseCodeAlign) {
1904 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1906 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1907 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1914 /// ParseDirectiveSymbolAttribute
1915 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1916 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1917 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1921 if (ParseIdentifier(Name))
1922 return TokError("expected identifier in directive");
1924 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1926 getStreamer().EmitSymbolAttribute(Sym, Attr);
1928 if (getLexer().is(AsmToken::EndOfStatement))
1931 if (getLexer().isNot(AsmToken::Comma))
1932 return TokError("unexpected token in directive");
1941 /// ParseDirectiveComm
1942 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1943 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1944 CheckForValidSection();
1946 SMLoc IDLoc = getLexer().getLoc();
1948 if (ParseIdentifier(Name))
1949 return TokError("expected identifier in directive");
1951 // Handle the identifier as the key symbol.
1952 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1954 if (getLexer().isNot(AsmToken::Comma))
1955 return TokError("unexpected token in directive");
1959 SMLoc SizeLoc = getLexer().getLoc();
1960 if (ParseAbsoluteExpression(Size))
1963 int64_t Pow2Alignment = 0;
1964 SMLoc Pow2AlignmentLoc;
1965 if (getLexer().is(AsmToken::Comma)) {
1967 Pow2AlignmentLoc = getLexer().getLoc();
1968 if (ParseAbsoluteExpression(Pow2Alignment))
1971 // If this target takes alignments in bytes (not log) validate and convert.
1972 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1973 if (!isPowerOf2_64(Pow2Alignment))
1974 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1975 Pow2Alignment = Log2_64(Pow2Alignment);
1979 if (getLexer().isNot(AsmToken::EndOfStatement))
1980 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1984 // NOTE: a size of zero for a .comm should create a undefined symbol
1985 // but a size of .lcomm creates a bss symbol of size zero.
1987 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1988 "be less than zero");
1990 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1991 // may internally end up wanting an alignment in bytes.
1992 // FIXME: Diagnose overflow.
1993 if (Pow2Alignment < 0)
1994 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1995 "alignment, can't be less than zero");
1997 if (!Sym->isUndefined())
1998 return Error(IDLoc, "invalid symbol redefinition");
2000 // '.lcomm' is equivalent to '.zerofill'.
2001 // Create the Symbol as a common or local common with Size and Pow2Alignment
2003 getStreamer().EmitZerofill(Ctx.getMachOSection(
2004 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2005 0, SectionKind::getBSS()),
2006 Sym, Size, 1 << Pow2Alignment);
2010 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2014 /// ParseDirectiveAbort
2015 /// ::= .abort [... message ...]
2016 bool AsmParser::ParseDirectiveAbort() {
2017 // FIXME: Use loc from directive.
2018 SMLoc Loc = getLexer().getLoc();
2020 StringRef Str = ParseStringToEndOfStatement();
2021 if (getLexer().isNot(AsmToken::EndOfStatement))
2022 return TokError("unexpected token in '.abort' directive");
2027 Error(Loc, ".abort detected. Assembly stopping.");
2029 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2030 // FIXME: Actually abort assembly here.
2035 /// ParseDirectiveInclude
2036 /// ::= .include "filename"
2037 bool AsmParser::ParseDirectiveInclude() {
2038 if (getLexer().isNot(AsmToken::String))
2039 return TokError("expected string in '.include' directive");
2041 std::string Filename = getTok().getString();
2042 SMLoc IncludeLoc = getLexer().getLoc();
2045 if (getLexer().isNot(AsmToken::EndOfStatement))
2046 return TokError("unexpected token in '.include' directive");
2048 // Strip the quotes.
2049 Filename = Filename.substr(1, Filename.size()-2);
2051 // Attempt to switch the lexer to the included file before consuming the end
2052 // of statement to avoid losing it when we switch.
2053 if (EnterIncludeFile(Filename)) {
2054 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2061 /// ParseDirectiveIf
2062 /// ::= .if expression
2063 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2064 TheCondStack.push_back(TheCondState);
2065 TheCondState.TheCond = AsmCond::IfCond;
2066 if(TheCondState.Ignore) {
2067 EatToEndOfStatement();
2071 if (ParseAbsoluteExpression(ExprValue))
2074 if (getLexer().isNot(AsmToken::EndOfStatement))
2075 return TokError("unexpected token in '.if' directive");
2079 TheCondState.CondMet = ExprValue;
2080 TheCondState.Ignore = !TheCondState.CondMet;
2086 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2088 TheCondStack.push_back(TheCondState);
2089 TheCondState.TheCond = AsmCond::IfCond;
2091 if (TheCondState.Ignore) {
2092 EatToEndOfStatement();
2094 if (ParseIdentifier(Name))
2095 return TokError("expected identifier after '.ifdef'");
2099 MCSymbol *Sym = getContext().LookupSymbol(Name);
2102 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2104 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2105 TheCondState.Ignore = !TheCondState.CondMet;
2111 /// ParseDirectiveElseIf
2112 /// ::= .elseif expression
2113 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2114 if (TheCondState.TheCond != AsmCond::IfCond &&
2115 TheCondState.TheCond != AsmCond::ElseIfCond)
2116 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2118 TheCondState.TheCond = AsmCond::ElseIfCond;
2120 bool LastIgnoreState = false;
2121 if (!TheCondStack.empty())
2122 LastIgnoreState = TheCondStack.back().Ignore;
2123 if (LastIgnoreState || TheCondState.CondMet) {
2124 TheCondState.Ignore = true;
2125 EatToEndOfStatement();
2129 if (ParseAbsoluteExpression(ExprValue))
2132 if (getLexer().isNot(AsmToken::EndOfStatement))
2133 return TokError("unexpected token in '.elseif' directive");
2136 TheCondState.CondMet = ExprValue;
2137 TheCondState.Ignore = !TheCondState.CondMet;
2143 /// ParseDirectiveElse
2145 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2146 if (getLexer().isNot(AsmToken::EndOfStatement))
2147 return TokError("unexpected token in '.else' directive");
2151 if (TheCondState.TheCond != AsmCond::IfCond &&
2152 TheCondState.TheCond != AsmCond::ElseIfCond)
2153 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2155 TheCondState.TheCond = AsmCond::ElseCond;
2156 bool LastIgnoreState = false;
2157 if (!TheCondStack.empty())
2158 LastIgnoreState = TheCondStack.back().Ignore;
2159 if (LastIgnoreState || TheCondState.CondMet)
2160 TheCondState.Ignore = true;
2162 TheCondState.Ignore = false;
2167 /// ParseDirectiveEndIf
2169 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2170 if (getLexer().isNot(AsmToken::EndOfStatement))
2171 return TokError("unexpected token in '.endif' directive");
2175 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2176 TheCondStack.empty())
2177 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2179 if (!TheCondStack.empty()) {
2180 TheCondState = TheCondStack.back();
2181 TheCondStack.pop_back();
2187 /// ParseDirectiveFile
2188 /// ::= .file [number] string
2189 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2190 // FIXME: I'm not sure what this is.
2191 int64_t FileNumber = -1;
2192 SMLoc FileNumberLoc = getLexer().getLoc();
2193 if (getLexer().is(AsmToken::Integer)) {
2194 FileNumber = getTok().getIntVal();
2198 return TokError("file number less than one");
2201 if (getLexer().isNot(AsmToken::String))
2202 return TokError("unexpected token in '.file' directive");
2204 StringRef Filename = getTok().getString();
2205 Filename = Filename.substr(1, Filename.size()-2);
2208 if (getLexer().isNot(AsmToken::EndOfStatement))
2209 return TokError("unexpected token in '.file' directive");
2211 if (FileNumber == -1)
2212 getStreamer().EmitFileDirective(Filename);
2214 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2215 Error(FileNumberLoc, "file number already allocated");
2221 /// ParseDirectiveLine
2222 /// ::= .line [number]
2223 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2224 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2225 if (getLexer().isNot(AsmToken::Integer))
2226 return TokError("unexpected token in '.line' directive");
2228 int64_t LineNumber = getTok().getIntVal();
2232 // FIXME: Do something with the .line.
2235 if (getLexer().isNot(AsmToken::EndOfStatement))
2236 return TokError("unexpected token in '.line' directive");
2242 /// ParseDirectiveLoc
2243 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2244 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2245 /// The first number is a file number, must have been previously assigned with
2246 /// a .file directive, the second number is the line number and optionally the
2247 /// third number is a column position (zero if not specified). The remaining
2248 /// optional items are .loc sub-directives.
2249 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2251 if (getLexer().isNot(AsmToken::Integer))
2252 return TokError("unexpected token in '.loc' directive");
2253 int64_t FileNumber = getTok().getIntVal();
2255 return TokError("file number less than one in '.loc' directive");
2256 if (!getContext().isValidDwarfFileNumber(FileNumber))
2257 return TokError("unassigned file number in '.loc' directive");
2260 int64_t LineNumber = 0;
2261 if (getLexer().is(AsmToken::Integer)) {
2262 LineNumber = getTok().getIntVal();
2264 return TokError("line number less than one in '.loc' directive");
2268 int64_t ColumnPos = 0;
2269 if (getLexer().is(AsmToken::Integer)) {
2270 ColumnPos = getTok().getIntVal();
2272 return TokError("column position less than zero in '.loc' directive");
2276 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2278 int64_t Discriminator = 0;
2279 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2281 if (getLexer().is(AsmToken::EndOfStatement))
2285 SMLoc Loc = getTok().getLoc();
2286 if (getParser().ParseIdentifier(Name))
2287 return TokError("unexpected token in '.loc' directive");
2289 if (Name == "basic_block")
2290 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2291 else if (Name == "prologue_end")
2292 Flags |= DWARF2_FLAG_PROLOGUE_END;
2293 else if (Name == "epilogue_begin")
2294 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2295 else if (Name == "is_stmt") {
2296 SMLoc Loc = getTok().getLoc();
2297 const MCExpr *Value;
2298 if (getParser().ParseExpression(Value))
2300 // The expression must be the constant 0 or 1.
2301 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2302 int Value = MCE->getValue();
2304 Flags &= ~DWARF2_FLAG_IS_STMT;
2305 else if (Value == 1)
2306 Flags |= DWARF2_FLAG_IS_STMT;
2308 return Error(Loc, "is_stmt value not 0 or 1");
2311 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2314 else if (Name == "isa") {
2315 SMLoc Loc = getTok().getLoc();
2316 const MCExpr *Value;
2317 if (getParser().ParseExpression(Value))
2319 // The expression must be a constant greater or equal to 0.
2320 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2321 int Value = MCE->getValue();
2323 return Error(Loc, "isa number less than zero");
2327 return Error(Loc, "isa number not a constant value");
2330 else if (Name == "discriminator") {
2331 if (getParser().ParseAbsoluteExpression(Discriminator))
2335 return Error(Loc, "unknown sub-directive in '.loc' directive");
2338 if (getLexer().is(AsmToken::EndOfStatement))
2343 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2344 Isa, Discriminator, StringRef());
2349 /// ParseDirectiveStabs
2350 /// ::= .stabs string, number, number, number
2351 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2352 SMLoc DirectiveLoc) {
2353 return TokError("unsupported directive '" + Directive + "'");
2356 /// ParseDirectiveCFISections
2357 /// ::= .cfi_sections section [, section]
2358 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2359 SMLoc DirectiveLoc) {
2364 if (getParser().ParseIdentifier(Name))
2365 return TokError("Expected an identifier");
2367 if (Name == ".eh_frame")
2369 else if (Name == ".debug_frame")
2372 if (getLexer().is(AsmToken::Comma)) {
2375 if (getParser().ParseIdentifier(Name))
2376 return TokError("Expected an identifier");
2378 if (Name == ".eh_frame")
2380 else if (Name == ".debug_frame")
2384 getStreamer().EmitCFISections(EH, Debug);
2389 /// ParseDirectiveCFIStartProc
2390 /// ::= .cfi_startproc
2391 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2392 SMLoc DirectiveLoc) {
2393 getStreamer().EmitCFIStartProc();
2397 /// ParseDirectiveCFIEndProc
2398 /// ::= .cfi_endproc
2399 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2400 getStreamer().EmitCFIEndProc();
2404 /// ParseRegisterOrRegisterNumber - parse register name or number.
2405 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2406 SMLoc DirectiveLoc) {
2409 if (getLexer().isNot(AsmToken::Integer)) {
2410 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2413 Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2415 return getParser().ParseAbsoluteExpression(Register);
2420 /// ParseDirectiveCFIDefCfa
2421 /// ::= .cfi_def_cfa register, offset
2422 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2423 SMLoc DirectiveLoc) {
2424 int64_t Register = 0;
2425 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2428 if (getLexer().isNot(AsmToken::Comma))
2429 return TokError("unexpected token in directive");
2433 if (getParser().ParseAbsoluteExpression(Offset))
2436 getStreamer().EmitCFIDefCfa(Register, Offset);
2440 /// ParseDirectiveCFIDefCfaOffset
2441 /// ::= .cfi_def_cfa_offset offset
2442 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2443 SMLoc DirectiveLoc) {
2445 if (getParser().ParseAbsoluteExpression(Offset))
2448 getStreamer().EmitCFIDefCfaOffset(Offset);
2452 /// ParseDirectiveCFIAdjustCfaOffset
2453 /// ::= .cfi_adjust_cfa_offset adjustment
2454 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2455 SMLoc DirectiveLoc) {
2456 int64_t Adjustment = 0;
2457 if (getParser().ParseAbsoluteExpression(Adjustment))
2460 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2464 /// ParseDirectiveCFIDefCfaRegister
2465 /// ::= .cfi_def_cfa_register register
2466 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2467 SMLoc DirectiveLoc) {
2468 int64_t Register = 0;
2469 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2472 getStreamer().EmitCFIDefCfaRegister(Register);
2476 /// ParseDirectiveCFIOffset
2477 /// ::= .cfi_offset register, offset
2478 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2479 int64_t Register = 0;
2482 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2485 if (getLexer().isNot(AsmToken::Comma))
2486 return TokError("unexpected token in directive");
2489 if (getParser().ParseAbsoluteExpression(Offset))
2492 getStreamer().EmitCFIOffset(Register, Offset);
2496 /// ParseDirectiveCFIRelOffset
2497 /// ::= .cfi_rel_offset register, offset
2498 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2499 SMLoc DirectiveLoc) {
2500 int64_t Register = 0;
2502 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2505 if (getLexer().isNot(AsmToken::Comma))
2506 return TokError("unexpected token in directive");
2510 if (getParser().ParseAbsoluteExpression(Offset))
2513 getStreamer().EmitCFIRelOffset(Register, Offset);
2517 static bool isValidEncoding(int64_t Encoding) {
2518 if (Encoding & ~0xff)
2521 if (Encoding == dwarf::DW_EH_PE_omit)
2524 const unsigned Format = Encoding & 0xf;
2525 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2526 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2527 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2528 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2531 const unsigned Application = Encoding & 0x70;
2532 if (Application != dwarf::DW_EH_PE_absptr &&
2533 Application != dwarf::DW_EH_PE_pcrel)
2539 /// ParseDirectiveCFIPersonalityOrLsda
2540 /// ::= .cfi_personality encoding, [symbol_name]
2541 /// ::= .cfi_lsda encoding, [symbol_name]
2542 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2543 SMLoc DirectiveLoc) {
2544 int64_t Encoding = 0;
2545 if (getParser().ParseAbsoluteExpression(Encoding))
2547 if (Encoding == dwarf::DW_EH_PE_omit)
2550 if (!isValidEncoding(Encoding))
2551 return TokError("unsupported encoding.");
2553 if (getLexer().isNot(AsmToken::Comma))
2554 return TokError("unexpected token in directive");
2558 if (getParser().ParseIdentifier(Name))
2559 return TokError("expected identifier in directive");
2561 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2563 if (IDVal == ".cfi_personality")
2564 getStreamer().EmitCFIPersonality(Sym, Encoding);
2566 assert(IDVal == ".cfi_lsda");
2567 getStreamer().EmitCFILsda(Sym, Encoding);
2572 /// ParseDirectiveCFIRememberState
2573 /// ::= .cfi_remember_state
2574 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2575 SMLoc DirectiveLoc) {
2576 getStreamer().EmitCFIRememberState();
2580 /// ParseDirectiveCFIRestoreState
2581 /// ::= .cfi_remember_state
2582 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2583 SMLoc DirectiveLoc) {
2584 getStreamer().EmitCFIRestoreState();
2588 /// ParseDirectiveCFISameValue
2589 /// ::= .cfi_same_value register
2590 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2591 SMLoc DirectiveLoc) {
2592 int64_t Register = 0;
2594 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2597 getStreamer().EmitCFISameValue(Register);
2602 /// ParseDirectiveMacrosOnOff
2605 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2606 SMLoc DirectiveLoc) {
2607 if (getLexer().isNot(AsmToken::EndOfStatement))
2608 return Error(getLexer().getLoc(),
2609 "unexpected token in '" + Directive + "' directive");
2611 getParser().MacrosEnabled = Directive == ".macros_on";
2616 /// ParseDirectiveMacro
2617 /// ::= .macro name [parameters]
2618 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2619 SMLoc DirectiveLoc) {
2621 if (getParser().ParseIdentifier(Name))
2622 return TokError("expected identifier in directive");
2624 std::vector<StringRef> Parameters;
2625 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2627 StringRef Parameter;
2628 if (getParser().ParseIdentifier(Parameter))
2629 return TokError("expected identifier in directive");
2630 Parameters.push_back(Parameter);
2632 if (getLexer().isNot(AsmToken::Comma))
2638 if (getLexer().isNot(AsmToken::EndOfStatement))
2639 return TokError("unexpected token in '.macro' directive");
2641 // Eat the end of statement.
2644 AsmToken EndToken, StartToken = getTok();
2646 // Lex the macro definition.
2648 // Check whether we have reached the end of the file.
2649 if (getLexer().is(AsmToken::Eof))
2650 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2652 // Otherwise, check whether we have reach the .endmacro.
2653 if (getLexer().is(AsmToken::Identifier) &&
2654 (getTok().getIdentifier() == ".endm" ||
2655 getTok().getIdentifier() == ".endmacro")) {
2656 EndToken = getTok();
2658 if (getLexer().isNot(AsmToken::EndOfStatement))
2659 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2664 // Otherwise, scan til the end of the statement.
2665 getParser().EatToEndOfStatement();
2668 if (getParser().MacroMap.lookup(Name)) {
2669 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2672 const char *BodyStart = StartToken.getLoc().getPointer();
2673 const char *BodyEnd = EndToken.getLoc().getPointer();
2674 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2675 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2679 /// ParseDirectiveEndMacro
2682 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2683 SMLoc DirectiveLoc) {
2684 if (getLexer().isNot(AsmToken::EndOfStatement))
2685 return TokError("unexpected token in '" + Directive + "' directive");
2687 // If we are inside a macro instantiation, terminate the current
2689 if (!getParser().ActiveMacros.empty()) {
2690 getParser().HandleMacroExit();
2694 // Otherwise, this .endmacro is a stray entry in the file; well formed
2695 // .endmacro directives are handled during the macro definition parsing.
2696 return TokError("unexpected '" + Directive + "' in file, "
2697 "no current macro definition");
2700 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2701 getParser().CheckForValidSection();
2703 const MCExpr *Value;
2705 if (getParser().ParseExpression(Value))
2708 if (getLexer().isNot(AsmToken::EndOfStatement))
2709 return TokError("unexpected token in directive");
2711 if (DirName[1] == 's')
2712 getStreamer().EmitSLEB128Value(Value);
2714 getStreamer().EmitULEB128Value(Value);
2720 /// \brief Create an MCAsmParser instance.
2721 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2722 MCContext &C, MCStreamer &Out,
2723 const MCAsmInfo &MAI) {
2724 return new AsmParser(T, SM, C, Out, MAI);