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/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCParser/AsmCond.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCTargetAsmParser.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/raw_ostream.h"
42 FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
47 /// \brief Helper class for tracking macro definitions.
51 std::vector<StringRef> Parameters;
54 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
58 /// \brief Helper class for storing information about an active macro
60 struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
70 /// The location where parsing should resume upon instantiation completion.
74 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
78 /// \brief The concrete assembly parser instance.
79 class AsmParser : public MCAsmParser {
80 friend class GenericAsmParser;
82 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
90 MCAsmParserExtension *GenericParser;
91 MCAsmParserExtension *PlatformParser;
93 /// This is the current buffer index we're lexing from as managed by the
98 std::vector<AsmCond> TheCondStack;
100 /// DirectiveMap - This is a table handlers for directives. Each handler is
101 /// invoked after the directive identifier is read and is responsible for
102 /// parsing and validating the rest of the directive. The handler is passed
103 /// in the directive name and the location of the directive keyword.
104 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
106 /// MacroMap - Map of currently defined macros.
107 StringMap<Macro*> MacroMap;
109 /// ActiveMacros - Stack of active macro instantiations.
110 std::vector<MacroInstantiation*> ActiveMacros;
112 /// Boolean tracking whether macro substitution is enabled.
113 unsigned MacrosEnabled : 1;
115 /// Flag tracking whether any errors have been encountered.
116 unsigned HadError : 1;
119 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
120 const MCAsmInfo &MAI);
123 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
125 void AddDirectiveHandler(MCAsmParserExtension *Object,
127 DirectiveHandler Handler) {
128 DirectiveMap[Directive] = std::make_pair(Object, Handler);
132 /// @name MCAsmParser Interface
135 virtual SourceMgr &getSourceManager() { return SrcMgr; }
136 virtual MCAsmLexer &getLexer() { return Lexer; }
137 virtual MCContext &getContext() { return Ctx; }
138 virtual MCStreamer &getStreamer() { return Out; }
140 virtual bool Warning(SMLoc L, const Twine &Msg);
141 virtual bool Error(SMLoc L, const Twine &Msg);
143 const AsmToken &Lex();
145 bool ParseExpression(const MCExpr *&Res);
146 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
147 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
148 virtual bool ParseAbsoluteExpression(int64_t &Res);
153 void CheckForValidSection();
155 bool ParseStatement();
157 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
158 bool expandMacro(SmallString<256> &Buf, StringRef Body,
159 const std::vector<StringRef> &Parameters,
160 const std::vector<std::vector<AsmToken> > &A,
162 void HandleMacroExit();
164 void PrintMacroInstantiations();
165 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type,
166 bool ShowLine = true) const {
167 SrcMgr.PrintMessage(Loc, Msg, Type, ShowLine);
170 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
171 bool EnterIncludeFile(const std::string &Filename);
173 /// \brief Reset the current lexer position to that given by \arg Loc. The
174 /// current token is not set; clients should ensure Lex() is called
176 void JumpToLoc(SMLoc Loc);
178 void EatToEndOfStatement();
180 /// \brief Parse up to the end of statement and a return the contents from the
181 /// current token until the end of the statement; the current token on exit
182 /// will be either the EndOfStatement or EOF.
183 StringRef ParseStringToEndOfStatement();
185 bool ParseAssignment(StringRef Name, bool allow_redef);
187 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
188 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
189 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
190 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
192 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
193 /// and set \arg Res to the identifier contents.
194 bool ParseIdentifier(StringRef &Res);
196 // Directive Parsing.
198 // ".ascii", ".asciiz", ".string"
199 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
200 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
201 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
202 bool ParseDirectiveFill(); // ".fill"
203 bool ParseDirectiveSpace(); // ".space"
204 bool ParseDirectiveZero(); // ".zero"
205 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
206 bool ParseDirectiveOrg(); // ".org"
207 // ".align{,32}", ".p2align{,w,l}"
208 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
210 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
211 /// accepts a single symbol (which should be a label or an external).
212 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
214 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
216 bool ParseDirectiveAbort(); // ".abort"
217 bool ParseDirectiveInclude(); // ".include"
219 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
220 // ".ifdef" or ".ifndef", depending on expect_defined
221 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
222 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
223 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
224 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
226 /// ParseEscapedString - Parse the current token as a string which may include
227 /// escaped characters and return the string contents.
228 bool ParseEscapedString(std::string &Data);
230 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
231 MCSymbolRefExpr::VariantKind Variant);
234 /// \brief Generic implementations of directive handling, etc. which is shared
235 /// (or the default, at least) for all assembler parser.
236 class GenericAsmParser : public MCAsmParserExtension {
237 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
238 void AddDirectiveHandler(StringRef Directive) {
239 getParser().AddDirectiveHandler(this, Directive,
240 HandleDirective<GenericAsmParser, Handler>);
243 GenericAsmParser() {}
245 AsmParser &getParser() {
246 return (AsmParser&) this->MCAsmParserExtension::getParser();
249 virtual void Initialize(MCAsmParser &Parser) {
250 // Call the base implementation.
251 this->MCAsmParserExtension::Initialize(Parser);
253 // Debugging directives.
254 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
255 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
256 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
257 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
260 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
262 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
264 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
266 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
268 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
269 ".cfi_def_cfa_offset");
270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
271 ".cfi_adjust_cfa_offset");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
273 ".cfi_def_cfa_register");
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
279 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
281 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
283 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
285 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
287 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
294 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
295 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
296 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
298 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
299 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
302 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
304 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
305 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
306 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
307 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
308 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
309 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
310 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
311 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
312 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
313 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
314 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
315 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
316 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
317 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
318 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
319 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
320 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
322 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
323 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
324 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
326 bool ParseDirectiveLEB128(StringRef, SMLoc);
333 extern MCAsmParserExtension *createDarwinAsmParser();
334 extern MCAsmParserExtension *createELFAsmParser();
335 extern MCAsmParserExtension *createCOFFAsmParser();
339 enum { DEFAULT_ADDRSPACE = 0 };
341 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
342 MCStreamer &_Out, const MCAsmInfo &_MAI)
343 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
344 GenericParser(new GenericAsmParser), PlatformParser(0),
345 CurBuffer(0), MacrosEnabled(true) {
346 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
348 // Initialize the generic parser.
349 GenericParser->Initialize(*this);
351 // Initialize the platform / file format parser.
353 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
355 if (_MAI.hasMicrosoftFastStdCallMangling()) {
356 PlatformParser = createCOFFAsmParser();
357 PlatformParser->Initialize(*this);
358 } else if (_MAI.hasSubsectionsViaSymbols()) {
359 PlatformParser = createDarwinAsmParser();
360 PlatformParser->Initialize(*this);
362 PlatformParser = createELFAsmParser();
363 PlatformParser->Initialize(*this);
367 AsmParser::~AsmParser() {
368 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
370 // Destroy any macros.
371 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
372 ie = MacroMap.end(); it != ie; ++it)
373 delete it->getValue();
375 delete PlatformParser;
376 delete GenericParser;
379 void AsmParser::PrintMacroInstantiations() {
380 // Print the active macro instantiation stack.
381 for (std::vector<MacroInstantiation*>::const_reverse_iterator
382 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
383 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
387 bool AsmParser::Warning(SMLoc L, const Twine &Msg) {
388 if (FatalAssemblerWarnings)
389 return Error(L, Msg);
390 PrintMessage(L, Msg, "warning");
391 PrintMacroInstantiations();
395 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
397 PrintMessage(L, Msg, "error");
398 PrintMacroInstantiations();
402 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
403 std::string IncludedFile;
404 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
410 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
415 void AsmParser::JumpToLoc(SMLoc Loc) {
416 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
417 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
420 const AsmToken &AsmParser::Lex() {
421 const AsmToken *tok = &Lexer.Lex();
423 if (tok->is(AsmToken::Eof)) {
424 // If this is the end of an included file, pop the parent file off the
426 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
427 if (ParentIncludeLoc != SMLoc()) {
428 JumpToLoc(ParentIncludeLoc);
433 if (tok->is(AsmToken::Error))
434 Error(Lexer.getErrLoc(), Lexer.getErr());
439 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
440 // Create the initial section, if requested.
441 if (!NoInitialTextSection)
448 AsmCond StartingCondState = TheCondState;
450 // While we have input, parse each statement.
451 while (Lexer.isNot(AsmToken::Eof)) {
452 if (!ParseStatement()) continue;
454 // We had an error, validate that one was emitted and recover by skipping to
456 assert(HadError && "Parse statement returned an error, but none emitted!");
457 EatToEndOfStatement();
460 if (TheCondState.TheCond != StartingCondState.TheCond ||
461 TheCondState.Ignore != StartingCondState.Ignore)
462 return TokError("unmatched .ifs or .elses");
464 // Check to see there are no empty DwarfFile slots.
465 const std::vector<MCDwarfFile *> &MCDwarfFiles =
466 getContext().getMCDwarfFiles();
467 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
468 if (!MCDwarfFiles[i])
469 TokError("unassigned file number: " + Twine(i) + " for .file directives");
472 // Check to see that all assembler local symbols were actually defined.
473 // Targets that don't do subsections via symbols may not want this, though,
474 // so conservatively exclude them. Only do this if we're finalizing, though,
475 // as otherwise we won't necessarilly have seen everything yet.
476 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
477 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
478 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
481 MCSymbol *Sym = i->getValue();
482 // Variable symbols may not be marked as defined, so check those
483 // explicitly. If we know it's a variable, we have a definition for
484 // the purposes of this check.
485 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
486 // FIXME: We would really like to refer back to where the symbol was
487 // first referenced for a source location. We need to add something
488 // to track that. Currently, we just point to the end of the file.
489 PrintMessage(getLexer().getLoc(), "assembler local symbol '" +
490 Sym->getName() + "' not defined", "error", false);
495 // Finalize the output stream if there are no errors and if the client wants
497 if (!HadError && !NoFinalize)
503 void AsmParser::CheckForValidSection() {
504 if (!getStreamer().getCurrentSection()) {
505 TokError("expected section directive before assembly directive");
506 Out.SwitchSection(Ctx.getMachOSection(
508 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
509 0, SectionKind::getText()));
513 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
514 void AsmParser::EatToEndOfStatement() {
515 while (Lexer.isNot(AsmToken::EndOfStatement) &&
516 Lexer.isNot(AsmToken::Eof))
520 if (Lexer.is(AsmToken::EndOfStatement))
524 StringRef AsmParser::ParseStringToEndOfStatement() {
525 const char *Start = getTok().getLoc().getPointer();
527 while (Lexer.isNot(AsmToken::EndOfStatement) &&
528 Lexer.isNot(AsmToken::Eof))
531 const char *End = getTok().getLoc().getPointer();
532 return StringRef(Start, End - Start);
535 /// ParseParenExpr - Parse a paren expression and return it.
536 /// NOTE: This assumes the leading '(' has already been consumed.
538 /// parenexpr ::= expr)
540 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
541 if (ParseExpression(Res)) return true;
542 if (Lexer.isNot(AsmToken::RParen))
543 return TokError("expected ')' in parentheses expression");
544 EndLoc = Lexer.getLoc();
549 /// ParseBracketExpr - Parse a bracket expression and return it.
550 /// NOTE: This assumes the leading '[' has already been consumed.
552 /// bracketexpr ::= expr]
554 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
555 if (ParseExpression(Res)) return true;
556 if (Lexer.isNot(AsmToken::RBrac))
557 return TokError("expected ']' in brackets expression");
558 EndLoc = Lexer.getLoc();
563 /// ParsePrimaryExpr - Parse a primary expression and return it.
564 /// primaryexpr ::= (parenexpr
565 /// primaryexpr ::= symbol
566 /// primaryexpr ::= number
567 /// primaryexpr ::= '.'
568 /// primaryexpr ::= ~,+,- primaryexpr
569 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
570 switch (Lexer.getKind()) {
572 return TokError("unknown token in expression");
573 // If we have an error assume that we've already handled it.
574 case AsmToken::Error:
576 case AsmToken::Exclaim:
577 Lex(); // Eat the operator.
578 if (ParsePrimaryExpr(Res, EndLoc))
580 Res = MCUnaryExpr::CreateLNot(Res, getContext());
582 case AsmToken::Dollar:
583 case AsmToken::String:
584 case AsmToken::Identifier: {
585 EndLoc = Lexer.getLoc();
587 StringRef Identifier;
588 if (ParseIdentifier(Identifier))
591 // This is a symbol reference.
592 std::pair<StringRef, StringRef> Split = Identifier.split('@');
593 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
595 // Lookup the symbol variant if used.
596 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
597 if (Split.first.size() != Identifier.size()) {
598 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
599 if (Variant == MCSymbolRefExpr::VK_Invalid) {
600 Variant = MCSymbolRefExpr::VK_None;
601 return TokError("invalid variant '" + Split.second + "'");
605 // If this is an absolute variable reference, substitute it now to preserve
606 // semantics in the face of reassignment.
607 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
609 return Error(EndLoc, "unexpected modifier on variable reference");
611 Res = Sym->getVariableValue();
615 // Otherwise create a symbol ref.
616 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
619 case AsmToken::Integer: {
620 SMLoc Loc = getTok().getLoc();
621 int64_t IntVal = getTok().getIntVal();
622 Res = MCConstantExpr::Create(IntVal, getContext());
623 EndLoc = Lexer.getLoc();
625 // Look for 'b' or 'f' following an Integer as a directional label
626 if (Lexer.getKind() == AsmToken::Identifier) {
627 StringRef IDVal = getTok().getString();
628 if (IDVal == "f" || IDVal == "b"){
629 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
630 IDVal == "f" ? 1 : 0);
631 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
633 if(IDVal == "b" && Sym->isUndefined())
634 return Error(Loc, "invalid reference to undefined symbol");
635 EndLoc = Lexer.getLoc();
636 Lex(); // Eat identifier.
641 case AsmToken::Real: {
642 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
643 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
644 Res = MCConstantExpr::Create(IntVal, getContext());
648 case AsmToken::Dot: {
649 // This is a '.' reference, which references the current PC. Emit a
650 // temporary label to the streamer and refer to it.
651 MCSymbol *Sym = Ctx.CreateTempSymbol();
653 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
654 EndLoc = Lexer.getLoc();
655 Lex(); // Eat identifier.
658 case AsmToken::LParen:
659 Lex(); // Eat the '('.
660 return ParseParenExpr(Res, EndLoc);
661 case AsmToken::LBrac:
662 if (!PlatformParser->HasBracketExpressions())
663 return TokError("brackets expression not supported on this target");
664 Lex(); // Eat the '['.
665 return ParseBracketExpr(Res, EndLoc);
666 case AsmToken::Minus:
667 Lex(); // Eat the operator.
668 if (ParsePrimaryExpr(Res, EndLoc))
670 Res = MCUnaryExpr::CreateMinus(Res, getContext());
673 Lex(); // Eat the operator.
674 if (ParsePrimaryExpr(Res, EndLoc))
676 Res = MCUnaryExpr::CreatePlus(Res, getContext());
678 case AsmToken::Tilde:
679 Lex(); // Eat the operator.
680 if (ParsePrimaryExpr(Res, EndLoc))
682 Res = MCUnaryExpr::CreateNot(Res, getContext());
687 bool AsmParser::ParseExpression(const MCExpr *&Res) {
689 return ParseExpression(Res, EndLoc);
693 AsmParser::ApplyModifierToExpr(const MCExpr *E,
694 MCSymbolRefExpr::VariantKind Variant) {
695 // Recurse over the given expression, rebuilding it to apply the given variant
696 // if there is exactly one symbol.
697 switch (E->getKind()) {
699 case MCExpr::Constant:
702 case MCExpr::SymbolRef: {
703 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
705 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
706 TokError("invalid variant on expression '" +
707 getTok().getIdentifier() + "' (already modified)");
711 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
714 case MCExpr::Unary: {
715 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
716 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
719 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
722 case MCExpr::Binary: {
723 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
724 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
725 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
730 if (!LHS) LHS = BE->getLHS();
731 if (!RHS) RHS = BE->getRHS();
733 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
737 assert(0 && "Invalid expression kind!");
741 /// ParseExpression - Parse an expression and return it.
743 /// expr ::= expr +,- expr -> lowest.
744 /// expr ::= expr |,^,&,! expr -> middle.
745 /// expr ::= expr *,/,%,<<,>> expr -> highest.
746 /// expr ::= primaryexpr
748 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
749 // Parse the expression.
751 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
754 // As a special case, we support 'a op b @ modifier' by rewriting the
755 // expression to include the modifier. This is inefficient, but in general we
756 // expect users to use 'a@modifier op b'.
757 if (Lexer.getKind() == AsmToken::At) {
760 if (Lexer.isNot(AsmToken::Identifier))
761 return TokError("unexpected symbol modifier following '@'");
763 MCSymbolRefExpr::VariantKind Variant =
764 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
765 if (Variant == MCSymbolRefExpr::VK_Invalid)
766 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
768 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
770 return TokError("invalid modifier '" + getTok().getIdentifier() +
771 "' (no symbols present)");
779 // Try to constant fold it up front, if possible.
781 if (Res->EvaluateAsAbsolute(Value))
782 Res = MCConstantExpr::Create(Value, getContext());
787 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
789 return ParseParenExpr(Res, EndLoc) ||
790 ParseBinOpRHS(1, Res, EndLoc);
793 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
796 SMLoc StartLoc = Lexer.getLoc();
797 if (ParseExpression(Expr))
800 if (!Expr->EvaluateAsAbsolute(Res))
801 return Error(StartLoc, "expected absolute expression");
806 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
807 MCBinaryExpr::Opcode &Kind) {
810 return 0; // not a binop.
812 // Lowest Precedence: &&, ||, @
813 case AsmToken::AmpAmp:
814 Kind = MCBinaryExpr::LAnd;
816 case AsmToken::PipePipe:
817 Kind = MCBinaryExpr::LOr;
821 // Low Precedence: |, &, ^
823 // FIXME: gas seems to support '!' as an infix operator?
825 Kind = MCBinaryExpr::Or;
827 case AsmToken::Caret:
828 Kind = MCBinaryExpr::Xor;
831 Kind = MCBinaryExpr::And;
834 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
835 case AsmToken::EqualEqual:
836 Kind = MCBinaryExpr::EQ;
838 case AsmToken::ExclaimEqual:
839 case AsmToken::LessGreater:
840 Kind = MCBinaryExpr::NE;
843 Kind = MCBinaryExpr::LT;
845 case AsmToken::LessEqual:
846 Kind = MCBinaryExpr::LTE;
848 case AsmToken::Greater:
849 Kind = MCBinaryExpr::GT;
851 case AsmToken::GreaterEqual:
852 Kind = MCBinaryExpr::GTE;
855 // High Intermediate Precedence: +, -
857 Kind = MCBinaryExpr::Add;
859 case AsmToken::Minus:
860 Kind = MCBinaryExpr::Sub;
863 // Highest Precedence: *, /, %, <<, >>
865 Kind = MCBinaryExpr::Mul;
867 case AsmToken::Slash:
868 Kind = MCBinaryExpr::Div;
870 case AsmToken::Percent:
871 Kind = MCBinaryExpr::Mod;
873 case AsmToken::LessLess:
874 Kind = MCBinaryExpr::Shl;
876 case AsmToken::GreaterGreater:
877 Kind = MCBinaryExpr::Shr;
883 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
884 /// Res contains the LHS of the expression on input.
885 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
888 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
889 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
891 // If the next token is lower precedence than we are allowed to eat, return
892 // successfully with what we ate already.
893 if (TokPrec < Precedence)
898 // Eat the next primary expression.
900 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
902 // If BinOp binds less tightly with RHS than the operator after RHS, let
903 // the pending operator take RHS as its LHS.
904 MCBinaryExpr::Opcode Dummy;
905 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
906 if (TokPrec < NextTokPrec) {
907 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
910 // Merge LHS and RHS according to operator.
911 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
919 /// ::= EndOfStatement
920 /// ::= Label* Directive ...Operands... EndOfStatement
921 /// ::= Label* Identifier OperandList* EndOfStatement
922 bool AsmParser::ParseStatement() {
923 if (Lexer.is(AsmToken::EndOfStatement)) {
929 // Statements always start with an identifier or are a full line comment.
930 AsmToken ID = getTok();
931 SMLoc IDLoc = ID.getLoc();
933 int64_t LocalLabelVal = -1;
934 // A full line comment is a '#' as the first token.
935 if (Lexer.is(AsmToken::Hash)) {
936 EatToEndOfStatement();
940 // Allow an integer followed by a ':' as a directional local label.
941 if (Lexer.is(AsmToken::Integer)) {
942 LocalLabelVal = getTok().getIntVal();
943 if (LocalLabelVal < 0) {
944 if (!TheCondState.Ignore)
945 return TokError("unexpected token at start of statement");
949 IDVal = getTok().getString();
950 Lex(); // Consume the integer token to be used as an identifier token.
951 if (Lexer.getKind() != AsmToken::Colon) {
952 if (!TheCondState.Ignore)
953 return TokError("unexpected token at start of statement");
957 } else if (Lexer.is(AsmToken::Dot)) {
958 // Treat '.' as a valid identifier in this context.
962 } else if (ParseIdentifier(IDVal)) {
963 if (!TheCondState.Ignore)
964 return TokError("unexpected token at start of statement");
969 // Handle conditional assembly here before checking for skipping. We
970 // have to do this so that .endif isn't skipped in a ".if 0" block for
973 return ParseDirectiveIf(IDLoc);
974 if (IDVal == ".ifdef")
975 return ParseDirectiveIfdef(IDLoc, true);
976 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
977 return ParseDirectiveIfdef(IDLoc, false);
978 if (IDVal == ".elseif")
979 return ParseDirectiveElseIf(IDLoc);
980 if (IDVal == ".else")
981 return ParseDirectiveElse(IDLoc);
982 if (IDVal == ".endif")
983 return ParseDirectiveEndIf(IDLoc);
985 // If we are in a ".if 0" block, ignore this statement.
986 if (TheCondState.Ignore) {
987 EatToEndOfStatement();
991 // FIXME: Recurse on local labels?
993 // See what kind of statement we have.
994 switch (Lexer.getKind()) {
995 case AsmToken::Colon: {
996 CheckForValidSection();
998 // identifier ':' -> Label.
1001 // Diagnose attempt to use '.' as a label.
1003 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1005 // Diagnose attempt to use a variable as a label.
1007 // FIXME: Diagnostics. Note the location of the definition as a label.
1008 // FIXME: This doesn't diagnose assignment to a symbol which has been
1009 // implicitly marked as external.
1011 if (LocalLabelVal == -1)
1012 Sym = getContext().GetOrCreateSymbol(IDVal);
1014 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1015 if (!Sym->isUndefined() || Sym->isVariable())
1016 return Error(IDLoc, "invalid symbol redefinition");
1021 // Consume any end of statement token, if present, to avoid spurious
1022 // AddBlankLine calls().
1023 if (Lexer.is(AsmToken::EndOfStatement)) {
1025 if (Lexer.is(AsmToken::Eof))
1029 return ParseStatement();
1032 case AsmToken::Equal:
1033 // identifier '=' ... -> assignment statement
1036 return ParseAssignment(IDVal, true);
1038 default: // Normal instruction or directive.
1042 // If macros are enabled, check to see if this is a macro instantiation.
1044 if (const Macro *M = MacroMap.lookup(IDVal))
1045 return HandleMacroEntry(IDVal, IDLoc, M);
1047 // Otherwise, we have a normal instruction or directive.
1048 if (IDVal[0] == '.' && IDVal != ".") {
1049 // Assembler features
1050 if (IDVal == ".set" || IDVal == ".equ")
1051 return ParseDirectiveSet(IDVal, true);
1052 if (IDVal == ".equiv")
1053 return ParseDirectiveSet(IDVal, false);
1057 if (IDVal == ".ascii")
1058 return ParseDirectiveAscii(IDVal, false);
1059 if (IDVal == ".asciz" || IDVal == ".string")
1060 return ParseDirectiveAscii(IDVal, true);
1062 if (IDVal == ".byte")
1063 return ParseDirectiveValue(1);
1064 if (IDVal == ".short")
1065 return ParseDirectiveValue(2);
1066 if (IDVal == ".value")
1067 return ParseDirectiveValue(2);
1068 if (IDVal == ".2byte")
1069 return ParseDirectiveValue(2);
1070 if (IDVal == ".long")
1071 return ParseDirectiveValue(4);
1072 if (IDVal == ".int")
1073 return ParseDirectiveValue(4);
1074 if (IDVal == ".4byte")
1075 return ParseDirectiveValue(4);
1076 if (IDVal == ".quad")
1077 return ParseDirectiveValue(8);
1078 if (IDVal == ".8byte")
1079 return ParseDirectiveValue(8);
1080 if (IDVal == ".single" || IDVal == ".float")
1081 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1082 if (IDVal == ".double")
1083 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1085 if (IDVal == ".align") {
1086 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1087 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1089 if (IDVal == ".align32") {
1090 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1091 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1093 if (IDVal == ".balign")
1094 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1095 if (IDVal == ".balignw")
1096 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1097 if (IDVal == ".balignl")
1098 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1099 if (IDVal == ".p2align")
1100 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1101 if (IDVal == ".p2alignw")
1102 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1103 if (IDVal == ".p2alignl")
1104 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1106 if (IDVal == ".org")
1107 return ParseDirectiveOrg();
1109 if (IDVal == ".fill")
1110 return ParseDirectiveFill();
1111 if (IDVal == ".space" || IDVal == ".skip")
1112 return ParseDirectiveSpace();
1113 if (IDVal == ".zero")
1114 return ParseDirectiveZero();
1116 // Symbol attribute directives
1118 if (IDVal == ".globl" || IDVal == ".global")
1119 return ParseDirectiveSymbolAttribute(MCSA_Global);
1120 if (IDVal == ".indirect_symbol")
1121 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1122 if (IDVal == ".lazy_reference")
1123 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1124 if (IDVal == ".no_dead_strip")
1125 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1126 if (IDVal == ".symbol_resolver")
1127 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1128 if (IDVal == ".private_extern")
1129 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1130 if (IDVal == ".reference")
1131 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1132 if (IDVal == ".weak_definition")
1133 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1134 if (IDVal == ".weak_reference")
1135 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1136 if (IDVal == ".weak_def_can_be_hidden")
1137 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1139 if (IDVal == ".comm" || IDVal == ".common")
1140 return ParseDirectiveComm(/*IsLocal=*/false);
1141 if (IDVal == ".lcomm")
1142 return ParseDirectiveComm(/*IsLocal=*/true);
1144 if (IDVal == ".abort")
1145 return ParseDirectiveAbort();
1146 if (IDVal == ".include")
1147 return ParseDirectiveInclude();
1149 if (IDVal == ".code16")
1150 return TokError(Twine(IDVal) + " not supported yet");
1152 // Look up the handler in the handler table.
1153 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1154 DirectiveMap.lookup(IDVal);
1156 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1158 // Target hook for parsing target specific directives.
1159 if (!getTargetParser().ParseDirective(ID))
1162 bool retval = Warning(IDLoc, "ignoring directive for now");
1163 EatToEndOfStatement();
1167 CheckForValidSection();
1169 // Canonicalize the opcode to lower case.
1170 SmallString<128> Opcode;
1171 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1172 Opcode.push_back(tolower(IDVal[i]));
1174 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1175 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1178 // Dump the parsed representation, if requested.
1179 if (getShowParsedOperands()) {
1180 SmallString<256> Str;
1181 raw_svector_ostream OS(Str);
1182 OS << "parsed instruction: [";
1183 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1186 ParsedOperands[i]->print(OS);
1190 PrintMessage(IDLoc, OS.str(), "note");
1193 // If parsing succeeded, match the instruction.
1195 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1198 // Free any parsed operands.
1199 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1200 delete ParsedOperands[i];
1202 // Don't skip the rest of the line, the instruction parser is responsible for
1207 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1208 const std::vector<StringRef> &Parameters,
1209 const std::vector<std::vector<AsmToken> > &A,
1211 raw_svector_ostream OS(Buf);
1212 unsigned NParameters = Parameters.size();
1213 if (NParameters != 0 && NParameters != A.size())
1214 return Error(L, "Wrong number of arguments");
1216 while (!Body.empty()) {
1217 // Scan for the next substitution.
1218 std::size_t End = Body.size(), Pos = 0;
1219 for (; Pos != End; ++Pos) {
1220 // Check for a substitution or escape.
1222 // This macro has no parameters, look for $0, $1, etc.
1223 if (Body[Pos] != '$' || Pos + 1 == End)
1226 char Next = Body[Pos + 1];
1227 if (Next == '$' || Next == 'n' || isdigit(Next))
1230 // This macro has parameters, look for \foo, \bar, etc.
1231 if (Body[Pos] == '\\' && Pos + 1 != End)
1237 OS << Body.slice(0, Pos);
1239 // Check if we reached the end.
1244 switch (Body[Pos+1]) {
1250 // $n => number of arguments
1255 // $[0-9] => argument
1257 // Missing arguments are ignored.
1258 unsigned Index = Body[Pos+1] - '0';
1259 if (Index >= A.size())
1262 // Otherwise substitute with the token values, with spaces eliminated.
1263 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1264 ie = A[Index].end(); it != ie; ++it)
1265 OS << it->getString();
1271 unsigned I = Pos + 1;
1272 while (isalnum(Body[I]) && I + 1 != End)
1275 const char *Begin = Body.data() + Pos +1;
1276 StringRef Argument(Begin, I - (Pos +1));
1278 for (; Index < NParameters; ++Index)
1279 if (Parameters[Index] == Argument)
1282 // FIXME: We should error at the macro definition.
1283 if (Index == NParameters)
1284 return Error(L, "Parameter not found");
1286 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1287 ie = A[Index].end(); it != ie; ++it)
1288 OS << it->getString();
1290 Pos += 1 + Argument.size();
1292 // Update the scan point.
1293 Body = Body.substr(Pos);
1296 // We include the .endmacro in the buffer as our queue to exit the macro
1298 OS << ".endmacro\n";
1302 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1304 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1308 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1310 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1311 // this, although we should protect against infinite loops.
1312 if (ActiveMacros.size() == 20)
1313 return TokError("macros cannot be nested more than 20 levels deep");
1315 // Parse the macro instantiation arguments.
1316 std::vector<std::vector<AsmToken> > MacroArguments;
1317 MacroArguments.push_back(std::vector<AsmToken>());
1318 unsigned ParenLevel = 0;
1320 if (Lexer.is(AsmToken::Eof))
1321 return TokError("unexpected token in macro instantiation");
1322 if (Lexer.is(AsmToken::EndOfStatement))
1325 // If we aren't inside parentheses and this is a comma, start a new token
1327 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1328 MacroArguments.push_back(std::vector<AsmToken>());
1330 // Adjust the current parentheses level.
1331 if (Lexer.is(AsmToken::LParen))
1333 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1336 // Append the token to the current argument list.
1337 MacroArguments.back().push_back(getTok());
1342 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1343 // to hold the macro body with substitutions.
1344 SmallString<256> Buf;
1345 StringRef Body = M->Body;
1347 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1350 MemoryBuffer *Instantiation =
1351 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1353 // Create the macro instantiation object and add to the current macro
1354 // instantiation stack.
1355 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1358 ActiveMacros.push_back(MI);
1360 // Jump to the macro instantiation and prime the lexer.
1361 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1362 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1368 void AsmParser::HandleMacroExit() {
1369 // Jump to the EndOfStatement we should return to, and consume it.
1370 JumpToLoc(ActiveMacros.back()->ExitLoc);
1373 // Pop the instantiation entry.
1374 delete ActiveMacros.back();
1375 ActiveMacros.pop_back();
1378 static void MarkUsed(const MCExpr *Value) {
1379 switch (Value->getKind()) {
1380 case MCExpr::Binary:
1381 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1382 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1384 case MCExpr::Target:
1385 case MCExpr::Constant:
1387 case MCExpr::SymbolRef: {
1388 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1392 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1397 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1398 // FIXME: Use better location, we should use proper tokens.
1399 SMLoc EqualLoc = Lexer.getLoc();
1401 const MCExpr *Value;
1402 if (ParseExpression(Value))
1407 if (Lexer.isNot(AsmToken::EndOfStatement))
1408 return TokError("unexpected token in assignment");
1410 // Error on assignment to '.'.
1412 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1413 "(use '.space' or '.org').)"));
1416 // Eat the end of statement marker.
1419 // Validate that the LHS is allowed to be a variable (either it has not been
1420 // used as a symbol, or it is an absolute symbol).
1421 MCSymbol *Sym = getContext().LookupSymbol(Name);
1423 // Diagnose assignment to a label.
1425 // FIXME: Diagnostics. Note the location of the definition as a label.
1426 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1427 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1428 ; // Allow redefinitions of undefined symbols only used in directives.
1429 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1430 return Error(EqualLoc, "redefinition of '" + Name + "'");
1431 else if (!Sym->isVariable())
1432 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1433 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1434 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1437 // Don't count these checks as uses.
1438 Sym->setUsed(false);
1440 Sym = getContext().GetOrCreateSymbol(Name);
1442 // FIXME: Handle '.'.
1444 // Do the assignment.
1445 Out.EmitAssignment(Sym, Value);
1450 /// ParseIdentifier:
1453 bool AsmParser::ParseIdentifier(StringRef &Res) {
1454 // The assembler has relaxed rules for accepting identifiers, in particular we
1455 // allow things like '.globl $foo', which would normally be separate
1456 // tokens. At this level, we have already lexed so we cannot (currently)
1457 // handle this as a context dependent token, instead we detect adjacent tokens
1458 // and return the combined identifier.
1459 if (Lexer.is(AsmToken::Dollar)) {
1460 SMLoc DollarLoc = getLexer().getLoc();
1462 // Consume the dollar sign, and check for a following identifier.
1464 if (Lexer.isNot(AsmToken::Identifier))
1467 // We have a '$' followed by an identifier, make sure they are adjacent.
1468 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1471 // Construct the joined identifier and consume the token.
1472 Res = StringRef(DollarLoc.getPointer(),
1473 getTok().getIdentifier().size() + 1);
1478 if (Lexer.isNot(AsmToken::Identifier) &&
1479 Lexer.isNot(AsmToken::String))
1482 Res = getTok().getIdentifier();
1484 Lex(); // Consume the identifier token.
1489 /// ParseDirectiveSet:
1490 /// ::= .equ identifier ',' expression
1491 /// ::= .equiv identifier ',' expression
1492 /// ::= .set identifier ',' expression
1493 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1496 if (ParseIdentifier(Name))
1497 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1499 if (getLexer().isNot(AsmToken::Comma))
1500 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1503 return ParseAssignment(Name, allow_redef);
1506 bool AsmParser::ParseEscapedString(std::string &Data) {
1507 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1510 StringRef Str = getTok().getStringContents();
1511 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1512 if (Str[i] != '\\') {
1517 // Recognize escaped characters. Note that this escape semantics currently
1518 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1521 return TokError("unexpected backslash at end of string");
1523 // Recognize octal sequences.
1524 if ((unsigned) (Str[i] - '0') <= 7) {
1525 // Consume up to three octal characters.
1526 unsigned Value = Str[i] - '0';
1528 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1530 Value = Value * 8 + (Str[i] - '0');
1532 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1534 Value = Value * 8 + (Str[i] - '0');
1539 return TokError("invalid octal escape sequence (out of range)");
1541 Data += (unsigned char) Value;
1545 // Otherwise recognize individual escapes.
1548 // Just reject invalid escape sequences for now.
1549 return TokError("invalid escape sequence (unrecognized character)");
1551 case 'b': Data += '\b'; break;
1552 case 'f': Data += '\f'; break;
1553 case 'n': Data += '\n'; break;
1554 case 'r': Data += '\r'; break;
1555 case 't': Data += '\t'; break;
1556 case '"': Data += '"'; break;
1557 case '\\': Data += '\\'; break;
1564 /// ParseDirectiveAscii:
1565 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1566 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1567 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1568 CheckForValidSection();
1571 if (getLexer().isNot(AsmToken::String))
1572 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1575 if (ParseEscapedString(Data))
1578 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1580 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1584 if (getLexer().is(AsmToken::EndOfStatement))
1587 if (getLexer().isNot(AsmToken::Comma))
1588 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1597 /// ParseDirectiveValue
1598 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1599 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1600 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1601 CheckForValidSection();
1604 const MCExpr *Value;
1605 SMLoc ExprLoc = getLexer().getLoc();
1606 if (ParseExpression(Value))
1609 // Special case constant expressions to match code generator.
1610 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1611 assert(Size <= 8 && "Invalid size");
1612 uint64_t IntValue = MCE->getValue();
1613 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1614 return Error(ExprLoc, "literal value out of range for directive");
1615 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1617 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1619 if (getLexer().is(AsmToken::EndOfStatement))
1622 // FIXME: Improve diagnostic.
1623 if (getLexer().isNot(AsmToken::Comma))
1624 return TokError("unexpected token in directive");
1633 /// ParseDirectiveRealValue
1634 /// ::= (.single | .double) [ expression (, expression)* ]
1635 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1636 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1637 CheckForValidSection();
1640 // We don't truly support arithmetic on floating point expressions, so we
1641 // have to manually parse unary prefixes.
1643 if (getLexer().is(AsmToken::Minus)) {
1646 } else if (getLexer().is(AsmToken::Plus))
1649 if (getLexer().isNot(AsmToken::Integer) &&
1650 getLexer().isNot(AsmToken::Real) &&
1651 getLexer().isNot(AsmToken::Identifier))
1652 return TokError("unexpected token in directive");
1654 // Convert to an APFloat.
1655 APFloat Value(Semantics);
1656 StringRef IDVal = getTok().getString();
1657 if (getLexer().is(AsmToken::Identifier)) {
1658 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1659 Value = APFloat::getInf(Semantics);
1660 else if (!IDVal.compare_lower("nan"))
1661 Value = APFloat::getNaN(Semantics, false, ~0);
1663 return TokError("invalid floating point literal");
1664 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1665 APFloat::opInvalidOp)
1666 return TokError("invalid floating point literal");
1670 // Consume the numeric token.
1673 // Emit the value as an integer.
1674 APInt AsInt = Value.bitcastToAPInt();
1675 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1676 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1678 if (getLexer().is(AsmToken::EndOfStatement))
1681 if (getLexer().isNot(AsmToken::Comma))
1682 return TokError("unexpected token in directive");
1691 /// ParseDirectiveSpace
1692 /// ::= .space expression [ , expression ]
1693 bool AsmParser::ParseDirectiveSpace() {
1694 CheckForValidSection();
1697 if (ParseAbsoluteExpression(NumBytes))
1700 int64_t FillExpr = 0;
1701 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1702 if (getLexer().isNot(AsmToken::Comma))
1703 return TokError("unexpected token in '.space' directive");
1706 if (ParseAbsoluteExpression(FillExpr))
1709 if (getLexer().isNot(AsmToken::EndOfStatement))
1710 return TokError("unexpected token in '.space' directive");
1716 return TokError("invalid number of bytes in '.space' directive");
1718 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1719 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1724 /// ParseDirectiveZero
1725 /// ::= .zero expression
1726 bool AsmParser::ParseDirectiveZero() {
1727 CheckForValidSection();
1730 if (ParseAbsoluteExpression(NumBytes))
1734 if (getLexer().is(AsmToken::Comma)) {
1736 if (ParseAbsoluteExpression(Val))
1740 if (getLexer().isNot(AsmToken::EndOfStatement))
1741 return TokError("unexpected token in '.zero' directive");
1745 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1750 /// ParseDirectiveFill
1751 /// ::= .fill expression , expression , expression
1752 bool AsmParser::ParseDirectiveFill() {
1753 CheckForValidSection();
1756 if (ParseAbsoluteExpression(NumValues))
1759 if (getLexer().isNot(AsmToken::Comma))
1760 return TokError("unexpected token in '.fill' directive");
1764 if (ParseAbsoluteExpression(FillSize))
1767 if (getLexer().isNot(AsmToken::Comma))
1768 return TokError("unexpected token in '.fill' directive");
1772 if (ParseAbsoluteExpression(FillExpr))
1775 if (getLexer().isNot(AsmToken::EndOfStatement))
1776 return TokError("unexpected token in '.fill' directive");
1780 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1781 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1783 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1784 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1789 /// ParseDirectiveOrg
1790 /// ::= .org expression [ , expression ]
1791 bool AsmParser::ParseDirectiveOrg() {
1792 CheckForValidSection();
1794 const MCExpr *Offset;
1795 if (ParseExpression(Offset))
1798 // Parse optional fill expression.
1799 int64_t FillExpr = 0;
1800 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1801 if (getLexer().isNot(AsmToken::Comma))
1802 return TokError("unexpected token in '.org' directive");
1805 if (ParseAbsoluteExpression(FillExpr))
1808 if (getLexer().isNot(AsmToken::EndOfStatement))
1809 return TokError("unexpected token in '.org' directive");
1814 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1815 // has to be relative to the current section.
1816 getStreamer().EmitValueToOffset(Offset, FillExpr);
1821 /// ParseDirectiveAlign
1822 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1823 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1824 CheckForValidSection();
1826 SMLoc AlignmentLoc = getLexer().getLoc();
1828 if (ParseAbsoluteExpression(Alignment))
1832 bool HasFillExpr = false;
1833 int64_t FillExpr = 0;
1834 int64_t MaxBytesToFill = 0;
1835 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1836 if (getLexer().isNot(AsmToken::Comma))
1837 return TokError("unexpected token in directive");
1840 // The fill expression can be omitted while specifying a maximum number of
1841 // alignment bytes, e.g:
1843 if (getLexer().isNot(AsmToken::Comma)) {
1845 if (ParseAbsoluteExpression(FillExpr))
1849 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1850 if (getLexer().isNot(AsmToken::Comma))
1851 return TokError("unexpected token in directive");
1854 MaxBytesLoc = getLexer().getLoc();
1855 if (ParseAbsoluteExpression(MaxBytesToFill))
1858 if (getLexer().isNot(AsmToken::EndOfStatement))
1859 return TokError("unexpected token in directive");
1868 // Compute alignment in bytes.
1870 // FIXME: Diagnose overflow.
1871 if (Alignment >= 32) {
1872 Error(AlignmentLoc, "invalid alignment value");
1876 Alignment = 1ULL << Alignment;
1879 // Diagnose non-sensical max bytes to align.
1880 if (MaxBytesLoc.isValid()) {
1881 if (MaxBytesToFill < 1) {
1882 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1883 "many bytes, ignoring maximum bytes expression");
1887 if (MaxBytesToFill >= Alignment) {
1888 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1894 // Check whether we should use optimal code alignment for this .align
1896 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1897 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1898 ValueSize == 1 && UseCodeAlign) {
1899 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1901 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1902 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1909 /// ParseDirectiveSymbolAttribute
1910 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1911 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1912 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1916 if (ParseIdentifier(Name))
1917 return TokError("expected identifier in directive");
1919 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1921 getStreamer().EmitSymbolAttribute(Sym, Attr);
1923 if (getLexer().is(AsmToken::EndOfStatement))
1926 if (getLexer().isNot(AsmToken::Comma))
1927 return TokError("unexpected token in directive");
1936 /// ParseDirectiveComm
1937 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1938 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1939 CheckForValidSection();
1941 SMLoc IDLoc = getLexer().getLoc();
1943 if (ParseIdentifier(Name))
1944 return TokError("expected identifier in directive");
1946 // Handle the identifier as the key symbol.
1947 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1949 if (getLexer().isNot(AsmToken::Comma))
1950 return TokError("unexpected token in directive");
1954 SMLoc SizeLoc = getLexer().getLoc();
1955 if (ParseAbsoluteExpression(Size))
1958 int64_t Pow2Alignment = 0;
1959 SMLoc Pow2AlignmentLoc;
1960 if (getLexer().is(AsmToken::Comma)) {
1962 Pow2AlignmentLoc = getLexer().getLoc();
1963 if (ParseAbsoluteExpression(Pow2Alignment))
1966 // If this target takes alignments in bytes (not log) validate and convert.
1967 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1968 if (!isPowerOf2_64(Pow2Alignment))
1969 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1970 Pow2Alignment = Log2_64(Pow2Alignment);
1974 if (getLexer().isNot(AsmToken::EndOfStatement))
1975 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1979 // NOTE: a size of zero for a .comm should create a undefined symbol
1980 // but a size of .lcomm creates a bss symbol of size zero.
1982 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1983 "be less than zero");
1985 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1986 // may internally end up wanting an alignment in bytes.
1987 // FIXME: Diagnose overflow.
1988 if (Pow2Alignment < 0)
1989 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1990 "alignment, can't be less than zero");
1992 if (!Sym->isUndefined())
1993 return Error(IDLoc, "invalid symbol redefinition");
1995 // '.lcomm' is equivalent to '.zerofill'.
1996 // Create the Symbol as a common or local common with Size and Pow2Alignment
1998 getStreamer().EmitZerofill(Ctx.getMachOSection(
1999 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2000 0, SectionKind::getBSS()),
2001 Sym, Size, 1 << Pow2Alignment);
2005 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2009 /// ParseDirectiveAbort
2010 /// ::= .abort [... message ...]
2011 bool AsmParser::ParseDirectiveAbort() {
2012 // FIXME: Use loc from directive.
2013 SMLoc Loc = getLexer().getLoc();
2015 StringRef Str = ParseStringToEndOfStatement();
2016 if (getLexer().isNot(AsmToken::EndOfStatement))
2017 return TokError("unexpected token in '.abort' directive");
2022 Error(Loc, ".abort detected. Assembly stopping.");
2024 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2025 // FIXME: Actually abort assembly here.
2030 /// ParseDirectiveInclude
2031 /// ::= .include "filename"
2032 bool AsmParser::ParseDirectiveInclude() {
2033 if (getLexer().isNot(AsmToken::String))
2034 return TokError("expected string in '.include' directive");
2036 std::string Filename = getTok().getString();
2037 SMLoc IncludeLoc = getLexer().getLoc();
2040 if (getLexer().isNot(AsmToken::EndOfStatement))
2041 return TokError("unexpected token in '.include' directive");
2043 // Strip the quotes.
2044 Filename = Filename.substr(1, Filename.size()-2);
2046 // Attempt to switch the lexer to the included file before consuming the end
2047 // of statement to avoid losing it when we switch.
2048 if (EnterIncludeFile(Filename)) {
2049 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2056 /// ParseDirectiveIf
2057 /// ::= .if expression
2058 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2059 TheCondStack.push_back(TheCondState);
2060 TheCondState.TheCond = AsmCond::IfCond;
2061 if(TheCondState.Ignore) {
2062 EatToEndOfStatement();
2066 if (ParseAbsoluteExpression(ExprValue))
2069 if (getLexer().isNot(AsmToken::EndOfStatement))
2070 return TokError("unexpected token in '.if' directive");
2074 TheCondState.CondMet = ExprValue;
2075 TheCondState.Ignore = !TheCondState.CondMet;
2081 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2083 TheCondStack.push_back(TheCondState);
2084 TheCondState.TheCond = AsmCond::IfCond;
2086 if (TheCondState.Ignore) {
2087 EatToEndOfStatement();
2089 if (ParseIdentifier(Name))
2090 return TokError("expected identifier after '.ifdef'");
2094 MCSymbol *Sym = getContext().LookupSymbol(Name);
2097 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2099 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2100 TheCondState.Ignore = !TheCondState.CondMet;
2106 /// ParseDirectiveElseIf
2107 /// ::= .elseif expression
2108 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2109 if (TheCondState.TheCond != AsmCond::IfCond &&
2110 TheCondState.TheCond != AsmCond::ElseIfCond)
2111 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2113 TheCondState.TheCond = AsmCond::ElseIfCond;
2115 bool LastIgnoreState = false;
2116 if (!TheCondStack.empty())
2117 LastIgnoreState = TheCondStack.back().Ignore;
2118 if (LastIgnoreState || TheCondState.CondMet) {
2119 TheCondState.Ignore = true;
2120 EatToEndOfStatement();
2124 if (ParseAbsoluteExpression(ExprValue))
2127 if (getLexer().isNot(AsmToken::EndOfStatement))
2128 return TokError("unexpected token in '.elseif' directive");
2131 TheCondState.CondMet = ExprValue;
2132 TheCondState.Ignore = !TheCondState.CondMet;
2138 /// ParseDirectiveElse
2140 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2141 if (getLexer().isNot(AsmToken::EndOfStatement))
2142 return TokError("unexpected token in '.else' directive");
2146 if (TheCondState.TheCond != AsmCond::IfCond &&
2147 TheCondState.TheCond != AsmCond::ElseIfCond)
2148 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2150 TheCondState.TheCond = AsmCond::ElseCond;
2151 bool LastIgnoreState = false;
2152 if (!TheCondStack.empty())
2153 LastIgnoreState = TheCondStack.back().Ignore;
2154 if (LastIgnoreState || TheCondState.CondMet)
2155 TheCondState.Ignore = true;
2157 TheCondState.Ignore = false;
2162 /// ParseDirectiveEndIf
2164 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2165 if (getLexer().isNot(AsmToken::EndOfStatement))
2166 return TokError("unexpected token in '.endif' directive");
2170 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2171 TheCondStack.empty())
2172 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2174 if (!TheCondStack.empty()) {
2175 TheCondState = TheCondStack.back();
2176 TheCondStack.pop_back();
2182 /// ParseDirectiveFile
2183 /// ::= .file [number] string
2184 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2185 // FIXME: I'm not sure what this is.
2186 int64_t FileNumber = -1;
2187 SMLoc FileNumberLoc = getLexer().getLoc();
2188 if (getLexer().is(AsmToken::Integer)) {
2189 FileNumber = getTok().getIntVal();
2193 return TokError("file number less than one");
2196 if (getLexer().isNot(AsmToken::String))
2197 return TokError("unexpected token in '.file' directive");
2199 StringRef Filename = getTok().getString();
2200 Filename = Filename.substr(1, Filename.size()-2);
2203 if (getLexer().isNot(AsmToken::EndOfStatement))
2204 return TokError("unexpected token in '.file' directive");
2206 if (FileNumber == -1)
2207 getStreamer().EmitFileDirective(Filename);
2209 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2210 Error(FileNumberLoc, "file number already allocated");
2216 /// ParseDirectiveLine
2217 /// ::= .line [number]
2218 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2219 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2220 if (getLexer().isNot(AsmToken::Integer))
2221 return TokError("unexpected token in '.line' directive");
2223 int64_t LineNumber = getTok().getIntVal();
2227 // FIXME: Do something with the .line.
2230 if (getLexer().isNot(AsmToken::EndOfStatement))
2231 return TokError("unexpected token in '.line' directive");
2237 /// ParseDirectiveLoc
2238 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2239 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2240 /// The first number is a file number, must have been previously assigned with
2241 /// a .file directive, the second number is the line number and optionally the
2242 /// third number is a column position (zero if not specified). The remaining
2243 /// optional items are .loc sub-directives.
2244 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2246 if (getLexer().isNot(AsmToken::Integer))
2247 return TokError("unexpected token in '.loc' directive");
2248 int64_t FileNumber = getTok().getIntVal();
2250 return TokError("file number less than one in '.loc' directive");
2251 if (!getContext().isValidDwarfFileNumber(FileNumber))
2252 return TokError("unassigned file number in '.loc' directive");
2255 int64_t LineNumber = 0;
2256 if (getLexer().is(AsmToken::Integer)) {
2257 LineNumber = getTok().getIntVal();
2259 return TokError("line number less than one in '.loc' directive");
2263 int64_t ColumnPos = 0;
2264 if (getLexer().is(AsmToken::Integer)) {
2265 ColumnPos = getTok().getIntVal();
2267 return TokError("column position less than zero in '.loc' directive");
2271 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2273 int64_t Discriminator = 0;
2274 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2276 if (getLexer().is(AsmToken::EndOfStatement))
2280 SMLoc Loc = getTok().getLoc();
2281 if (getParser().ParseIdentifier(Name))
2282 return TokError("unexpected token in '.loc' directive");
2284 if (Name == "basic_block")
2285 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2286 else if (Name == "prologue_end")
2287 Flags |= DWARF2_FLAG_PROLOGUE_END;
2288 else if (Name == "epilogue_begin")
2289 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2290 else if (Name == "is_stmt") {
2291 SMLoc Loc = getTok().getLoc();
2292 const MCExpr *Value;
2293 if (getParser().ParseExpression(Value))
2295 // The expression must be the constant 0 or 1.
2296 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2297 int Value = MCE->getValue();
2299 Flags &= ~DWARF2_FLAG_IS_STMT;
2300 else if (Value == 1)
2301 Flags |= DWARF2_FLAG_IS_STMT;
2303 return Error(Loc, "is_stmt value not 0 or 1");
2306 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2309 else if (Name == "isa") {
2310 SMLoc Loc = getTok().getLoc();
2311 const MCExpr *Value;
2312 if (getParser().ParseExpression(Value))
2314 // The expression must be a constant greater or equal to 0.
2315 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2316 int Value = MCE->getValue();
2318 return Error(Loc, "isa number less than zero");
2322 return Error(Loc, "isa number not a constant value");
2325 else if (Name == "discriminator") {
2326 if (getParser().ParseAbsoluteExpression(Discriminator))
2330 return Error(Loc, "unknown sub-directive in '.loc' directive");
2333 if (getLexer().is(AsmToken::EndOfStatement))
2338 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2339 Isa, Discriminator, StringRef());
2344 /// ParseDirectiveStabs
2345 /// ::= .stabs string, number, number, number
2346 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2347 SMLoc DirectiveLoc) {
2348 return TokError("unsupported directive '" + Directive + "'");
2351 /// ParseDirectiveCFISections
2352 /// ::= .cfi_sections section [, section]
2353 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2354 SMLoc DirectiveLoc) {
2359 if (getParser().ParseIdentifier(Name))
2360 return TokError("Expected an identifier");
2362 if (Name == ".eh_frame")
2364 else if (Name == ".debug_frame")
2367 if (getLexer().is(AsmToken::Comma)) {
2370 if (getParser().ParseIdentifier(Name))
2371 return TokError("Expected an identifier");
2373 if (Name == ".eh_frame")
2375 else if (Name == ".debug_frame")
2379 getStreamer().EmitCFISections(EH, Debug);
2384 /// ParseDirectiveCFIStartProc
2385 /// ::= .cfi_startproc
2386 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2387 SMLoc DirectiveLoc) {
2388 getStreamer().EmitCFIStartProc();
2392 /// ParseDirectiveCFIEndProc
2393 /// ::= .cfi_endproc
2394 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2395 getStreamer().EmitCFIEndProc();
2399 /// ParseRegisterOrRegisterNumber - parse register name or number.
2400 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2401 SMLoc DirectiveLoc) {
2404 if (getLexer().isNot(AsmToken::Integer)) {
2405 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2408 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2410 return getParser().ParseAbsoluteExpression(Register);
2415 /// ParseDirectiveCFIDefCfa
2416 /// ::= .cfi_def_cfa register, offset
2417 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2418 SMLoc DirectiveLoc) {
2419 int64_t Register = 0;
2420 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2423 if (getLexer().isNot(AsmToken::Comma))
2424 return TokError("unexpected token in directive");
2428 if (getParser().ParseAbsoluteExpression(Offset))
2431 getStreamer().EmitCFIDefCfa(Register, Offset);
2435 /// ParseDirectiveCFIDefCfaOffset
2436 /// ::= .cfi_def_cfa_offset offset
2437 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2438 SMLoc DirectiveLoc) {
2440 if (getParser().ParseAbsoluteExpression(Offset))
2443 getStreamer().EmitCFIDefCfaOffset(Offset);
2447 /// ParseDirectiveCFIAdjustCfaOffset
2448 /// ::= .cfi_adjust_cfa_offset adjustment
2449 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2450 SMLoc DirectiveLoc) {
2451 int64_t Adjustment = 0;
2452 if (getParser().ParseAbsoluteExpression(Adjustment))
2455 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2459 /// ParseDirectiveCFIDefCfaRegister
2460 /// ::= .cfi_def_cfa_register register
2461 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2462 SMLoc DirectiveLoc) {
2463 int64_t Register = 0;
2464 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2467 getStreamer().EmitCFIDefCfaRegister(Register);
2471 /// ParseDirectiveCFIOffset
2472 /// ::= .cfi_offset register, offset
2473 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2474 int64_t Register = 0;
2477 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2480 if (getLexer().isNot(AsmToken::Comma))
2481 return TokError("unexpected token in directive");
2484 if (getParser().ParseAbsoluteExpression(Offset))
2487 getStreamer().EmitCFIOffset(Register, Offset);
2491 /// ParseDirectiveCFIRelOffset
2492 /// ::= .cfi_rel_offset register, offset
2493 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2494 SMLoc DirectiveLoc) {
2495 int64_t Register = 0;
2497 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2500 if (getLexer().isNot(AsmToken::Comma))
2501 return TokError("unexpected token in directive");
2505 if (getParser().ParseAbsoluteExpression(Offset))
2508 getStreamer().EmitCFIRelOffset(Register, Offset);
2512 static bool isValidEncoding(int64_t Encoding) {
2513 if (Encoding & ~0xff)
2516 if (Encoding == dwarf::DW_EH_PE_omit)
2519 const unsigned Format = Encoding & 0xf;
2520 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2521 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2522 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2523 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2526 const unsigned Application = Encoding & 0x70;
2527 if (Application != dwarf::DW_EH_PE_absptr &&
2528 Application != dwarf::DW_EH_PE_pcrel)
2534 /// ParseDirectiveCFIPersonalityOrLsda
2535 /// ::= .cfi_personality encoding, [symbol_name]
2536 /// ::= .cfi_lsda encoding, [symbol_name]
2537 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2538 SMLoc DirectiveLoc) {
2539 int64_t Encoding = 0;
2540 if (getParser().ParseAbsoluteExpression(Encoding))
2542 if (Encoding == dwarf::DW_EH_PE_omit)
2545 if (!isValidEncoding(Encoding))
2546 return TokError("unsupported encoding.");
2548 if (getLexer().isNot(AsmToken::Comma))
2549 return TokError("unexpected token in directive");
2553 if (getParser().ParseIdentifier(Name))
2554 return TokError("expected identifier in directive");
2556 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2558 if (IDVal == ".cfi_personality")
2559 getStreamer().EmitCFIPersonality(Sym, Encoding);
2561 assert(IDVal == ".cfi_lsda");
2562 getStreamer().EmitCFILsda(Sym, Encoding);
2567 /// ParseDirectiveCFIRememberState
2568 /// ::= .cfi_remember_state
2569 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2570 SMLoc DirectiveLoc) {
2571 getStreamer().EmitCFIRememberState();
2575 /// ParseDirectiveCFIRestoreState
2576 /// ::= .cfi_remember_state
2577 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2578 SMLoc DirectiveLoc) {
2579 getStreamer().EmitCFIRestoreState();
2583 /// ParseDirectiveCFISameValue
2584 /// ::= .cfi_same_value register
2585 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2586 SMLoc DirectiveLoc) {
2587 int64_t Register = 0;
2589 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2592 getStreamer().EmitCFISameValue(Register);
2597 /// ParseDirectiveMacrosOnOff
2600 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2601 SMLoc DirectiveLoc) {
2602 if (getLexer().isNot(AsmToken::EndOfStatement))
2603 return Error(getLexer().getLoc(),
2604 "unexpected token in '" + Directive + "' directive");
2606 getParser().MacrosEnabled = Directive == ".macros_on";
2611 /// ParseDirectiveMacro
2612 /// ::= .macro name [parameters]
2613 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2614 SMLoc DirectiveLoc) {
2616 if (getParser().ParseIdentifier(Name))
2617 return TokError("expected identifier in directive");
2619 std::vector<StringRef> Parameters;
2620 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2622 StringRef Parameter;
2623 if (getParser().ParseIdentifier(Parameter))
2624 return TokError("expected identifier in directive");
2625 Parameters.push_back(Parameter);
2627 if (getLexer().isNot(AsmToken::Comma))
2633 if (getLexer().isNot(AsmToken::EndOfStatement))
2634 return TokError("unexpected token in '.macro' directive");
2636 // Eat the end of statement.
2639 AsmToken EndToken, StartToken = getTok();
2641 // Lex the macro definition.
2643 // Check whether we have reached the end of the file.
2644 if (getLexer().is(AsmToken::Eof))
2645 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2647 // Otherwise, check whether we have reach the .endmacro.
2648 if (getLexer().is(AsmToken::Identifier) &&
2649 (getTok().getIdentifier() == ".endm" ||
2650 getTok().getIdentifier() == ".endmacro")) {
2651 EndToken = getTok();
2653 if (getLexer().isNot(AsmToken::EndOfStatement))
2654 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2659 // Otherwise, scan til the end of the statement.
2660 getParser().EatToEndOfStatement();
2663 if (getParser().MacroMap.lookup(Name)) {
2664 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2667 const char *BodyStart = StartToken.getLoc().getPointer();
2668 const char *BodyEnd = EndToken.getLoc().getPointer();
2669 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2670 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2674 /// ParseDirectiveEndMacro
2677 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2678 SMLoc DirectiveLoc) {
2679 if (getLexer().isNot(AsmToken::EndOfStatement))
2680 return TokError("unexpected token in '" + Directive + "' directive");
2682 // If we are inside a macro instantiation, terminate the current
2684 if (!getParser().ActiveMacros.empty()) {
2685 getParser().HandleMacroExit();
2689 // Otherwise, this .endmacro is a stray entry in the file; well formed
2690 // .endmacro directives are handled during the macro definition parsing.
2691 return TokError("unexpected '" + Directive + "' in file, "
2692 "no current macro definition");
2695 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2696 getParser().CheckForValidSection();
2698 const MCExpr *Value;
2700 if (getParser().ParseExpression(Value))
2703 if (getLexer().isNot(AsmToken::EndOfStatement))
2704 return TokError("unexpected token in directive");
2706 if (DirName[1] == 's')
2707 getStreamer().EmitSLEB128Value(Value);
2709 getStreamer().EmitULEB128Value(Value);
2715 /// \brief Create an MCAsmParser instance.
2716 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2717 MCContext &C, MCStreamer &Out,
2718 const MCAsmInfo &MAI) {
2719 return new AsmParser(T, SM, C, Out, MAI);