1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCDwarf.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetAsmParser.h"
41 FatalAssemblerWarnings("fatal-assembler-warnings",
42 cl::desc("Consider warnings as error"));
46 /// \brief Helper class for tracking macro definitions.
52 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
55 /// \brief Helper class for storing information about an active macro
57 struct MacroInstantiation {
58 /// The macro being instantiated.
59 const Macro *TheMacro;
61 /// The macro instantiation with substitutions.
62 MemoryBuffer *Instantiation;
64 /// The location of the instantiation.
65 SMLoc InstantiationLoc;
67 /// The location where parsing should resume upon instantiation completion.
71 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
72 const std::vector<std::vector<AsmToken> > &A);
75 /// \brief The concrete assembly parser instance.
76 class AsmParser : public MCAsmParser {
77 friend class GenericAsmParser;
79 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
80 void operator=(const AsmParser &); // DO NOT IMPLEMENT
86 MCAsmParserExtension *GenericParser;
87 MCAsmParserExtension *PlatformParser;
89 /// This is the current buffer index we're lexing from as managed by the
94 std::vector<AsmCond> TheCondStack;
96 /// DirectiveMap - This is a table handlers for directives. Each handler is
97 /// invoked after the directive identifier is read and is responsible for
98 /// parsing and validating the rest of the directive. The handler is passed
99 /// in the directive name and the location of the directive keyword.
100 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
102 /// MacroMap - Map of currently defined macros.
103 StringMap<Macro*> MacroMap;
105 /// ActiveMacros - Stack of active macro instantiations.
106 std::vector<MacroInstantiation*> ActiveMacros;
108 /// Boolean tracking whether macro substitution is enabled.
109 unsigned MacrosEnabled : 1;
111 /// Flag tracking whether any errors have been encountered.
112 unsigned HadError : 1;
115 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
116 const MCAsmInfo &MAI);
119 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
121 void AddDirectiveHandler(MCAsmParserExtension *Object,
123 DirectiveHandler Handler) {
124 DirectiveMap[Directive] = std::make_pair(Object, Handler);
128 /// @name MCAsmParser Interface
131 virtual SourceMgr &getSourceManager() { return SrcMgr; }
132 virtual MCAsmLexer &getLexer() { return Lexer; }
133 virtual MCContext &getContext() { return Ctx; }
134 virtual MCStreamer &getStreamer() { return Out; }
136 virtual bool Warning(SMLoc L, const Twine &Meg);
137 virtual bool Error(SMLoc L, const Twine &Msg);
139 const AsmToken &Lex();
141 bool ParseExpression(const MCExpr *&Res);
142 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
143 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
144 virtual bool ParseAbsoluteExpression(int64_t &Res);
149 void CheckForValidSection();
151 bool ParseStatement();
153 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
154 void HandleMacroExit();
156 void PrintMacroInstantiations();
157 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
158 SrcMgr.PrintMessage(Loc, Msg, Type);
161 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
162 bool EnterIncludeFile(const std::string &Filename);
164 /// \brief Reset the current lexer position to that given by \arg Loc. The
165 /// current token is not set; clients should ensure Lex() is called
167 void JumpToLoc(SMLoc Loc);
169 void EatToEndOfStatement();
171 /// \brief Parse up to the end of statement and a return the contents from the
172 /// current token until the end of the statement; the current token on exit
173 /// will be either the EndOfStatement or EOF.
174 StringRef ParseStringToEndOfStatement();
176 bool ParseAssignment(StringRef Name, bool allow_redef);
178 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
179 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
180 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
181 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
183 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
184 /// and set \arg Res to the identifier contents.
185 bool ParseIdentifier(StringRef &Res);
187 // Directive Parsing.
189 // ".ascii", ".asciiz", ".string"
190 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
191 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
192 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
193 bool ParseDirectiveFill(); // ".fill"
194 bool ParseDirectiveSpace(); // ".space"
195 bool ParseDirectiveZero(); // ".zero"
196 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
197 bool ParseDirectiveOrg(); // ".org"
198 // ".align{,32}", ".p2align{,w,l}"
199 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
201 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
202 /// accepts a single symbol (which should be a label or an external).
203 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
205 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
207 bool ParseDirectiveAbort(); // ".abort"
208 bool ParseDirectiveInclude(); // ".include"
210 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
211 // ".ifdef" or ".ifndef", depending on expect_defined
212 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
213 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
214 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
215 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
217 /// ParseEscapedString - Parse the current token as a string which may include
218 /// escaped characters and return the string contents.
219 bool ParseEscapedString(std::string &Data);
221 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
222 MCSymbolRefExpr::VariantKind Variant);
225 /// \brief Generic implementations of directive handling, etc. which is shared
226 /// (or the default, at least) for all assembler parser.
227 class GenericAsmParser : public MCAsmParserExtension {
228 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
229 void AddDirectiveHandler(StringRef Directive) {
230 getParser().AddDirectiveHandler(this, Directive,
231 HandleDirective<GenericAsmParser, Handler>);
234 GenericAsmParser() {}
236 AsmParser &getParser() {
237 return (AsmParser&) this->MCAsmParserExtension::getParser();
240 virtual void Initialize(MCAsmParser &Parser) {
241 // Call the base implementation.
242 this->MCAsmParserExtension::Initialize(Parser);
244 // Debugging directives.
245 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
246 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
247 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
248 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
251 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
253 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
255 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
257 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
259 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
260 ".cfi_def_cfa_offset");
261 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
262 ".cfi_adjust_cfa_offset");
263 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
264 ".cfi_def_cfa_register");
265 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
270 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
272 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
274 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
276 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
278 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
281 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
283 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
285 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
287 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
289 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
293 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
295 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
296 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
297 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
298 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
299 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
300 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
301 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
302 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
303 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
304 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
305 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
306 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
307 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
308 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
309 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
310 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
311 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
313 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
314 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
315 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
317 bool ParseDirectiveLEB128(StringRef, SMLoc);
324 extern MCAsmParserExtension *createDarwinAsmParser();
325 extern MCAsmParserExtension *createELFAsmParser();
326 extern MCAsmParserExtension *createCOFFAsmParser();
330 enum { DEFAULT_ADDRSPACE = 0 };
332 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
333 MCStreamer &_Out, const MCAsmInfo &_MAI)
334 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
335 GenericParser(new GenericAsmParser), PlatformParser(0),
336 CurBuffer(0), MacrosEnabled(true) {
337 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
339 // Initialize the generic parser.
340 GenericParser->Initialize(*this);
342 // Initialize the platform / file format parser.
344 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
346 if (_MAI.hasMicrosoftFastStdCallMangling()) {
347 PlatformParser = createCOFFAsmParser();
348 PlatformParser->Initialize(*this);
349 } else if (_MAI.hasSubsectionsViaSymbols()) {
350 PlatformParser = createDarwinAsmParser();
351 PlatformParser->Initialize(*this);
353 PlatformParser = createELFAsmParser();
354 PlatformParser->Initialize(*this);
358 AsmParser::~AsmParser() {
359 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
361 // Destroy any macros.
362 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
363 ie = MacroMap.end(); it != ie; ++it)
364 delete it->getValue();
366 delete PlatformParser;
367 delete GenericParser;
370 void AsmParser::PrintMacroInstantiations() {
371 // Print the active macro instantiation stack.
372 for (std::vector<MacroInstantiation*>::const_reverse_iterator
373 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
374 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
378 bool AsmParser::Warning(SMLoc L, const Twine &Msg) {
379 if (FatalAssemblerWarnings)
380 return Error(L, Msg);
381 PrintMessage(L, Msg, "warning");
382 PrintMacroInstantiations();
386 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
388 PrintMessage(L, Msg, "error");
389 PrintMacroInstantiations();
393 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
394 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
400 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
405 void AsmParser::JumpToLoc(SMLoc Loc) {
406 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
407 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
410 const AsmToken &AsmParser::Lex() {
411 const AsmToken *tok = &Lexer.Lex();
413 if (tok->is(AsmToken::Eof)) {
414 // If this is the end of an included file, pop the parent file off the
416 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
417 if (ParentIncludeLoc != SMLoc()) {
418 JumpToLoc(ParentIncludeLoc);
423 if (tok->is(AsmToken::Error))
424 Error(Lexer.getErrLoc(), Lexer.getErr());
429 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
430 // Create the initial section, if requested.
431 if (!NoInitialTextSection)
438 AsmCond StartingCondState = TheCondState;
440 // While we have input, parse each statement.
441 while (Lexer.isNot(AsmToken::Eof)) {
442 if (!ParseStatement()) continue;
444 // We had an error, validate that one was emitted and recover by skipping to
446 assert(HadError && "Parse statement returned an error, but none emitted!");
447 EatToEndOfStatement();
450 if (TheCondState.TheCond != StartingCondState.TheCond ||
451 TheCondState.Ignore != StartingCondState.Ignore)
452 return TokError("unmatched .ifs or .elses");
454 // Check to see there are no empty DwarfFile slots.
455 const std::vector<MCDwarfFile *> &MCDwarfFiles =
456 getContext().getMCDwarfFiles();
457 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
458 if (!MCDwarfFiles[i])
459 TokError("unassigned file number: " + Twine(i) + " for .file directives");
462 // Finalize the output stream if there are no errors and if the client wants
464 if (!HadError && !NoFinalize)
470 void AsmParser::CheckForValidSection() {
471 if (!getStreamer().getCurrentSection()) {
472 TokError("expected section directive before assembly directive");
473 Out.SwitchSection(Ctx.getMachOSection(
475 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
476 0, SectionKind::getText()));
480 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
481 void AsmParser::EatToEndOfStatement() {
482 while (Lexer.isNot(AsmToken::EndOfStatement) &&
483 Lexer.isNot(AsmToken::Eof))
487 if (Lexer.is(AsmToken::EndOfStatement))
491 StringRef AsmParser::ParseStringToEndOfStatement() {
492 const char *Start = getTok().getLoc().getPointer();
494 while (Lexer.isNot(AsmToken::EndOfStatement) &&
495 Lexer.isNot(AsmToken::Eof))
498 const char *End = getTok().getLoc().getPointer();
499 return StringRef(Start, End - Start);
502 /// ParseParenExpr - Parse a paren expression and return it.
503 /// NOTE: This assumes the leading '(' has already been consumed.
505 /// parenexpr ::= expr)
507 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
508 if (ParseExpression(Res)) return true;
509 if (Lexer.isNot(AsmToken::RParen))
510 return TokError("expected ')' in parentheses expression");
511 EndLoc = Lexer.getLoc();
516 /// ParseBracketExpr - Parse a bracket expression and return it.
517 /// NOTE: This assumes the leading '[' has already been consumed.
519 /// bracketexpr ::= expr]
521 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
522 if (ParseExpression(Res)) return true;
523 if (Lexer.isNot(AsmToken::RBrac))
524 return TokError("expected ']' in brackets expression");
525 EndLoc = Lexer.getLoc();
530 /// ParsePrimaryExpr - Parse a primary expression and return it.
531 /// primaryexpr ::= (parenexpr
532 /// primaryexpr ::= symbol
533 /// primaryexpr ::= number
534 /// primaryexpr ::= '.'
535 /// primaryexpr ::= ~,+,- primaryexpr
536 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
537 switch (Lexer.getKind()) {
539 return TokError("unknown token in expression");
540 // If we have an error assume that we've already handled it.
541 case AsmToken::Error:
543 case AsmToken::Exclaim:
544 Lex(); // Eat the operator.
545 if (ParsePrimaryExpr(Res, EndLoc))
547 Res = MCUnaryExpr::CreateLNot(Res, getContext());
549 case AsmToken::Dollar:
550 case AsmToken::String:
551 case AsmToken::Identifier: {
552 EndLoc = Lexer.getLoc();
554 StringRef Identifier;
555 if (ParseIdentifier(Identifier))
558 // This is a symbol reference.
559 std::pair<StringRef, StringRef> Split = Identifier.split('@');
560 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
562 // Lookup the symbol variant if used.
563 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
564 if (Split.first.size() != Identifier.size()) {
565 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
566 if (Variant == MCSymbolRefExpr::VK_Invalid) {
567 Variant = MCSymbolRefExpr::VK_None;
568 return TokError("invalid variant '" + Split.second + "'");
572 // If this is an absolute variable reference, substitute it now to preserve
573 // semantics in the face of reassignment.
574 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
576 return Error(EndLoc, "unexpected modifier on variable reference");
578 Res = Sym->getVariableValue();
582 // Otherwise create a symbol ref.
583 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
586 case AsmToken::Integer: {
587 SMLoc Loc = getTok().getLoc();
588 int64_t IntVal = getTok().getIntVal();
589 Res = MCConstantExpr::Create(IntVal, getContext());
590 EndLoc = Lexer.getLoc();
592 // Look for 'b' or 'f' following an Integer as a directional label
593 if (Lexer.getKind() == AsmToken::Identifier) {
594 StringRef IDVal = getTok().getString();
595 if (IDVal == "f" || IDVal == "b"){
596 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
597 IDVal == "f" ? 1 : 0);
598 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
600 if(IDVal == "b" && Sym->isUndefined())
601 return Error(Loc, "invalid reference to undefined symbol");
602 EndLoc = Lexer.getLoc();
603 Lex(); // Eat identifier.
608 case AsmToken::Real: {
609 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
610 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
611 Res = MCConstantExpr::Create(IntVal, getContext());
615 case AsmToken::Dot: {
616 // This is a '.' reference, which references the current PC. Emit a
617 // temporary label to the streamer and refer to it.
618 MCSymbol *Sym = Ctx.CreateTempSymbol();
620 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
621 EndLoc = Lexer.getLoc();
622 Lex(); // Eat identifier.
625 case AsmToken::LParen:
626 Lex(); // Eat the '('.
627 return ParseParenExpr(Res, EndLoc);
628 case AsmToken::LBrac:
629 if (!PlatformParser->HasBracketExpressions())
630 return TokError("brackets expression not supported on this target");
631 Lex(); // Eat the '['.
632 return ParseBracketExpr(Res, EndLoc);
633 case AsmToken::Minus:
634 Lex(); // Eat the operator.
635 if (ParsePrimaryExpr(Res, EndLoc))
637 Res = MCUnaryExpr::CreateMinus(Res, getContext());
640 Lex(); // Eat the operator.
641 if (ParsePrimaryExpr(Res, EndLoc))
643 Res = MCUnaryExpr::CreatePlus(Res, getContext());
645 case AsmToken::Tilde:
646 Lex(); // Eat the operator.
647 if (ParsePrimaryExpr(Res, EndLoc))
649 Res = MCUnaryExpr::CreateNot(Res, getContext());
654 bool AsmParser::ParseExpression(const MCExpr *&Res) {
656 return ParseExpression(Res, EndLoc);
660 AsmParser::ApplyModifierToExpr(const MCExpr *E,
661 MCSymbolRefExpr::VariantKind Variant) {
662 // Recurse over the given expression, rebuilding it to apply the given variant
663 // if there is exactly one symbol.
664 switch (E->getKind()) {
666 case MCExpr::Constant:
669 case MCExpr::SymbolRef: {
670 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
672 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
673 TokError("invalid variant on expression '" +
674 getTok().getIdentifier() + "' (already modified)");
678 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
681 case MCExpr::Unary: {
682 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
683 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
686 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
689 case MCExpr::Binary: {
690 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
691 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
692 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
697 if (!LHS) LHS = BE->getLHS();
698 if (!RHS) RHS = BE->getRHS();
700 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
704 assert(0 && "Invalid expression kind!");
708 /// ParseExpression - Parse an expression and return it.
710 /// expr ::= expr +,- expr -> lowest.
711 /// expr ::= expr |,^,&,! expr -> middle.
712 /// expr ::= expr *,/,%,<<,>> expr -> highest.
713 /// expr ::= primaryexpr
715 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
716 // Parse the expression.
718 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
721 // As a special case, we support 'a op b @ modifier' by rewriting the
722 // expression to include the modifier. This is inefficient, but in general we
723 // expect users to use 'a@modifier op b'.
724 if (Lexer.getKind() == AsmToken::At) {
727 if (Lexer.isNot(AsmToken::Identifier))
728 return TokError("unexpected symbol modifier following '@'");
730 MCSymbolRefExpr::VariantKind Variant =
731 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
732 if (Variant == MCSymbolRefExpr::VK_Invalid)
733 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
735 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
737 return TokError("invalid modifier '" + getTok().getIdentifier() +
738 "' (no symbols present)");
746 // Try to constant fold it up front, if possible.
748 if (Res->EvaluateAsAbsolute(Value))
749 Res = MCConstantExpr::Create(Value, getContext());
754 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
756 return ParseParenExpr(Res, EndLoc) ||
757 ParseBinOpRHS(1, Res, EndLoc);
760 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
763 SMLoc StartLoc = Lexer.getLoc();
764 if (ParseExpression(Expr))
767 if (!Expr->EvaluateAsAbsolute(Res))
768 return Error(StartLoc, "expected absolute expression");
773 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
774 MCBinaryExpr::Opcode &Kind) {
777 return 0; // not a binop.
779 // Lowest Precedence: &&, ||, @
780 case AsmToken::AmpAmp:
781 Kind = MCBinaryExpr::LAnd;
783 case AsmToken::PipePipe:
784 Kind = MCBinaryExpr::LOr;
788 // Low Precedence: |, &, ^
790 // FIXME: gas seems to support '!' as an infix operator?
792 Kind = MCBinaryExpr::Or;
794 case AsmToken::Caret:
795 Kind = MCBinaryExpr::Xor;
798 Kind = MCBinaryExpr::And;
801 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
802 case AsmToken::EqualEqual:
803 Kind = MCBinaryExpr::EQ;
805 case AsmToken::ExclaimEqual:
806 case AsmToken::LessGreater:
807 Kind = MCBinaryExpr::NE;
810 Kind = MCBinaryExpr::LT;
812 case AsmToken::LessEqual:
813 Kind = MCBinaryExpr::LTE;
815 case AsmToken::Greater:
816 Kind = MCBinaryExpr::GT;
818 case AsmToken::GreaterEqual:
819 Kind = MCBinaryExpr::GTE;
822 // High Intermediate Precedence: +, -
824 Kind = MCBinaryExpr::Add;
826 case AsmToken::Minus:
827 Kind = MCBinaryExpr::Sub;
830 // Highest Precedence: *, /, %, <<, >>
832 Kind = MCBinaryExpr::Mul;
834 case AsmToken::Slash:
835 Kind = MCBinaryExpr::Div;
837 case AsmToken::Percent:
838 Kind = MCBinaryExpr::Mod;
840 case AsmToken::LessLess:
841 Kind = MCBinaryExpr::Shl;
843 case AsmToken::GreaterGreater:
844 Kind = MCBinaryExpr::Shr;
850 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
851 /// Res contains the LHS of the expression on input.
852 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
855 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
856 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
858 // If the next token is lower precedence than we are allowed to eat, return
859 // successfully with what we ate already.
860 if (TokPrec < Precedence)
865 // Eat the next primary expression.
867 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
869 // If BinOp binds less tightly with RHS than the operator after RHS, let
870 // the pending operator take RHS as its LHS.
871 MCBinaryExpr::Opcode Dummy;
872 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
873 if (TokPrec < NextTokPrec) {
874 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
877 // Merge LHS and RHS according to operator.
878 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
886 /// ::= EndOfStatement
887 /// ::= Label* Directive ...Operands... EndOfStatement
888 /// ::= Label* Identifier OperandList* EndOfStatement
889 bool AsmParser::ParseStatement() {
890 if (Lexer.is(AsmToken::EndOfStatement)) {
896 // Statements always start with an identifier or are a full line comment.
897 AsmToken ID = getTok();
898 SMLoc IDLoc = ID.getLoc();
900 int64_t LocalLabelVal = -1;
901 // A full line comment is a '#' as the first token.
902 if (Lexer.is(AsmToken::Hash)) {
903 EatToEndOfStatement();
907 // Allow an integer followed by a ':' as a directional local label.
908 if (Lexer.is(AsmToken::Integer)) {
909 LocalLabelVal = getTok().getIntVal();
910 if (LocalLabelVal < 0) {
911 if (!TheCondState.Ignore)
912 return TokError("unexpected token at start of statement");
916 IDVal = getTok().getString();
917 Lex(); // Consume the integer token to be used as an identifier token.
918 if (Lexer.getKind() != AsmToken::Colon) {
919 if (!TheCondState.Ignore)
920 return TokError("unexpected token at start of statement");
924 } else if (Lexer.is(AsmToken::Dot)) {
925 // Treat '.' as a valid identifier in this context.
929 } else if (ParseIdentifier(IDVal)) {
930 if (!TheCondState.Ignore)
931 return TokError("unexpected token at start of statement");
936 // Handle conditional assembly here before checking for skipping. We
937 // have to do this so that .endif isn't skipped in a ".if 0" block for
940 return ParseDirectiveIf(IDLoc);
941 if (IDVal == ".ifdef")
942 return ParseDirectiveIfdef(IDLoc, true);
943 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
944 return ParseDirectiveIfdef(IDLoc, false);
945 if (IDVal == ".elseif")
946 return ParseDirectiveElseIf(IDLoc);
947 if (IDVal == ".else")
948 return ParseDirectiveElse(IDLoc);
949 if (IDVal == ".endif")
950 return ParseDirectiveEndIf(IDLoc);
952 // If we are in a ".if 0" block, ignore this statement.
953 if (TheCondState.Ignore) {
954 EatToEndOfStatement();
958 // FIXME: Recurse on local labels?
960 // See what kind of statement we have.
961 switch (Lexer.getKind()) {
962 case AsmToken::Colon: {
963 CheckForValidSection();
965 // identifier ':' -> Label.
968 // Diagnose attempt to use '.' as a label.
970 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
972 // Diagnose attempt to use a variable as a label.
974 // FIXME: Diagnostics. Note the location of the definition as a label.
975 // FIXME: This doesn't diagnose assignment to a symbol which has been
976 // implicitly marked as external.
978 if (LocalLabelVal == -1)
979 Sym = getContext().GetOrCreateSymbol(IDVal);
981 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
982 if (!Sym->isUndefined() || Sym->isVariable())
983 return Error(IDLoc, "invalid symbol redefinition");
988 // Consume any end of statement token, if present, to avoid spurious
989 // AddBlankLine calls().
990 if (Lexer.is(AsmToken::EndOfStatement)) {
992 if (Lexer.is(AsmToken::Eof))
996 return ParseStatement();
999 case AsmToken::Equal:
1000 // identifier '=' ... -> assignment statement
1003 return ParseAssignment(IDVal, true);
1005 default: // Normal instruction or directive.
1009 // If macros are enabled, check to see if this is a macro instantiation.
1011 if (const Macro *M = MacroMap.lookup(IDVal))
1012 return HandleMacroEntry(IDVal, IDLoc, M);
1014 // Otherwise, we have a normal instruction or directive.
1015 if (IDVal[0] == '.' && IDVal != ".") {
1016 // Assembler features
1017 if (IDVal == ".set" || IDVal == ".equ")
1018 return ParseDirectiveSet(IDVal, true);
1019 if (IDVal == ".equiv")
1020 return ParseDirectiveSet(IDVal, false);
1024 if (IDVal == ".ascii")
1025 return ParseDirectiveAscii(IDVal, false);
1026 if (IDVal == ".asciz" || IDVal == ".string")
1027 return ParseDirectiveAscii(IDVal, true);
1029 if (IDVal == ".byte")
1030 return ParseDirectiveValue(1);
1031 if (IDVal == ".short")
1032 return ParseDirectiveValue(2);
1033 if (IDVal == ".value")
1034 return ParseDirectiveValue(2);
1035 if (IDVal == ".2byte")
1036 return ParseDirectiveValue(2);
1037 if (IDVal == ".long")
1038 return ParseDirectiveValue(4);
1039 if (IDVal == ".int")
1040 return ParseDirectiveValue(4);
1041 if (IDVal == ".4byte")
1042 return ParseDirectiveValue(4);
1043 if (IDVal == ".quad")
1044 return ParseDirectiveValue(8);
1045 if (IDVal == ".8byte")
1046 return ParseDirectiveValue(8);
1047 if (IDVal == ".single" || IDVal == ".float")
1048 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1049 if (IDVal == ".double")
1050 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1052 if (IDVal == ".align") {
1053 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1054 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1056 if (IDVal == ".align32") {
1057 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1058 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1060 if (IDVal == ".balign")
1061 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1062 if (IDVal == ".balignw")
1063 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1064 if (IDVal == ".balignl")
1065 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1066 if (IDVal == ".p2align")
1067 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1068 if (IDVal == ".p2alignw")
1069 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1070 if (IDVal == ".p2alignl")
1071 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1073 if (IDVal == ".org")
1074 return ParseDirectiveOrg();
1076 if (IDVal == ".fill")
1077 return ParseDirectiveFill();
1078 if (IDVal == ".space" || IDVal == ".skip")
1079 return ParseDirectiveSpace();
1080 if (IDVal == ".zero")
1081 return ParseDirectiveZero();
1083 // Symbol attribute directives
1085 if (IDVal == ".globl" || IDVal == ".global")
1086 return ParseDirectiveSymbolAttribute(MCSA_Global);
1087 // ELF only? Should it be here?
1088 if (IDVal == ".local")
1089 return ParseDirectiveSymbolAttribute(MCSA_Local);
1090 if (IDVal == ".hidden")
1091 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1092 if (IDVal == ".indirect_symbol")
1093 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1094 if (IDVal == ".internal")
1095 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1096 if (IDVal == ".lazy_reference")
1097 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1098 if (IDVal == ".no_dead_strip")
1099 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1100 if (IDVal == ".symbol_resolver")
1101 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1102 if (IDVal == ".private_extern")
1103 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1104 if (IDVal == ".protected")
1105 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1106 if (IDVal == ".reference")
1107 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1108 if (IDVal == ".weak")
1109 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1110 if (IDVal == ".weak_definition")
1111 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1112 if (IDVal == ".weak_reference")
1113 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1114 if (IDVal == ".weak_def_can_be_hidden")
1115 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1117 if (IDVal == ".comm")
1118 return ParseDirectiveComm(/*IsLocal=*/false);
1119 if (IDVal == ".lcomm")
1120 return ParseDirectiveComm(/*IsLocal=*/true);
1122 if (IDVal == ".abort")
1123 return ParseDirectiveAbort();
1124 if (IDVal == ".include")
1125 return ParseDirectiveInclude();
1127 if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1128 return TokError(Twine(IDVal) + " not supported yet");
1130 // Look up the handler in the handler table.
1131 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1132 DirectiveMap.lookup(IDVal);
1134 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1136 // Target hook for parsing target specific directives.
1137 if (!getTargetParser().ParseDirective(ID))
1140 bool retval = Warning(IDLoc, "ignoring directive for now");
1141 EatToEndOfStatement();
1145 CheckForValidSection();
1147 // Canonicalize the opcode to lower case.
1148 SmallString<128> Opcode;
1149 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1150 Opcode.push_back(tolower(IDVal[i]));
1152 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1153 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1156 // Dump the parsed representation, if requested.
1157 if (getShowParsedOperands()) {
1158 SmallString<256> Str;
1159 raw_svector_ostream OS(Str);
1160 OS << "parsed instruction: [";
1161 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1164 ParsedOperands[i]->dump(OS);
1168 PrintMessage(IDLoc, OS.str(), "note");
1171 // If parsing succeeded, match the instruction.
1173 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1176 // Free any parsed operands.
1177 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1178 delete ParsedOperands[i];
1180 // Don't skip the rest of the line, the instruction parser is responsible for
1185 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1186 const std::vector<std::vector<AsmToken> > &A)
1187 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1189 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1190 // to hold the macro body with substitutions.
1191 SmallString<256> Buf;
1192 raw_svector_ostream OS(Buf);
1194 StringRef Body = M->Body;
1195 while (!Body.empty()) {
1196 // Scan for the next substitution.
1197 std::size_t End = Body.size(), Pos = 0;
1198 for (; Pos != End; ++Pos) {
1199 // Check for a substitution or escape.
1200 if (Body[Pos] != '$' || Pos + 1 == End)
1203 char Next = Body[Pos + 1];
1204 if (Next == '$' || Next == 'n' || isdigit(Next))
1209 OS << Body.slice(0, Pos);
1211 // Check if we reached the end.
1215 switch (Body[Pos+1]) {
1221 // $n => number of arguments
1226 // $[0-9] => argument
1228 // Missing arguments are ignored.
1229 unsigned Index = Body[Pos+1] - '0';
1230 if (Index >= A.size())
1233 // Otherwise substitute with the token values, with spaces eliminated.
1234 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1235 ie = A[Index].end(); it != ie; ++it)
1236 OS << it->getString();
1241 // Update the scan point.
1242 Body = Body.substr(Pos + 2);
1245 // We include the .endmacro in the buffer as our queue to exit the macro
1247 OS << ".endmacro\n";
1249 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1252 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1254 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1255 // this, although we should protect against infinite loops.
1256 if (ActiveMacros.size() == 20)
1257 return TokError("macros cannot be nested more than 20 levels deep");
1259 // Parse the macro instantiation arguments.
1260 std::vector<std::vector<AsmToken> > MacroArguments;
1261 MacroArguments.push_back(std::vector<AsmToken>());
1262 unsigned ParenLevel = 0;
1264 if (Lexer.is(AsmToken::Eof))
1265 return TokError("unexpected token in macro instantiation");
1266 if (Lexer.is(AsmToken::EndOfStatement))
1269 // If we aren't inside parentheses and this is a comma, start a new token
1271 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1272 MacroArguments.push_back(std::vector<AsmToken>());
1274 // Adjust the current parentheses level.
1275 if (Lexer.is(AsmToken::LParen))
1277 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1280 // Append the token to the current argument list.
1281 MacroArguments.back().push_back(getTok());
1286 // Create the macro instantiation object and add to the current macro
1287 // instantiation stack.
1288 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1291 ActiveMacros.push_back(MI);
1293 // Jump to the macro instantiation and prime the lexer.
1294 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1295 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1301 void AsmParser::HandleMacroExit() {
1302 // Jump to the EndOfStatement we should return to, and consume it.
1303 JumpToLoc(ActiveMacros.back()->ExitLoc);
1306 // Pop the instantiation entry.
1307 delete ActiveMacros.back();
1308 ActiveMacros.pop_back();
1311 static void MarkUsed(const MCExpr *Value) {
1312 switch (Value->getKind()) {
1313 case MCExpr::Binary:
1314 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1315 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1317 case MCExpr::Target:
1318 case MCExpr::Constant:
1320 case MCExpr::SymbolRef: {
1321 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1325 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1330 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1331 // FIXME: Use better location, we should use proper tokens.
1332 SMLoc EqualLoc = Lexer.getLoc();
1334 const MCExpr *Value;
1335 if (ParseExpression(Value))
1340 if (Lexer.isNot(AsmToken::EndOfStatement))
1341 return TokError("unexpected token in assignment");
1343 // Error on assignment to '.'.
1345 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1346 "(use '.space' or '.org').)"));
1349 // Eat the end of statement marker.
1352 // Validate that the LHS is allowed to be a variable (either it has not been
1353 // used as a symbol, or it is an absolute symbol).
1354 MCSymbol *Sym = getContext().LookupSymbol(Name);
1356 // Diagnose assignment to a label.
1358 // FIXME: Diagnostics. Note the location of the definition as a label.
1359 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1360 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1361 ; // Allow redefinitions of undefined symbols only used in directives.
1362 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1363 return Error(EqualLoc, "redefinition of '" + Name + "'");
1364 else if (!Sym->isVariable())
1365 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1366 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1367 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1370 // Don't count these checks as uses.
1371 Sym->setUsed(false);
1373 Sym = getContext().GetOrCreateSymbol(Name);
1375 // FIXME: Handle '.'.
1377 // Do the assignment.
1378 Out.EmitAssignment(Sym, Value);
1383 /// ParseIdentifier:
1386 bool AsmParser::ParseIdentifier(StringRef &Res) {
1387 // The assembler has relaxed rules for accepting identifiers, in particular we
1388 // allow things like '.globl $foo', which would normally be separate
1389 // tokens. At this level, we have already lexed so we cannot (currently)
1390 // handle this as a context dependent token, instead we detect adjacent tokens
1391 // and return the combined identifier.
1392 if (Lexer.is(AsmToken::Dollar)) {
1393 SMLoc DollarLoc = getLexer().getLoc();
1395 // Consume the dollar sign, and check for a following identifier.
1397 if (Lexer.isNot(AsmToken::Identifier))
1400 // We have a '$' followed by an identifier, make sure they are adjacent.
1401 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1404 // Construct the joined identifier and consume the token.
1405 Res = StringRef(DollarLoc.getPointer(),
1406 getTok().getIdentifier().size() + 1);
1411 if (Lexer.isNot(AsmToken::Identifier) &&
1412 Lexer.isNot(AsmToken::String))
1415 Res = getTok().getIdentifier();
1417 Lex(); // Consume the identifier token.
1422 /// ParseDirectiveSet:
1423 /// ::= .equ identifier ',' expression
1424 /// ::= .equiv identifier ',' expression
1425 /// ::= .set identifier ',' expression
1426 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1429 if (ParseIdentifier(Name))
1430 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1432 if (getLexer().isNot(AsmToken::Comma))
1433 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1436 return ParseAssignment(Name, allow_redef);
1439 bool AsmParser::ParseEscapedString(std::string &Data) {
1440 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1443 StringRef Str = getTok().getStringContents();
1444 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1445 if (Str[i] != '\\') {
1450 // Recognize escaped characters. Note that this escape semantics currently
1451 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1454 return TokError("unexpected backslash at end of string");
1456 // Recognize octal sequences.
1457 if ((unsigned) (Str[i] - '0') <= 7) {
1458 // Consume up to three octal characters.
1459 unsigned Value = Str[i] - '0';
1461 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1463 Value = Value * 8 + (Str[i] - '0');
1465 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1467 Value = Value * 8 + (Str[i] - '0');
1472 return TokError("invalid octal escape sequence (out of range)");
1474 Data += (unsigned char) Value;
1478 // Otherwise recognize individual escapes.
1481 // Just reject invalid escape sequences for now.
1482 return TokError("invalid escape sequence (unrecognized character)");
1484 case 'b': Data += '\b'; break;
1485 case 'f': Data += '\f'; break;
1486 case 'n': Data += '\n'; break;
1487 case 'r': Data += '\r'; break;
1488 case 't': Data += '\t'; break;
1489 case '"': Data += '"'; break;
1490 case '\\': Data += '\\'; break;
1497 /// ParseDirectiveAscii:
1498 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1499 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1500 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1501 CheckForValidSection();
1504 if (getLexer().isNot(AsmToken::String))
1505 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1508 if (ParseEscapedString(Data))
1511 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1513 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1517 if (getLexer().is(AsmToken::EndOfStatement))
1520 if (getLexer().isNot(AsmToken::Comma))
1521 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1530 /// ParseDirectiveValue
1531 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1532 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1533 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1534 CheckForValidSection();
1537 const MCExpr *Value;
1538 if (ParseExpression(Value))
1541 // Special case constant expressions to match code generator.
1542 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1543 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1545 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1547 if (getLexer().is(AsmToken::EndOfStatement))
1550 // FIXME: Improve diagnostic.
1551 if (getLexer().isNot(AsmToken::Comma))
1552 return TokError("unexpected token in directive");
1561 /// ParseDirectiveRealValue
1562 /// ::= (.single | .double) [ expression (, expression)* ]
1563 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1564 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1565 CheckForValidSection();
1568 // We don't truly support arithmetic on floating point expressions, so we
1569 // have to manually parse unary prefixes.
1571 if (getLexer().is(AsmToken::Minus)) {
1574 } else if (getLexer().is(AsmToken::Plus))
1577 if (getLexer().isNot(AsmToken::Integer) &&
1578 getLexer().isNot(AsmToken::Real) &&
1579 getLexer().isNot(AsmToken::Identifier))
1580 return TokError("unexpected token in directive");
1582 // Convert to an APFloat.
1583 APFloat Value(Semantics);
1584 StringRef IDVal = getTok().getString();
1585 if (getLexer().is(AsmToken::Identifier)) {
1586 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1587 Value = APFloat::getInf(Semantics);
1588 else if (!IDVal.compare_lower("nan"))
1589 Value = APFloat::getNaN(Semantics, false, ~0);
1591 return TokError("invalid floating point literal");
1592 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1593 APFloat::opInvalidOp)
1594 return TokError("invalid floating point literal");
1598 // Consume the numeric token.
1601 // Emit the value as an integer.
1602 APInt AsInt = Value.bitcastToAPInt();
1603 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1604 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1606 if (getLexer().is(AsmToken::EndOfStatement))
1609 if (getLexer().isNot(AsmToken::Comma))
1610 return TokError("unexpected token in directive");
1619 /// ParseDirectiveSpace
1620 /// ::= .space expression [ , expression ]
1621 bool AsmParser::ParseDirectiveSpace() {
1622 CheckForValidSection();
1625 if (ParseAbsoluteExpression(NumBytes))
1628 int64_t FillExpr = 0;
1629 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1630 if (getLexer().isNot(AsmToken::Comma))
1631 return TokError("unexpected token in '.space' directive");
1634 if (ParseAbsoluteExpression(FillExpr))
1637 if (getLexer().isNot(AsmToken::EndOfStatement))
1638 return TokError("unexpected token in '.space' directive");
1644 return TokError("invalid number of bytes in '.space' directive");
1646 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1647 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1652 /// ParseDirectiveZero
1653 /// ::= .zero expression
1654 bool AsmParser::ParseDirectiveZero() {
1655 CheckForValidSection();
1658 if (ParseAbsoluteExpression(NumBytes))
1662 if (getLexer().is(AsmToken::Comma)) {
1664 if (ParseAbsoluteExpression(Val))
1668 if (getLexer().isNot(AsmToken::EndOfStatement))
1669 return TokError("unexpected token in '.zero' directive");
1673 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1678 /// ParseDirectiveFill
1679 /// ::= .fill expression , expression , expression
1680 bool AsmParser::ParseDirectiveFill() {
1681 CheckForValidSection();
1684 if (ParseAbsoluteExpression(NumValues))
1687 if (getLexer().isNot(AsmToken::Comma))
1688 return TokError("unexpected token in '.fill' directive");
1692 if (ParseAbsoluteExpression(FillSize))
1695 if (getLexer().isNot(AsmToken::Comma))
1696 return TokError("unexpected token in '.fill' directive");
1700 if (ParseAbsoluteExpression(FillExpr))
1703 if (getLexer().isNot(AsmToken::EndOfStatement))
1704 return TokError("unexpected token in '.fill' directive");
1708 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1709 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1711 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1712 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1717 /// ParseDirectiveOrg
1718 /// ::= .org expression [ , expression ]
1719 bool AsmParser::ParseDirectiveOrg() {
1720 CheckForValidSection();
1722 const MCExpr *Offset;
1723 if (ParseExpression(Offset))
1726 // Parse optional fill expression.
1727 int64_t FillExpr = 0;
1728 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1729 if (getLexer().isNot(AsmToken::Comma))
1730 return TokError("unexpected token in '.org' directive");
1733 if (ParseAbsoluteExpression(FillExpr))
1736 if (getLexer().isNot(AsmToken::EndOfStatement))
1737 return TokError("unexpected token in '.org' directive");
1742 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1743 // has to be relative to the current section.
1744 getStreamer().EmitValueToOffset(Offset, FillExpr);
1749 /// ParseDirectiveAlign
1750 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1751 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1752 CheckForValidSection();
1754 SMLoc AlignmentLoc = getLexer().getLoc();
1756 if (ParseAbsoluteExpression(Alignment))
1760 bool HasFillExpr = false;
1761 int64_t FillExpr = 0;
1762 int64_t MaxBytesToFill = 0;
1763 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1764 if (getLexer().isNot(AsmToken::Comma))
1765 return TokError("unexpected token in directive");
1768 // The fill expression can be omitted while specifying a maximum number of
1769 // alignment bytes, e.g:
1771 if (getLexer().isNot(AsmToken::Comma)) {
1773 if (ParseAbsoluteExpression(FillExpr))
1777 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1778 if (getLexer().isNot(AsmToken::Comma))
1779 return TokError("unexpected token in directive");
1782 MaxBytesLoc = getLexer().getLoc();
1783 if (ParseAbsoluteExpression(MaxBytesToFill))
1786 if (getLexer().isNot(AsmToken::EndOfStatement))
1787 return TokError("unexpected token in directive");
1796 // Compute alignment in bytes.
1798 // FIXME: Diagnose overflow.
1799 if (Alignment >= 32) {
1800 Error(AlignmentLoc, "invalid alignment value");
1804 Alignment = 1ULL << Alignment;
1807 // Diagnose non-sensical max bytes to align.
1808 if (MaxBytesLoc.isValid()) {
1809 if (MaxBytesToFill < 1) {
1810 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1811 "many bytes, ignoring maximum bytes expression");
1815 if (MaxBytesToFill >= Alignment) {
1816 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1822 // Check whether we should use optimal code alignment for this .align
1824 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1825 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1826 ValueSize == 1 && UseCodeAlign) {
1827 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1829 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1830 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1837 /// ParseDirectiveSymbolAttribute
1838 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1839 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1840 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1844 if (ParseIdentifier(Name))
1845 return TokError("expected identifier in directive");
1847 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1849 getStreamer().EmitSymbolAttribute(Sym, Attr);
1851 if (getLexer().is(AsmToken::EndOfStatement))
1854 if (getLexer().isNot(AsmToken::Comma))
1855 return TokError("unexpected token in directive");
1864 /// ParseDirectiveComm
1865 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1866 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1867 CheckForValidSection();
1869 SMLoc IDLoc = getLexer().getLoc();
1871 if (ParseIdentifier(Name))
1872 return TokError("expected identifier in directive");
1874 // Handle the identifier as the key symbol.
1875 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1877 if (getLexer().isNot(AsmToken::Comma))
1878 return TokError("unexpected token in directive");
1882 SMLoc SizeLoc = getLexer().getLoc();
1883 if (ParseAbsoluteExpression(Size))
1886 int64_t Pow2Alignment = 0;
1887 SMLoc Pow2AlignmentLoc;
1888 if (getLexer().is(AsmToken::Comma)) {
1890 Pow2AlignmentLoc = getLexer().getLoc();
1891 if (ParseAbsoluteExpression(Pow2Alignment))
1894 // If this target takes alignments in bytes (not log) validate and convert.
1895 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1896 if (!isPowerOf2_64(Pow2Alignment))
1897 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1898 Pow2Alignment = Log2_64(Pow2Alignment);
1902 if (getLexer().isNot(AsmToken::EndOfStatement))
1903 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1907 // NOTE: a size of zero for a .comm should create a undefined symbol
1908 // but a size of .lcomm creates a bss symbol of size zero.
1910 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1911 "be less than zero");
1913 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1914 // may internally end up wanting an alignment in bytes.
1915 // FIXME: Diagnose overflow.
1916 if (Pow2Alignment < 0)
1917 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1918 "alignment, can't be less than zero");
1920 if (!Sym->isUndefined())
1921 return Error(IDLoc, "invalid symbol redefinition");
1923 // '.lcomm' is equivalent to '.zerofill'.
1924 // Create the Symbol as a common or local common with Size and Pow2Alignment
1926 getStreamer().EmitZerofill(Ctx.getMachOSection(
1927 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1928 0, SectionKind::getBSS()),
1929 Sym, Size, 1 << Pow2Alignment);
1933 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1937 /// ParseDirectiveAbort
1938 /// ::= .abort [... message ...]
1939 bool AsmParser::ParseDirectiveAbort() {
1940 // FIXME: Use loc from directive.
1941 SMLoc Loc = getLexer().getLoc();
1943 StringRef Str = ParseStringToEndOfStatement();
1944 if (getLexer().isNot(AsmToken::EndOfStatement))
1945 return TokError("unexpected token in '.abort' directive");
1950 Error(Loc, ".abort detected. Assembly stopping.");
1952 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1953 // FIXME: Actually abort assembly here.
1958 /// ParseDirectiveInclude
1959 /// ::= .include "filename"
1960 bool AsmParser::ParseDirectiveInclude() {
1961 if (getLexer().isNot(AsmToken::String))
1962 return TokError("expected string in '.include' directive");
1964 std::string Filename = getTok().getString();
1965 SMLoc IncludeLoc = getLexer().getLoc();
1968 if (getLexer().isNot(AsmToken::EndOfStatement))
1969 return TokError("unexpected token in '.include' directive");
1971 // Strip the quotes.
1972 Filename = Filename.substr(1, Filename.size()-2);
1974 // Attempt to switch the lexer to the included file before consuming the end
1975 // of statement to avoid losing it when we switch.
1976 if (EnterIncludeFile(Filename)) {
1977 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1984 /// ParseDirectiveIf
1985 /// ::= .if expression
1986 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1987 TheCondStack.push_back(TheCondState);
1988 TheCondState.TheCond = AsmCond::IfCond;
1989 if(TheCondState.Ignore) {
1990 EatToEndOfStatement();
1994 if (ParseAbsoluteExpression(ExprValue))
1997 if (getLexer().isNot(AsmToken::EndOfStatement))
1998 return TokError("unexpected token in '.if' directive");
2002 TheCondState.CondMet = ExprValue;
2003 TheCondState.Ignore = !TheCondState.CondMet;
2009 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2011 TheCondStack.push_back(TheCondState);
2012 TheCondState.TheCond = AsmCond::IfCond;
2014 if (TheCondState.Ignore) {
2015 EatToEndOfStatement();
2017 if (ParseIdentifier(Name))
2018 return TokError("expected identifier after '.ifdef'");
2022 MCSymbol *Sym = getContext().LookupSymbol(Name);
2025 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2027 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2028 TheCondState.Ignore = !TheCondState.CondMet;
2034 /// ParseDirectiveElseIf
2035 /// ::= .elseif expression
2036 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2037 if (TheCondState.TheCond != AsmCond::IfCond &&
2038 TheCondState.TheCond != AsmCond::ElseIfCond)
2039 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2041 TheCondState.TheCond = AsmCond::ElseIfCond;
2043 bool LastIgnoreState = false;
2044 if (!TheCondStack.empty())
2045 LastIgnoreState = TheCondStack.back().Ignore;
2046 if (LastIgnoreState || TheCondState.CondMet) {
2047 TheCondState.Ignore = true;
2048 EatToEndOfStatement();
2052 if (ParseAbsoluteExpression(ExprValue))
2055 if (getLexer().isNot(AsmToken::EndOfStatement))
2056 return TokError("unexpected token in '.elseif' directive");
2059 TheCondState.CondMet = ExprValue;
2060 TheCondState.Ignore = !TheCondState.CondMet;
2066 /// ParseDirectiveElse
2068 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2069 if (getLexer().isNot(AsmToken::EndOfStatement))
2070 return TokError("unexpected token in '.else' directive");
2074 if (TheCondState.TheCond != AsmCond::IfCond &&
2075 TheCondState.TheCond != AsmCond::ElseIfCond)
2076 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2078 TheCondState.TheCond = AsmCond::ElseCond;
2079 bool LastIgnoreState = false;
2080 if (!TheCondStack.empty())
2081 LastIgnoreState = TheCondStack.back().Ignore;
2082 if (LastIgnoreState || TheCondState.CondMet)
2083 TheCondState.Ignore = true;
2085 TheCondState.Ignore = false;
2090 /// ParseDirectiveEndIf
2092 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2093 if (getLexer().isNot(AsmToken::EndOfStatement))
2094 return TokError("unexpected token in '.endif' directive");
2098 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2099 TheCondStack.empty())
2100 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2102 if (!TheCondStack.empty()) {
2103 TheCondState = TheCondStack.back();
2104 TheCondStack.pop_back();
2110 /// ParseDirectiveFile
2111 /// ::= .file [number] string
2112 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2113 // FIXME: I'm not sure what this is.
2114 int64_t FileNumber = -1;
2115 SMLoc FileNumberLoc = getLexer().getLoc();
2116 if (getLexer().is(AsmToken::Integer)) {
2117 FileNumber = getTok().getIntVal();
2121 return TokError("file number less than one");
2124 if (getLexer().isNot(AsmToken::String))
2125 return TokError("unexpected token in '.file' directive");
2127 StringRef Filename = getTok().getString();
2128 Filename = Filename.substr(1, Filename.size()-2);
2131 if (getLexer().isNot(AsmToken::EndOfStatement))
2132 return TokError("unexpected token in '.file' directive");
2134 if (FileNumber == -1)
2135 getStreamer().EmitFileDirective(Filename);
2137 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2138 Error(FileNumberLoc, "file number already allocated");
2144 /// ParseDirectiveLine
2145 /// ::= .line [number]
2146 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2147 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2148 if (getLexer().isNot(AsmToken::Integer))
2149 return TokError("unexpected token in '.line' directive");
2151 int64_t LineNumber = getTok().getIntVal();
2155 // FIXME: Do something with the .line.
2158 if (getLexer().isNot(AsmToken::EndOfStatement))
2159 return TokError("unexpected token in '.line' directive");
2165 /// ParseDirectiveLoc
2166 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2167 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2168 /// The first number is a file number, must have been previously assigned with
2169 /// a .file directive, the second number is the line number and optionally the
2170 /// third number is a column position (zero if not specified). The remaining
2171 /// optional items are .loc sub-directives.
2172 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2174 if (getLexer().isNot(AsmToken::Integer))
2175 return TokError("unexpected token in '.loc' directive");
2176 int64_t FileNumber = getTok().getIntVal();
2178 return TokError("file number less than one in '.loc' directive");
2179 if (!getContext().isValidDwarfFileNumber(FileNumber))
2180 return TokError("unassigned file number in '.loc' directive");
2183 int64_t LineNumber = 0;
2184 if (getLexer().is(AsmToken::Integer)) {
2185 LineNumber = getTok().getIntVal();
2187 return TokError("line number less than one in '.loc' directive");
2191 int64_t ColumnPos = 0;
2192 if (getLexer().is(AsmToken::Integer)) {
2193 ColumnPos = getTok().getIntVal();
2195 return TokError("column position less than zero in '.loc' directive");
2199 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2201 int64_t Discriminator = 0;
2202 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2204 if (getLexer().is(AsmToken::EndOfStatement))
2208 SMLoc Loc = getTok().getLoc();
2209 if (getParser().ParseIdentifier(Name))
2210 return TokError("unexpected token in '.loc' directive");
2212 if (Name == "basic_block")
2213 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2214 else if (Name == "prologue_end")
2215 Flags |= DWARF2_FLAG_PROLOGUE_END;
2216 else if (Name == "epilogue_begin")
2217 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2218 else if (Name == "is_stmt") {
2219 SMLoc Loc = getTok().getLoc();
2220 const MCExpr *Value;
2221 if (getParser().ParseExpression(Value))
2223 // The expression must be the constant 0 or 1.
2224 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2225 int Value = MCE->getValue();
2227 Flags &= ~DWARF2_FLAG_IS_STMT;
2228 else if (Value == 1)
2229 Flags |= DWARF2_FLAG_IS_STMT;
2231 return Error(Loc, "is_stmt value not 0 or 1");
2234 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2237 else if (Name == "isa") {
2238 SMLoc Loc = getTok().getLoc();
2239 const MCExpr *Value;
2240 if (getParser().ParseExpression(Value))
2242 // The expression must be a constant greater or equal to 0.
2243 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2244 int Value = MCE->getValue();
2246 return Error(Loc, "isa number less than zero");
2250 return Error(Loc, "isa number not a constant value");
2253 else if (Name == "discriminator") {
2254 if (getParser().ParseAbsoluteExpression(Discriminator))
2258 return Error(Loc, "unknown sub-directive in '.loc' directive");
2261 if (getLexer().is(AsmToken::EndOfStatement))
2266 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2267 Isa, Discriminator, StringRef());
2272 /// ParseDirectiveStabs
2273 /// ::= .stabs string, number, number, number
2274 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2275 SMLoc DirectiveLoc) {
2276 return TokError("unsupported directive '" + Directive + "'");
2279 /// ParseDirectiveCFISections
2280 /// ::= .cfi_sections section [, section]
2281 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2282 SMLoc DirectiveLoc) {
2287 if (getParser().ParseIdentifier(Name))
2288 return TokError("Expected an identifier");
2290 if (Name == ".eh_frame")
2292 else if (Name == ".debug_frame")
2295 if (getLexer().is(AsmToken::Comma)) {
2298 if (getParser().ParseIdentifier(Name))
2299 return TokError("Expected an identifier");
2301 if (Name == ".eh_frame")
2303 else if (Name == ".debug_frame")
2307 getStreamer().EmitCFISections(EH, Debug);
2312 /// ParseDirectiveCFIStartProc
2313 /// ::= .cfi_startproc
2314 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2315 SMLoc DirectiveLoc) {
2316 getStreamer().EmitCFIStartProc();
2320 /// ParseDirectiveCFIEndProc
2321 /// ::= .cfi_endproc
2322 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2323 getStreamer().EmitCFIEndProc();
2327 /// ParseRegisterOrRegisterNumber - parse register name or number.
2328 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2329 SMLoc DirectiveLoc) {
2332 if (getLexer().is(AsmToken::Percent)) {
2333 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2336 Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2338 return getParser().ParseAbsoluteExpression(Register);
2343 /// ParseDirectiveCFIDefCfa
2344 /// ::= .cfi_def_cfa register, offset
2345 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2346 SMLoc DirectiveLoc) {
2347 int64_t Register = 0;
2348 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2351 if (getLexer().isNot(AsmToken::Comma))
2352 return TokError("unexpected token in directive");
2356 if (getParser().ParseAbsoluteExpression(Offset))
2359 getStreamer().EmitCFIDefCfa(Register, Offset);
2363 /// ParseDirectiveCFIDefCfaOffset
2364 /// ::= .cfi_def_cfa_offset offset
2365 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2366 SMLoc DirectiveLoc) {
2368 if (getParser().ParseAbsoluteExpression(Offset))
2371 getStreamer().EmitCFIDefCfaOffset(Offset);
2375 /// ParseDirectiveCFIAdjustCfaOffset
2376 /// ::= .cfi_adjust_cfa_offset adjustment
2377 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2378 SMLoc DirectiveLoc) {
2379 int64_t Adjustment = 0;
2380 if (getParser().ParseAbsoluteExpression(Adjustment))
2383 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2387 /// ParseDirectiveCFIDefCfaRegister
2388 /// ::= .cfi_def_cfa_register register
2389 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2390 SMLoc DirectiveLoc) {
2391 int64_t Register = 0;
2392 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2395 getStreamer().EmitCFIDefCfaRegister(Register);
2399 /// ParseDirectiveCFIOffset
2400 /// ::= .cfi_offset register, offset
2401 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2402 int64_t Register = 0;
2405 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2408 if (getLexer().isNot(AsmToken::Comma))
2409 return TokError("unexpected token in directive");
2412 if (getParser().ParseAbsoluteExpression(Offset))
2415 getStreamer().EmitCFIOffset(Register, Offset);
2419 /// ParseDirectiveCFIRelOffset
2420 /// ::= .cfi_rel_offset register, offset
2421 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2422 SMLoc DirectiveLoc) {
2423 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().EmitCFIRelOffset(Register, Offset);
2440 static bool isValidEncoding(int64_t Encoding) {
2441 if (Encoding & ~0xff)
2444 if (Encoding == dwarf::DW_EH_PE_omit)
2447 const unsigned Format = Encoding & 0xf;
2448 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2449 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2450 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2451 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2454 const unsigned Application = Encoding & 0x70;
2455 if (Application != dwarf::DW_EH_PE_absptr &&
2456 Application != dwarf::DW_EH_PE_pcrel)
2462 /// ParseDirectiveCFIPersonalityOrLsda
2463 /// ::= .cfi_personality encoding, [symbol_name]
2464 /// ::= .cfi_lsda encoding, [symbol_name]
2465 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2466 SMLoc DirectiveLoc) {
2467 int64_t Encoding = 0;
2468 if (getParser().ParseAbsoluteExpression(Encoding))
2470 if (Encoding == dwarf::DW_EH_PE_omit)
2473 if (!isValidEncoding(Encoding))
2474 return TokError("unsupported encoding.");
2476 if (getLexer().isNot(AsmToken::Comma))
2477 return TokError("unexpected token in directive");
2481 if (getParser().ParseIdentifier(Name))
2482 return TokError("expected identifier in directive");
2484 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2486 if (IDVal == ".cfi_personality")
2487 getStreamer().EmitCFIPersonality(Sym, Encoding);
2489 assert(IDVal == ".cfi_lsda");
2490 getStreamer().EmitCFILsda(Sym, Encoding);
2495 /// ParseDirectiveCFIRememberState
2496 /// ::= .cfi_remember_state
2497 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2498 SMLoc DirectiveLoc) {
2499 getStreamer().EmitCFIRememberState();
2503 /// ParseDirectiveCFIRestoreState
2504 /// ::= .cfi_remember_state
2505 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2506 SMLoc DirectiveLoc) {
2507 getStreamer().EmitCFIRestoreState();
2511 /// ParseDirectiveCFISameValue
2512 /// ::= .cfi_same_value register
2513 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2514 SMLoc DirectiveLoc) {
2515 int64_t Register = 0;
2517 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2520 getStreamer().EmitCFISameValue(Register);
2525 /// ParseDirectiveMacrosOnOff
2528 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2529 SMLoc DirectiveLoc) {
2530 if (getLexer().isNot(AsmToken::EndOfStatement))
2531 return Error(getLexer().getLoc(),
2532 "unexpected token in '" + Directive + "' directive");
2534 getParser().MacrosEnabled = Directive == ".macros_on";
2539 /// ParseDirectiveMacro
2541 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2542 SMLoc DirectiveLoc) {
2544 if (getParser().ParseIdentifier(Name))
2545 return TokError("expected identifier in directive");
2547 if (getLexer().isNot(AsmToken::EndOfStatement))
2548 return TokError("unexpected token in '.macro' directive");
2550 // Eat the end of statement.
2553 AsmToken EndToken, StartToken = getTok();
2555 // Lex the macro definition.
2557 // Check whether we have reached the end of the file.
2558 if (getLexer().is(AsmToken::Eof))
2559 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2561 // Otherwise, check whether we have reach the .endmacro.
2562 if (getLexer().is(AsmToken::Identifier) &&
2563 (getTok().getIdentifier() == ".endm" ||
2564 getTok().getIdentifier() == ".endmacro")) {
2565 EndToken = getTok();
2567 if (getLexer().isNot(AsmToken::EndOfStatement))
2568 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2573 // Otherwise, scan til the end of the statement.
2574 getParser().EatToEndOfStatement();
2577 if (getParser().MacroMap.lookup(Name)) {
2578 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2581 const char *BodyStart = StartToken.getLoc().getPointer();
2582 const char *BodyEnd = EndToken.getLoc().getPointer();
2583 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2584 getParser().MacroMap[Name] = new Macro(Name, Body);
2588 /// ParseDirectiveEndMacro
2591 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2592 SMLoc DirectiveLoc) {
2593 if (getLexer().isNot(AsmToken::EndOfStatement))
2594 return TokError("unexpected token in '" + Directive + "' directive");
2596 // If we are inside a macro instantiation, terminate the current
2598 if (!getParser().ActiveMacros.empty()) {
2599 getParser().HandleMacroExit();
2603 // Otherwise, this .endmacro is a stray entry in the file; well formed
2604 // .endmacro directives are handled during the macro definition parsing.
2605 return TokError("unexpected '" + Directive + "' in file, "
2606 "no current macro definition");
2609 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2610 getParser().CheckForValidSection();
2612 const MCExpr *Value;
2614 if (getParser().ParseExpression(Value))
2617 if (getLexer().isNot(AsmToken::EndOfStatement))
2618 return TokError("unexpected token in directive");
2620 if (DirName[1] == 's')
2621 getStreamer().EmitSLEB128Value(Value);
2623 getStreamer().EmitULEB128Value(Value);
2629 /// \brief Create an MCAsmParser instance.
2630 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2631 MCContext &C, MCStreamer &Out,
2632 const MCAsmInfo &MAI) {
2633 return new AsmParser(T, SM, C, Out, MAI);