1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCDwarf.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetAsmParser.h"
41 /// \brief Helper class for tracking macro definitions.
47 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
50 /// \brief Helper class for storing information about an active macro
52 struct MacroInstantiation {
53 /// The macro being instantiated.
54 const Macro *TheMacro;
56 /// The macro instantiation with substitutions.
57 MemoryBuffer *Instantiation;
59 /// The location of the instantiation.
60 SMLoc InstantiationLoc;
62 /// The location where parsing should resume upon instantiation completion.
66 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
67 const std::vector<std::vector<AsmToken> > &A);
70 /// \brief The concrete assembly parser instance.
71 class AsmParser : public MCAsmParser {
72 friend class GenericAsmParser;
74 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
75 void operator=(const AsmParser &); // DO NOT IMPLEMENT
81 MCAsmParserExtension *GenericParser;
82 MCAsmParserExtension *PlatformParser;
84 /// This is the current buffer index we're lexing from as managed by the
89 std::vector<AsmCond> TheCondStack;
91 /// DirectiveMap - This is a table handlers for directives. Each handler is
92 /// invoked after the directive identifier is read and is responsible for
93 /// parsing and validating the rest of the directive. The handler is passed
94 /// in the directive name and the location of the directive keyword.
95 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
97 /// MacroMap - Map of currently defined macros.
98 StringMap<Macro*> MacroMap;
100 /// ActiveMacros - Stack of active macro instantiations.
101 std::vector<MacroInstantiation*> ActiveMacros;
103 /// Boolean tracking whether macro substitution is enabled.
104 unsigned MacrosEnabled : 1;
106 /// Flag tracking whether any errors have been encountered.
107 unsigned HadError : 1;
110 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
111 const MCAsmInfo &MAI);
114 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
116 void AddDirectiveHandler(MCAsmParserExtension *Object,
118 DirectiveHandler Handler) {
119 DirectiveMap[Directive] = std::make_pair(Object, Handler);
123 /// @name MCAsmParser Interface
126 virtual SourceMgr &getSourceManager() { return SrcMgr; }
127 virtual MCAsmLexer &getLexer() { return Lexer; }
128 virtual MCContext &getContext() { return Ctx; }
129 virtual MCStreamer &getStreamer() { return Out; }
131 virtual void Warning(SMLoc L, const Twine &Meg);
132 virtual bool Error(SMLoc L, const Twine &Msg);
134 const AsmToken &Lex();
136 bool ParseExpression(const MCExpr *&Res);
137 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
138 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
139 virtual bool ParseAbsoluteExpression(int64_t &Res);
144 void CheckForValidSection();
146 bool ParseStatement();
148 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
149 void HandleMacroExit();
151 void PrintMacroInstantiations();
152 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
153 SrcMgr.PrintMessage(Loc, Msg, Type);
156 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
157 bool EnterIncludeFile(const std::string &Filename);
159 /// \brief Reset the current lexer position to that given by \arg Loc. The
160 /// current token is not set; clients should ensure Lex() is called
162 void JumpToLoc(SMLoc Loc);
164 void EatToEndOfStatement();
166 /// \brief Parse up to the end of statement and a return the contents from the
167 /// current token until the end of the statement; the current token on exit
168 /// will be either the EndOfStatement or EOF.
169 StringRef ParseStringToEndOfStatement();
171 bool ParseAssignment(StringRef Name, bool allow_redef);
173 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
174 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
175 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
176 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
178 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
179 /// and set \arg Res to the identifier contents.
180 bool ParseIdentifier(StringRef &Res);
182 // Directive Parsing.
184 // ".ascii", ".asciiz", ".string"
185 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
186 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
187 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
188 bool ParseDirectiveFill(); // ".fill"
189 bool ParseDirectiveSpace(); // ".space"
190 bool ParseDirectiveZero(); // ".zero"
191 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
192 bool ParseDirectiveOrg(); // ".org"
193 // ".align{,32}", ".p2align{,w,l}"
194 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
196 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
197 /// accepts a single symbol (which should be a label or an external).
198 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
200 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
202 bool ParseDirectiveAbort(); // ".abort"
203 bool ParseDirectiveInclude(); // ".include"
205 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
206 // ".ifdef" or ".ifndef", depending on expect_defined
207 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
208 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
209 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
210 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
212 /// ParseEscapedString - Parse the current token as a string which may include
213 /// escaped characters and return the string contents.
214 bool ParseEscapedString(std::string &Data);
216 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
217 MCSymbolRefExpr::VariantKind Variant);
220 /// \brief Generic implementations of directive handling, etc. which is shared
221 /// (or the default, at least) for all assembler parser.
222 class GenericAsmParser : public MCAsmParserExtension {
223 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
224 void AddDirectiveHandler(StringRef Directive) {
225 getParser().AddDirectiveHandler(this, Directive,
226 HandleDirective<GenericAsmParser, Handler>);
229 GenericAsmParser() {}
231 AsmParser &getParser() {
232 return (AsmParser&) this->MCAsmParserExtension::getParser();
235 virtual void Initialize(MCAsmParser &Parser) {
236 // Call the base implementation.
237 this->MCAsmParserExtension::Initialize(Parser);
239 // Debugging directives.
240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
241 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
242 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
243 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
246 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
248 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
250 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
252 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
254 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
255 ".cfi_def_cfa_offset");
256 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
257 ".cfi_adjust_cfa_offset");
258 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
259 ".cfi_def_cfa_register");
260 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
262 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
265 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
267 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
269 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
271 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
273 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
278 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
280 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
281 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
282 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
285 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
288 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
290 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
291 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
292 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
293 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
294 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
295 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
296 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
297 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
298 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
299 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
300 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
301 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
302 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
303 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
304 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
305 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
306 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
308 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
309 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
310 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
312 bool ParseDirectiveLEB128(StringRef, SMLoc);
319 extern MCAsmParserExtension *createDarwinAsmParser();
320 extern MCAsmParserExtension *createELFAsmParser();
321 extern MCAsmParserExtension *createCOFFAsmParser();
325 enum { DEFAULT_ADDRSPACE = 0 };
327 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
328 MCStreamer &_Out, const MCAsmInfo &_MAI)
329 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
330 GenericParser(new GenericAsmParser), PlatformParser(0),
331 CurBuffer(0), MacrosEnabled(true) {
332 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
334 // Initialize the generic parser.
335 GenericParser->Initialize(*this);
337 // Initialize the platform / file format parser.
339 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
341 if (_MAI.hasMicrosoftFastStdCallMangling()) {
342 PlatformParser = createCOFFAsmParser();
343 PlatformParser->Initialize(*this);
344 } else if (_MAI.hasSubsectionsViaSymbols()) {
345 PlatformParser = createDarwinAsmParser();
346 PlatformParser->Initialize(*this);
348 PlatformParser = createELFAsmParser();
349 PlatformParser->Initialize(*this);
353 AsmParser::~AsmParser() {
354 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
356 // Destroy any macros.
357 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
358 ie = MacroMap.end(); it != ie; ++it)
359 delete it->getValue();
361 delete PlatformParser;
362 delete GenericParser;
365 void AsmParser::PrintMacroInstantiations() {
366 // Print the active macro instantiation stack.
367 for (std::vector<MacroInstantiation*>::const_reverse_iterator
368 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
369 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
373 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
374 PrintMessage(L, Msg, "warning");
375 PrintMacroInstantiations();
378 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
380 PrintMessage(L, Msg, "error");
381 PrintMacroInstantiations();
385 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
386 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
392 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
397 void AsmParser::JumpToLoc(SMLoc Loc) {
398 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
399 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
402 const AsmToken &AsmParser::Lex() {
403 const AsmToken *tok = &Lexer.Lex();
405 if (tok->is(AsmToken::Eof)) {
406 // If this is the end of an included file, pop the parent file off the
408 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
409 if (ParentIncludeLoc != SMLoc()) {
410 JumpToLoc(ParentIncludeLoc);
415 if (tok->is(AsmToken::Error))
416 Error(Lexer.getErrLoc(), Lexer.getErr());
421 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
422 // Create the initial section, if requested.
423 if (!NoInitialTextSection)
430 AsmCond StartingCondState = TheCondState;
432 // While we have input, parse each statement.
433 while (Lexer.isNot(AsmToken::Eof)) {
434 if (!ParseStatement()) continue;
436 // We had an error, validate that one was emitted and recover by skipping to
438 assert(HadError && "Parse statement returned an error, but none emitted!");
439 EatToEndOfStatement();
442 if (TheCondState.TheCond != StartingCondState.TheCond ||
443 TheCondState.Ignore != StartingCondState.Ignore)
444 return TokError("unmatched .ifs or .elses");
446 // Check to see there are no empty DwarfFile slots.
447 const std::vector<MCDwarfFile *> &MCDwarfFiles =
448 getContext().getMCDwarfFiles();
449 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
450 if (!MCDwarfFiles[i])
451 TokError("unassigned file number: " + Twine(i) + " for .file directives");
454 // Finalize the output stream if there are no errors and if the client wants
456 if (!HadError && !NoFinalize)
462 void AsmParser::CheckForValidSection() {
463 if (!getStreamer().getCurrentSection()) {
464 TokError("expected section directive before assembly directive");
465 Out.SwitchSection(Ctx.getMachOSection(
467 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
468 0, SectionKind::getText()));
472 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
473 void AsmParser::EatToEndOfStatement() {
474 while (Lexer.isNot(AsmToken::EndOfStatement) &&
475 Lexer.isNot(AsmToken::Eof))
479 if (Lexer.is(AsmToken::EndOfStatement))
483 StringRef AsmParser::ParseStringToEndOfStatement() {
484 const char *Start = getTok().getLoc().getPointer();
486 while (Lexer.isNot(AsmToken::EndOfStatement) &&
487 Lexer.isNot(AsmToken::Eof))
490 const char *End = getTok().getLoc().getPointer();
491 return StringRef(Start, End - Start);
494 /// ParseParenExpr - Parse a paren expression and return it.
495 /// NOTE: This assumes the leading '(' has already been consumed.
497 /// parenexpr ::= expr)
499 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
500 if (ParseExpression(Res)) return true;
501 if (Lexer.isNot(AsmToken::RParen))
502 return TokError("expected ')' in parentheses expression");
503 EndLoc = Lexer.getLoc();
508 /// ParseBracketExpr - Parse a bracket expression and return it.
509 /// NOTE: This assumes the leading '[' has already been consumed.
511 /// bracketexpr ::= expr]
513 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
514 if (ParseExpression(Res)) return true;
515 if (Lexer.isNot(AsmToken::RBrac))
516 return TokError("expected ']' in brackets expression");
517 EndLoc = Lexer.getLoc();
522 /// ParsePrimaryExpr - Parse a primary expression and return it.
523 /// primaryexpr ::= (parenexpr
524 /// primaryexpr ::= symbol
525 /// primaryexpr ::= number
526 /// primaryexpr ::= '.'
527 /// primaryexpr ::= ~,+,- primaryexpr
528 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
529 switch (Lexer.getKind()) {
531 return TokError("unknown token in expression");
532 // If we have an error assume that we've already handled it.
533 case AsmToken::Error:
535 case AsmToken::Exclaim:
536 Lex(); // Eat the operator.
537 if (ParsePrimaryExpr(Res, EndLoc))
539 Res = MCUnaryExpr::CreateLNot(Res, getContext());
541 case AsmToken::Dollar:
542 case AsmToken::String:
543 case AsmToken::Identifier: {
544 EndLoc = Lexer.getLoc();
546 StringRef Identifier;
547 if (ParseIdentifier(Identifier))
550 // This is a symbol reference.
551 std::pair<StringRef, StringRef> Split = Identifier.split('@');
552 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
554 // Lookup the symbol variant if used.
555 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
556 if (Split.first.size() != Identifier.size()) {
557 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
558 if (Variant == MCSymbolRefExpr::VK_Invalid) {
559 Variant = MCSymbolRefExpr::VK_None;
560 return TokError("invalid variant '" + Split.second + "'");
564 // If this is an absolute variable reference, substitute it now to preserve
565 // semantics in the face of reassignment.
566 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
568 return Error(EndLoc, "unexpected modifier on variable reference");
570 Res = Sym->getVariableValue();
574 // Otherwise create a symbol ref.
575 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
578 case AsmToken::Integer: {
579 SMLoc Loc = getTok().getLoc();
580 int64_t IntVal = getTok().getIntVal();
581 Res = MCConstantExpr::Create(IntVal, getContext());
582 EndLoc = Lexer.getLoc();
584 // Look for 'b' or 'f' following an Integer as a directional label
585 if (Lexer.getKind() == AsmToken::Identifier) {
586 StringRef IDVal = getTok().getString();
587 if (IDVal == "f" || IDVal == "b"){
588 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
589 IDVal == "f" ? 1 : 0);
590 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
592 if(IDVal == "b" && Sym->isUndefined())
593 return Error(Loc, "invalid reference to undefined symbol");
594 EndLoc = Lexer.getLoc();
595 Lex(); // Eat identifier.
600 case AsmToken::Real: {
601 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
602 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
603 Res = MCConstantExpr::Create(IntVal, getContext());
607 case AsmToken::Dot: {
608 // This is a '.' reference, which references the current PC. Emit a
609 // temporary label to the streamer and refer to it.
610 MCSymbol *Sym = Ctx.CreateTempSymbol();
612 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
613 EndLoc = Lexer.getLoc();
614 Lex(); // Eat identifier.
617 case AsmToken::LParen:
618 Lex(); // Eat the '('.
619 return ParseParenExpr(Res, EndLoc);
620 case AsmToken::LBrac:
621 if (!PlatformParser->HasBracketExpressions())
622 return TokError("brackets expression not supported on this target");
623 Lex(); // Eat the '['.
624 return ParseBracketExpr(Res, EndLoc);
625 case AsmToken::Minus:
626 Lex(); // Eat the operator.
627 if (ParsePrimaryExpr(Res, EndLoc))
629 Res = MCUnaryExpr::CreateMinus(Res, getContext());
632 Lex(); // Eat the operator.
633 if (ParsePrimaryExpr(Res, EndLoc))
635 Res = MCUnaryExpr::CreatePlus(Res, getContext());
637 case AsmToken::Tilde:
638 Lex(); // Eat the operator.
639 if (ParsePrimaryExpr(Res, EndLoc))
641 Res = MCUnaryExpr::CreateNot(Res, getContext());
646 bool AsmParser::ParseExpression(const MCExpr *&Res) {
648 return ParseExpression(Res, EndLoc);
652 AsmParser::ApplyModifierToExpr(const MCExpr *E,
653 MCSymbolRefExpr::VariantKind Variant) {
654 // Recurse over the given expression, rebuilding it to apply the given variant
655 // if there is exactly one symbol.
656 switch (E->getKind()) {
658 case MCExpr::Constant:
661 case MCExpr::SymbolRef: {
662 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
664 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
665 TokError("invalid variant on expression '" +
666 getTok().getIdentifier() + "' (already modified)");
670 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
673 case MCExpr::Unary: {
674 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
675 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
678 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
681 case MCExpr::Binary: {
682 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
683 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
684 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
689 if (!LHS) LHS = BE->getLHS();
690 if (!RHS) RHS = BE->getRHS();
692 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
696 assert(0 && "Invalid expression kind!");
700 /// ParseExpression - Parse an expression and return it.
702 /// expr ::= expr +,- expr -> lowest.
703 /// expr ::= expr |,^,&,! expr -> middle.
704 /// expr ::= expr *,/,%,<<,>> expr -> highest.
705 /// expr ::= primaryexpr
707 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
708 // Parse the expression.
710 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
713 // As a special case, we support 'a op b @ modifier' by rewriting the
714 // expression to include the modifier. This is inefficient, but in general we
715 // expect users to use 'a@modifier op b'.
716 if (Lexer.getKind() == AsmToken::At) {
719 if (Lexer.isNot(AsmToken::Identifier))
720 return TokError("unexpected symbol modifier following '@'");
722 MCSymbolRefExpr::VariantKind Variant =
723 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
724 if (Variant == MCSymbolRefExpr::VK_Invalid)
725 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
727 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
729 return TokError("invalid modifier '" + getTok().getIdentifier() +
730 "' (no symbols present)");
738 // Try to constant fold it up front, if possible.
740 if (Res->EvaluateAsAbsolute(Value))
741 Res = MCConstantExpr::Create(Value, getContext());
746 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
748 return ParseParenExpr(Res, EndLoc) ||
749 ParseBinOpRHS(1, Res, EndLoc);
752 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
755 SMLoc StartLoc = Lexer.getLoc();
756 if (ParseExpression(Expr))
759 if (!Expr->EvaluateAsAbsolute(Res))
760 return Error(StartLoc, "expected absolute expression");
765 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
766 MCBinaryExpr::Opcode &Kind) {
769 return 0; // not a binop.
771 // Lowest Precedence: &&, ||, @
772 case AsmToken::AmpAmp:
773 Kind = MCBinaryExpr::LAnd;
775 case AsmToken::PipePipe:
776 Kind = MCBinaryExpr::LOr;
780 // Low Precedence: |, &, ^
782 // FIXME: gas seems to support '!' as an infix operator?
784 Kind = MCBinaryExpr::Or;
786 case AsmToken::Caret:
787 Kind = MCBinaryExpr::Xor;
790 Kind = MCBinaryExpr::And;
793 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
794 case AsmToken::EqualEqual:
795 Kind = MCBinaryExpr::EQ;
797 case AsmToken::ExclaimEqual:
798 case AsmToken::LessGreater:
799 Kind = MCBinaryExpr::NE;
802 Kind = MCBinaryExpr::LT;
804 case AsmToken::LessEqual:
805 Kind = MCBinaryExpr::LTE;
807 case AsmToken::Greater:
808 Kind = MCBinaryExpr::GT;
810 case AsmToken::GreaterEqual:
811 Kind = MCBinaryExpr::GTE;
814 // High Intermediate Precedence: +, -
816 Kind = MCBinaryExpr::Add;
818 case AsmToken::Minus:
819 Kind = MCBinaryExpr::Sub;
822 // Highest Precedence: *, /, %, <<, >>
824 Kind = MCBinaryExpr::Mul;
826 case AsmToken::Slash:
827 Kind = MCBinaryExpr::Div;
829 case AsmToken::Percent:
830 Kind = MCBinaryExpr::Mod;
832 case AsmToken::LessLess:
833 Kind = MCBinaryExpr::Shl;
835 case AsmToken::GreaterGreater:
836 Kind = MCBinaryExpr::Shr;
842 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
843 /// Res contains the LHS of the expression on input.
844 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
847 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
848 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
850 // If the next token is lower precedence than we are allowed to eat, return
851 // successfully with what we ate already.
852 if (TokPrec < Precedence)
857 // Eat the next primary expression.
859 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
861 // If BinOp binds less tightly with RHS than the operator after RHS, let
862 // the pending operator take RHS as its LHS.
863 MCBinaryExpr::Opcode Dummy;
864 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
865 if (TokPrec < NextTokPrec) {
866 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
869 // Merge LHS and RHS according to operator.
870 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
878 /// ::= EndOfStatement
879 /// ::= Label* Directive ...Operands... EndOfStatement
880 /// ::= Label* Identifier OperandList* EndOfStatement
881 bool AsmParser::ParseStatement() {
882 if (Lexer.is(AsmToken::EndOfStatement)) {
888 // Statements always start with an identifier or are a full line comment.
889 AsmToken ID = getTok();
890 SMLoc IDLoc = ID.getLoc();
892 int64_t LocalLabelVal = -1;
893 // A full line comment is a '#' as the first token.
894 if (Lexer.is(AsmToken::Hash)) {
895 EatToEndOfStatement();
899 // Allow an integer followed by a ':' as a directional local label.
900 if (Lexer.is(AsmToken::Integer)) {
901 LocalLabelVal = getTok().getIntVal();
902 if (LocalLabelVal < 0) {
903 if (!TheCondState.Ignore)
904 return TokError("unexpected token at start of statement");
908 IDVal = getTok().getString();
909 Lex(); // Consume the integer token to be used as an identifier token.
910 if (Lexer.getKind() != AsmToken::Colon) {
911 if (!TheCondState.Ignore)
912 return TokError("unexpected token at start of statement");
916 } else if (Lexer.is(AsmToken::Dot)) {
917 // Treat '.' as a valid identifier in this context.
921 } else if (ParseIdentifier(IDVal)) {
922 if (!TheCondState.Ignore)
923 return TokError("unexpected token at start of statement");
928 // Handle conditional assembly here before checking for skipping. We
929 // have to do this so that .endif isn't skipped in a ".if 0" block for
932 return ParseDirectiveIf(IDLoc);
933 if (IDVal == ".ifdef")
934 return ParseDirectiveIfdef(IDLoc, true);
935 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
936 return ParseDirectiveIfdef(IDLoc, false);
937 if (IDVal == ".elseif")
938 return ParseDirectiveElseIf(IDLoc);
939 if (IDVal == ".else")
940 return ParseDirectiveElse(IDLoc);
941 if (IDVal == ".endif")
942 return ParseDirectiveEndIf(IDLoc);
944 // If we are in a ".if 0" block, ignore this statement.
945 if (TheCondState.Ignore) {
946 EatToEndOfStatement();
950 // FIXME: Recurse on local labels?
952 // See what kind of statement we have.
953 switch (Lexer.getKind()) {
954 case AsmToken::Colon: {
955 CheckForValidSection();
957 // identifier ':' -> Label.
960 // Diagnose attempt to use '.' as a label.
962 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
964 // Diagnose attempt to use a variable as a label.
966 // FIXME: Diagnostics. Note the location of the definition as a label.
967 // FIXME: This doesn't diagnose assignment to a symbol which has been
968 // implicitly marked as external.
970 if (LocalLabelVal == -1)
971 Sym = getContext().GetOrCreateSymbol(IDVal);
973 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
974 if (!Sym->isUndefined() || Sym->isVariable())
975 return Error(IDLoc, "invalid symbol redefinition");
980 // Consume any end of statement token, if present, to avoid spurious
981 // AddBlankLine calls().
982 if (Lexer.is(AsmToken::EndOfStatement)) {
984 if (Lexer.is(AsmToken::Eof))
988 return ParseStatement();
991 case AsmToken::Equal:
992 // identifier '=' ... -> assignment statement
995 return ParseAssignment(IDVal, true);
997 default: // Normal instruction or directive.
1001 // If macros are enabled, check to see if this is a macro instantiation.
1003 if (const Macro *M = MacroMap.lookup(IDVal))
1004 return HandleMacroEntry(IDVal, IDLoc, M);
1006 // Otherwise, we have a normal instruction or directive.
1007 if (IDVal[0] == '.' && IDVal != ".") {
1008 // Assembler features
1009 if (IDVal == ".set" || IDVal == ".equ")
1010 return ParseDirectiveSet(IDVal, true);
1011 if (IDVal == ".equiv")
1012 return ParseDirectiveSet(IDVal, false);
1016 if (IDVal == ".ascii")
1017 return ParseDirectiveAscii(IDVal, false);
1018 if (IDVal == ".asciz" || IDVal == ".string")
1019 return ParseDirectiveAscii(IDVal, true);
1021 if (IDVal == ".byte")
1022 return ParseDirectiveValue(1);
1023 if (IDVal == ".short")
1024 return ParseDirectiveValue(2);
1025 if (IDVal == ".value")
1026 return ParseDirectiveValue(2);
1027 if (IDVal == ".2byte")
1028 return ParseDirectiveValue(2);
1029 if (IDVal == ".long")
1030 return ParseDirectiveValue(4);
1031 if (IDVal == ".int")
1032 return ParseDirectiveValue(4);
1033 if (IDVal == ".4byte")
1034 return ParseDirectiveValue(4);
1035 if (IDVal == ".quad")
1036 return ParseDirectiveValue(8);
1037 if (IDVal == ".8byte")
1038 return ParseDirectiveValue(8);
1039 if (IDVal == ".single" || IDVal == ".float")
1040 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1041 if (IDVal == ".double")
1042 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1044 if (IDVal == ".align") {
1045 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1046 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1048 if (IDVal == ".align32") {
1049 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1050 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1052 if (IDVal == ".balign")
1053 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1054 if (IDVal == ".balignw")
1055 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1056 if (IDVal == ".balignl")
1057 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1058 if (IDVal == ".p2align")
1059 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1060 if (IDVal == ".p2alignw")
1061 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1062 if (IDVal == ".p2alignl")
1063 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1065 if (IDVal == ".org")
1066 return ParseDirectiveOrg();
1068 if (IDVal == ".fill")
1069 return ParseDirectiveFill();
1070 if (IDVal == ".space" || IDVal == ".skip")
1071 return ParseDirectiveSpace();
1072 if (IDVal == ".zero")
1073 return ParseDirectiveZero();
1075 // Symbol attribute directives
1077 if (IDVal == ".globl" || IDVal == ".global")
1078 return ParseDirectiveSymbolAttribute(MCSA_Global);
1079 // ELF only? Should it be here?
1080 if (IDVal == ".local")
1081 return ParseDirectiveSymbolAttribute(MCSA_Local);
1082 if (IDVal == ".hidden")
1083 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1084 if (IDVal == ".indirect_symbol")
1085 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1086 if (IDVal == ".internal")
1087 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1088 if (IDVal == ".lazy_reference")
1089 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1090 if (IDVal == ".no_dead_strip")
1091 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1092 if (IDVal == ".symbol_resolver")
1093 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1094 if (IDVal == ".private_extern")
1095 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1096 if (IDVal == ".protected")
1097 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1098 if (IDVal == ".reference")
1099 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1100 if (IDVal == ".weak")
1101 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1102 if (IDVal == ".weak_definition")
1103 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1104 if (IDVal == ".weak_reference")
1105 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1106 if (IDVal == ".weak_def_can_be_hidden")
1107 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1109 if (IDVal == ".comm")
1110 return ParseDirectiveComm(/*IsLocal=*/false);
1111 if (IDVal == ".lcomm")
1112 return ParseDirectiveComm(/*IsLocal=*/true);
1114 if (IDVal == ".abort")
1115 return ParseDirectiveAbort();
1116 if (IDVal == ".include")
1117 return ParseDirectiveInclude();
1119 if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1120 return TokError(Twine(IDVal) + " not supported yet");
1122 // Look up the handler in the handler table.
1123 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1124 DirectiveMap.lookup(IDVal);
1126 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1128 // Target hook for parsing target specific directives.
1129 if (!getTargetParser().ParseDirective(ID))
1132 Warning(IDLoc, "ignoring directive for now");
1133 EatToEndOfStatement();
1137 CheckForValidSection();
1139 // Canonicalize the opcode to lower case.
1140 SmallString<128> Opcode;
1141 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1142 Opcode.push_back(tolower(IDVal[i]));
1144 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1145 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1148 // Dump the parsed representation, if requested.
1149 if (getShowParsedOperands()) {
1150 SmallString<256> Str;
1151 raw_svector_ostream OS(Str);
1152 OS << "parsed instruction: [";
1153 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1156 ParsedOperands[i]->dump(OS);
1160 PrintMessage(IDLoc, OS.str(), "note");
1163 // If parsing succeeded, match the instruction.
1165 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1168 // Free any parsed operands.
1169 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1170 delete ParsedOperands[i];
1172 // Don't skip the rest of the line, the instruction parser is responsible for
1177 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1178 const std::vector<std::vector<AsmToken> > &A)
1179 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1181 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1182 // to hold the macro body with substitutions.
1183 SmallString<256> Buf;
1184 raw_svector_ostream OS(Buf);
1186 StringRef Body = M->Body;
1187 while (!Body.empty()) {
1188 // Scan for the next substitution.
1189 std::size_t End = Body.size(), Pos = 0;
1190 for (; Pos != End; ++Pos) {
1191 // Check for a substitution or escape.
1192 if (Body[Pos] != '$' || Pos + 1 == End)
1195 char Next = Body[Pos + 1];
1196 if (Next == '$' || Next == 'n' || isdigit(Next))
1201 OS << Body.slice(0, Pos);
1203 // Check if we reached the end.
1207 switch (Body[Pos+1]) {
1213 // $n => number of arguments
1218 // $[0-9] => argument
1220 // Missing arguments are ignored.
1221 unsigned Index = Body[Pos+1] - '0';
1222 if (Index >= A.size())
1225 // Otherwise substitute with the token values, with spaces eliminated.
1226 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1227 ie = A[Index].end(); it != ie; ++it)
1228 OS << it->getString();
1233 // Update the scan point.
1234 Body = Body.substr(Pos + 2);
1237 // We include the .endmacro in the buffer as our queue to exit the macro
1239 OS << ".endmacro\n";
1241 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1244 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1246 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1247 // this, although we should protect against infinite loops.
1248 if (ActiveMacros.size() == 20)
1249 return TokError("macros cannot be nested more than 20 levels deep");
1251 // Parse the macro instantiation arguments.
1252 std::vector<std::vector<AsmToken> > MacroArguments;
1253 MacroArguments.push_back(std::vector<AsmToken>());
1254 unsigned ParenLevel = 0;
1256 if (Lexer.is(AsmToken::Eof))
1257 return TokError("unexpected token in macro instantiation");
1258 if (Lexer.is(AsmToken::EndOfStatement))
1261 // If we aren't inside parentheses and this is a comma, start a new token
1263 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1264 MacroArguments.push_back(std::vector<AsmToken>());
1266 // Adjust the current parentheses level.
1267 if (Lexer.is(AsmToken::LParen))
1269 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1272 // Append the token to the current argument list.
1273 MacroArguments.back().push_back(getTok());
1278 // Create the macro instantiation object and add to the current macro
1279 // instantiation stack.
1280 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1283 ActiveMacros.push_back(MI);
1285 // Jump to the macro instantiation and prime the lexer.
1286 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1287 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1293 void AsmParser::HandleMacroExit() {
1294 // Jump to the EndOfStatement we should return to, and consume it.
1295 JumpToLoc(ActiveMacros.back()->ExitLoc);
1298 // Pop the instantiation entry.
1299 delete ActiveMacros.back();
1300 ActiveMacros.pop_back();
1303 static void MarkUsed(const MCExpr *Value) {
1304 switch (Value->getKind()) {
1305 case MCExpr::Binary:
1306 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1307 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1309 case MCExpr::Target:
1310 case MCExpr::Constant:
1312 case MCExpr::SymbolRef: {
1313 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1317 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1322 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1323 // FIXME: Use better location, we should use proper tokens.
1324 SMLoc EqualLoc = Lexer.getLoc();
1326 const MCExpr *Value;
1327 if (ParseExpression(Value))
1332 if (Lexer.isNot(AsmToken::EndOfStatement))
1333 return TokError("unexpected token in assignment");
1335 // Error on assignment to '.'.
1337 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1338 "(use '.space' or '.org').)"));
1341 // Eat the end of statement marker.
1344 // Validate that the LHS is allowed to be a variable (either it has not been
1345 // used as a symbol, or it is an absolute symbol).
1346 MCSymbol *Sym = getContext().LookupSymbol(Name);
1348 // Diagnose assignment to a label.
1350 // FIXME: Diagnostics. Note the location of the definition as a label.
1351 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1352 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1353 ; // Allow redefinitions of undefined symbols only used in directives.
1354 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1355 return Error(EqualLoc, "redefinition of '" + Name + "'");
1356 else if (!Sym->isVariable())
1357 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1358 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1359 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1362 // Don't count these checks as uses.
1363 Sym->setUsed(false);
1365 Sym = getContext().GetOrCreateSymbol(Name);
1367 // FIXME: Handle '.'.
1369 // Do the assignment.
1370 Out.EmitAssignment(Sym, Value);
1375 /// ParseIdentifier:
1378 bool AsmParser::ParseIdentifier(StringRef &Res) {
1379 // The assembler has relaxed rules for accepting identifiers, in particular we
1380 // allow things like '.globl $foo', which would normally be separate
1381 // tokens. At this level, we have already lexed so we cannot (currently)
1382 // handle this as a context dependent token, instead we detect adjacent tokens
1383 // and return the combined identifier.
1384 if (Lexer.is(AsmToken::Dollar)) {
1385 SMLoc DollarLoc = getLexer().getLoc();
1387 // Consume the dollar sign, and check for a following identifier.
1389 if (Lexer.isNot(AsmToken::Identifier))
1392 // We have a '$' followed by an identifier, make sure they are adjacent.
1393 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1396 // Construct the joined identifier and consume the token.
1397 Res = StringRef(DollarLoc.getPointer(),
1398 getTok().getIdentifier().size() + 1);
1403 if (Lexer.isNot(AsmToken::Identifier) &&
1404 Lexer.isNot(AsmToken::String))
1407 Res = getTok().getIdentifier();
1409 Lex(); // Consume the identifier token.
1414 /// ParseDirectiveSet:
1415 /// ::= .equ identifier ',' expression
1416 /// ::= .equiv identifier ',' expression
1417 /// ::= .set identifier ',' expression
1418 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1421 if (ParseIdentifier(Name))
1422 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1424 if (getLexer().isNot(AsmToken::Comma))
1425 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1428 return ParseAssignment(Name, allow_redef);
1431 bool AsmParser::ParseEscapedString(std::string &Data) {
1432 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1435 StringRef Str = getTok().getStringContents();
1436 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1437 if (Str[i] != '\\') {
1442 // Recognize escaped characters. Note that this escape semantics currently
1443 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1446 return TokError("unexpected backslash at end of string");
1448 // Recognize octal sequences.
1449 if ((unsigned) (Str[i] - '0') <= 7) {
1450 // Consume up to three octal characters.
1451 unsigned Value = Str[i] - '0';
1453 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1455 Value = Value * 8 + (Str[i] - '0');
1457 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1459 Value = Value * 8 + (Str[i] - '0');
1464 return TokError("invalid octal escape sequence (out of range)");
1466 Data += (unsigned char) Value;
1470 // Otherwise recognize individual escapes.
1473 // Just reject invalid escape sequences for now.
1474 return TokError("invalid escape sequence (unrecognized character)");
1476 case 'b': Data += '\b'; break;
1477 case 'f': Data += '\f'; break;
1478 case 'n': Data += '\n'; break;
1479 case 'r': Data += '\r'; break;
1480 case 't': Data += '\t'; break;
1481 case '"': Data += '"'; break;
1482 case '\\': Data += '\\'; break;
1489 /// ParseDirectiveAscii:
1490 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1491 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1492 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1493 CheckForValidSection();
1496 if (getLexer().isNot(AsmToken::String))
1497 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1500 if (ParseEscapedString(Data))
1503 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1505 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1509 if (getLexer().is(AsmToken::EndOfStatement))
1512 if (getLexer().isNot(AsmToken::Comma))
1513 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1522 /// ParseDirectiveValue
1523 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1524 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1525 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1526 CheckForValidSection();
1529 const MCExpr *Value;
1530 if (ParseExpression(Value))
1533 // Special case constant expressions to match code generator.
1534 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1535 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1537 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1539 if (getLexer().is(AsmToken::EndOfStatement))
1542 // FIXME: Improve diagnostic.
1543 if (getLexer().isNot(AsmToken::Comma))
1544 return TokError("unexpected token in directive");
1553 /// ParseDirectiveRealValue
1554 /// ::= (.single | .double) [ expression (, expression)* ]
1555 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1556 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1557 CheckForValidSection();
1560 // We don't truly support arithmetic on floating point expressions, so we
1561 // have to manually parse unary prefixes.
1563 if (getLexer().is(AsmToken::Minus)) {
1566 } else if (getLexer().is(AsmToken::Plus))
1569 if (getLexer().isNot(AsmToken::Integer) &&
1570 getLexer().isNot(AsmToken::Real) &&
1571 getLexer().isNot(AsmToken::Identifier))
1572 return TokError("unexpected token in directive");
1574 // Convert to an APFloat.
1575 APFloat Value(Semantics);
1576 StringRef IDVal = getTok().getString();
1577 if (getLexer().is(AsmToken::Identifier)) {
1578 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1579 Value = APFloat::getInf(Semantics);
1580 else if (!IDVal.compare_lower("nan"))
1581 Value = APFloat::getNaN(Semantics, false, ~0);
1583 return TokError("invalid floating point literal");
1584 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1585 APFloat::opInvalidOp)
1586 return TokError("invalid floating point literal");
1590 // Consume the numeric token.
1593 // Emit the value as an integer.
1594 APInt AsInt = Value.bitcastToAPInt();
1595 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1596 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1598 if (getLexer().is(AsmToken::EndOfStatement))
1601 if (getLexer().isNot(AsmToken::Comma))
1602 return TokError("unexpected token in directive");
1611 /// ParseDirectiveSpace
1612 /// ::= .space expression [ , expression ]
1613 bool AsmParser::ParseDirectiveSpace() {
1614 CheckForValidSection();
1617 if (ParseAbsoluteExpression(NumBytes))
1620 int64_t FillExpr = 0;
1621 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1622 if (getLexer().isNot(AsmToken::Comma))
1623 return TokError("unexpected token in '.space' directive");
1626 if (ParseAbsoluteExpression(FillExpr))
1629 if (getLexer().isNot(AsmToken::EndOfStatement))
1630 return TokError("unexpected token in '.space' directive");
1636 return TokError("invalid number of bytes in '.space' directive");
1638 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1639 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1644 /// ParseDirectiveZero
1645 /// ::= .zero expression
1646 bool AsmParser::ParseDirectiveZero() {
1647 CheckForValidSection();
1650 if (ParseAbsoluteExpression(NumBytes))
1654 if (getLexer().is(AsmToken::Comma)) {
1656 if (ParseAbsoluteExpression(Val))
1660 if (getLexer().isNot(AsmToken::EndOfStatement))
1661 return TokError("unexpected token in '.zero' directive");
1665 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1670 /// ParseDirectiveFill
1671 /// ::= .fill expression , expression , expression
1672 bool AsmParser::ParseDirectiveFill() {
1673 CheckForValidSection();
1676 if (ParseAbsoluteExpression(NumValues))
1679 if (getLexer().isNot(AsmToken::Comma))
1680 return TokError("unexpected token in '.fill' directive");
1684 if (ParseAbsoluteExpression(FillSize))
1687 if (getLexer().isNot(AsmToken::Comma))
1688 return TokError("unexpected token in '.fill' directive");
1692 if (ParseAbsoluteExpression(FillExpr))
1695 if (getLexer().isNot(AsmToken::EndOfStatement))
1696 return TokError("unexpected token in '.fill' directive");
1700 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1701 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1703 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1704 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1709 /// ParseDirectiveOrg
1710 /// ::= .org expression [ , expression ]
1711 bool AsmParser::ParseDirectiveOrg() {
1712 CheckForValidSection();
1714 const MCExpr *Offset;
1715 if (ParseExpression(Offset))
1718 // Parse optional fill expression.
1719 int64_t FillExpr = 0;
1720 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1721 if (getLexer().isNot(AsmToken::Comma))
1722 return TokError("unexpected token in '.org' directive");
1725 if (ParseAbsoluteExpression(FillExpr))
1728 if (getLexer().isNot(AsmToken::EndOfStatement))
1729 return TokError("unexpected token in '.org' directive");
1734 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1735 // has to be relative to the current section.
1736 getStreamer().EmitValueToOffset(Offset, FillExpr);
1741 /// ParseDirectiveAlign
1742 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1743 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1744 CheckForValidSection();
1746 SMLoc AlignmentLoc = getLexer().getLoc();
1748 if (ParseAbsoluteExpression(Alignment))
1752 bool HasFillExpr = false;
1753 int64_t FillExpr = 0;
1754 int64_t MaxBytesToFill = 0;
1755 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1756 if (getLexer().isNot(AsmToken::Comma))
1757 return TokError("unexpected token in directive");
1760 // The fill expression can be omitted while specifying a maximum number of
1761 // alignment bytes, e.g:
1763 if (getLexer().isNot(AsmToken::Comma)) {
1765 if (ParseAbsoluteExpression(FillExpr))
1769 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1770 if (getLexer().isNot(AsmToken::Comma))
1771 return TokError("unexpected token in directive");
1774 MaxBytesLoc = getLexer().getLoc();
1775 if (ParseAbsoluteExpression(MaxBytesToFill))
1778 if (getLexer().isNot(AsmToken::EndOfStatement))
1779 return TokError("unexpected token in directive");
1788 // Compute alignment in bytes.
1790 // FIXME: Diagnose overflow.
1791 if (Alignment >= 32) {
1792 Error(AlignmentLoc, "invalid alignment value");
1796 Alignment = 1ULL << Alignment;
1799 // Diagnose non-sensical max bytes to align.
1800 if (MaxBytesLoc.isValid()) {
1801 if (MaxBytesToFill < 1) {
1802 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1803 "many bytes, ignoring maximum bytes expression");
1807 if (MaxBytesToFill >= Alignment) {
1808 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1814 // Check whether we should use optimal code alignment for this .align
1816 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1817 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1818 ValueSize == 1 && UseCodeAlign) {
1819 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1821 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1822 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1829 /// ParseDirectiveSymbolAttribute
1830 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1831 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1832 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1836 if (ParseIdentifier(Name))
1837 return TokError("expected identifier in directive");
1839 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1841 getStreamer().EmitSymbolAttribute(Sym, Attr);
1843 if (getLexer().is(AsmToken::EndOfStatement))
1846 if (getLexer().isNot(AsmToken::Comma))
1847 return TokError("unexpected token in directive");
1856 /// ParseDirectiveComm
1857 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1858 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1859 CheckForValidSection();
1861 SMLoc IDLoc = getLexer().getLoc();
1863 if (ParseIdentifier(Name))
1864 return TokError("expected identifier in directive");
1866 // Handle the identifier as the key symbol.
1867 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1869 if (getLexer().isNot(AsmToken::Comma))
1870 return TokError("unexpected token in directive");
1874 SMLoc SizeLoc = getLexer().getLoc();
1875 if (ParseAbsoluteExpression(Size))
1878 int64_t Pow2Alignment = 0;
1879 SMLoc Pow2AlignmentLoc;
1880 if (getLexer().is(AsmToken::Comma)) {
1882 Pow2AlignmentLoc = getLexer().getLoc();
1883 if (ParseAbsoluteExpression(Pow2Alignment))
1886 // If this target takes alignments in bytes (not log) validate and convert.
1887 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1888 if (!isPowerOf2_64(Pow2Alignment))
1889 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1890 Pow2Alignment = Log2_64(Pow2Alignment);
1894 if (getLexer().isNot(AsmToken::EndOfStatement))
1895 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1899 // NOTE: a size of zero for a .comm should create a undefined symbol
1900 // but a size of .lcomm creates a bss symbol of size zero.
1902 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1903 "be less than zero");
1905 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1906 // may internally end up wanting an alignment in bytes.
1907 // FIXME: Diagnose overflow.
1908 if (Pow2Alignment < 0)
1909 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1910 "alignment, can't be less than zero");
1912 if (!Sym->isUndefined())
1913 return Error(IDLoc, "invalid symbol redefinition");
1915 // '.lcomm' is equivalent to '.zerofill'.
1916 // Create the Symbol as a common or local common with Size and Pow2Alignment
1918 getStreamer().EmitZerofill(Ctx.getMachOSection(
1919 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1920 0, SectionKind::getBSS()),
1921 Sym, Size, 1 << Pow2Alignment);
1925 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1929 /// ParseDirectiveAbort
1930 /// ::= .abort [... message ...]
1931 bool AsmParser::ParseDirectiveAbort() {
1932 // FIXME: Use loc from directive.
1933 SMLoc Loc = getLexer().getLoc();
1935 StringRef Str = ParseStringToEndOfStatement();
1936 if (getLexer().isNot(AsmToken::EndOfStatement))
1937 return TokError("unexpected token in '.abort' directive");
1942 Error(Loc, ".abort detected. Assembly stopping.");
1944 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1945 // FIXME: Actually abort assembly here.
1950 /// ParseDirectiveInclude
1951 /// ::= .include "filename"
1952 bool AsmParser::ParseDirectiveInclude() {
1953 if (getLexer().isNot(AsmToken::String))
1954 return TokError("expected string in '.include' directive");
1956 std::string Filename = getTok().getString();
1957 SMLoc IncludeLoc = getLexer().getLoc();
1960 if (getLexer().isNot(AsmToken::EndOfStatement))
1961 return TokError("unexpected token in '.include' directive");
1963 // Strip the quotes.
1964 Filename = Filename.substr(1, Filename.size()-2);
1966 // Attempt to switch the lexer to the included file before consuming the end
1967 // of statement to avoid losing it when we switch.
1968 if (EnterIncludeFile(Filename)) {
1969 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1976 /// ParseDirectiveIf
1977 /// ::= .if expression
1978 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1979 TheCondStack.push_back(TheCondState);
1980 TheCondState.TheCond = AsmCond::IfCond;
1981 if(TheCondState.Ignore) {
1982 EatToEndOfStatement();
1986 if (ParseAbsoluteExpression(ExprValue))
1989 if (getLexer().isNot(AsmToken::EndOfStatement))
1990 return TokError("unexpected token in '.if' directive");
1994 TheCondState.CondMet = ExprValue;
1995 TheCondState.Ignore = !TheCondState.CondMet;
2001 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2003 TheCondStack.push_back(TheCondState);
2004 TheCondState.TheCond = AsmCond::IfCond;
2006 if (TheCondState.Ignore) {
2007 EatToEndOfStatement();
2009 if (ParseIdentifier(Name))
2010 return TokError("expected identifier after '.ifdef'");
2014 MCSymbol *Sym = getContext().LookupSymbol(Name);
2017 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2019 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2020 TheCondState.Ignore = !TheCondState.CondMet;
2026 /// ParseDirectiveElseIf
2027 /// ::= .elseif expression
2028 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2029 if (TheCondState.TheCond != AsmCond::IfCond &&
2030 TheCondState.TheCond != AsmCond::ElseIfCond)
2031 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2033 TheCondState.TheCond = AsmCond::ElseIfCond;
2035 bool LastIgnoreState = false;
2036 if (!TheCondStack.empty())
2037 LastIgnoreState = TheCondStack.back().Ignore;
2038 if (LastIgnoreState || TheCondState.CondMet) {
2039 TheCondState.Ignore = true;
2040 EatToEndOfStatement();
2044 if (ParseAbsoluteExpression(ExprValue))
2047 if (getLexer().isNot(AsmToken::EndOfStatement))
2048 return TokError("unexpected token in '.elseif' directive");
2051 TheCondState.CondMet = ExprValue;
2052 TheCondState.Ignore = !TheCondState.CondMet;
2058 /// ParseDirectiveElse
2060 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2061 if (getLexer().isNot(AsmToken::EndOfStatement))
2062 return TokError("unexpected token in '.else' directive");
2066 if (TheCondState.TheCond != AsmCond::IfCond &&
2067 TheCondState.TheCond != AsmCond::ElseIfCond)
2068 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2070 TheCondState.TheCond = AsmCond::ElseCond;
2071 bool LastIgnoreState = false;
2072 if (!TheCondStack.empty())
2073 LastIgnoreState = TheCondStack.back().Ignore;
2074 if (LastIgnoreState || TheCondState.CondMet)
2075 TheCondState.Ignore = true;
2077 TheCondState.Ignore = false;
2082 /// ParseDirectiveEndIf
2084 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2085 if (getLexer().isNot(AsmToken::EndOfStatement))
2086 return TokError("unexpected token in '.endif' directive");
2090 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2091 TheCondStack.empty())
2092 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2094 if (!TheCondStack.empty()) {
2095 TheCondState = TheCondStack.back();
2096 TheCondStack.pop_back();
2102 /// ParseDirectiveFile
2103 /// ::= .file [number] string
2104 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2105 // FIXME: I'm not sure what this is.
2106 int64_t FileNumber = -1;
2107 SMLoc FileNumberLoc = getLexer().getLoc();
2108 if (getLexer().is(AsmToken::Integer)) {
2109 FileNumber = getTok().getIntVal();
2113 return TokError("file number less than one");
2116 if (getLexer().isNot(AsmToken::String))
2117 return TokError("unexpected token in '.file' directive");
2119 StringRef Filename = getTok().getString();
2120 Filename = Filename.substr(1, Filename.size()-2);
2123 if (getLexer().isNot(AsmToken::EndOfStatement))
2124 return TokError("unexpected token in '.file' directive");
2126 if (FileNumber == -1)
2127 getStreamer().EmitFileDirective(Filename);
2129 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2130 Error(FileNumberLoc, "file number already allocated");
2136 /// ParseDirectiveLine
2137 /// ::= .line [number]
2138 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2139 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2140 if (getLexer().isNot(AsmToken::Integer))
2141 return TokError("unexpected token in '.line' directive");
2143 int64_t LineNumber = getTok().getIntVal();
2147 // FIXME: Do something with the .line.
2150 if (getLexer().isNot(AsmToken::EndOfStatement))
2151 return TokError("unexpected token in '.line' directive");
2157 /// ParseDirectiveLoc
2158 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2159 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2160 /// The first number is a file number, must have been previously assigned with
2161 /// a .file directive, the second number is the line number and optionally the
2162 /// third number is a column position (zero if not specified). The remaining
2163 /// optional items are .loc sub-directives.
2164 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2166 if (getLexer().isNot(AsmToken::Integer))
2167 return TokError("unexpected token in '.loc' directive");
2168 int64_t FileNumber = getTok().getIntVal();
2170 return TokError("file number less than one in '.loc' directive");
2171 if (!getContext().isValidDwarfFileNumber(FileNumber))
2172 return TokError("unassigned file number in '.loc' directive");
2175 int64_t LineNumber = 0;
2176 if (getLexer().is(AsmToken::Integer)) {
2177 LineNumber = getTok().getIntVal();
2179 return TokError("line number less than one in '.loc' directive");
2183 int64_t ColumnPos = 0;
2184 if (getLexer().is(AsmToken::Integer)) {
2185 ColumnPos = getTok().getIntVal();
2187 return TokError("column position less than zero in '.loc' directive");
2191 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2193 int64_t Discriminator = 0;
2194 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2196 if (getLexer().is(AsmToken::EndOfStatement))
2200 SMLoc Loc = getTok().getLoc();
2201 if (getParser().ParseIdentifier(Name))
2202 return TokError("unexpected token in '.loc' directive");
2204 if (Name == "basic_block")
2205 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2206 else if (Name == "prologue_end")
2207 Flags |= DWARF2_FLAG_PROLOGUE_END;
2208 else if (Name == "epilogue_begin")
2209 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2210 else if (Name == "is_stmt") {
2211 SMLoc Loc = getTok().getLoc();
2212 const MCExpr *Value;
2213 if (getParser().ParseExpression(Value))
2215 // The expression must be the constant 0 or 1.
2216 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2217 int Value = MCE->getValue();
2219 Flags &= ~DWARF2_FLAG_IS_STMT;
2220 else if (Value == 1)
2221 Flags |= DWARF2_FLAG_IS_STMT;
2223 return Error(Loc, "is_stmt value not 0 or 1");
2226 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2229 else if (Name == "isa") {
2230 SMLoc Loc = getTok().getLoc();
2231 const MCExpr *Value;
2232 if (getParser().ParseExpression(Value))
2234 // The expression must be a constant greater or equal to 0.
2235 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2236 int Value = MCE->getValue();
2238 return Error(Loc, "isa number less than zero");
2242 return Error(Loc, "isa number not a constant value");
2245 else if (Name == "discriminator") {
2246 if (getParser().ParseAbsoluteExpression(Discriminator))
2250 return Error(Loc, "unknown sub-directive in '.loc' directive");
2253 if (getLexer().is(AsmToken::EndOfStatement))
2258 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2259 Isa, Discriminator, StringRef());
2264 /// ParseDirectiveStabs
2265 /// ::= .stabs string, number, number, number
2266 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2267 SMLoc DirectiveLoc) {
2268 return TokError("unsupported directive '" + Directive + "'");
2271 /// ParseDirectiveCFISections
2272 /// ::= .cfi_sections section [, section]
2273 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2274 SMLoc DirectiveLoc) {
2279 if (getParser().ParseIdentifier(Name))
2280 return TokError("Expected an identifier");
2282 if (Name == ".eh_frame")
2284 else if (Name == ".debug_frame")
2287 if (getLexer().is(AsmToken::Comma)) {
2290 if (getParser().ParseIdentifier(Name))
2291 return TokError("Expected an identifier");
2293 if (Name == ".eh_frame")
2295 else if (Name == ".debug_frame")
2299 getStreamer().EmitCFISections(EH, Debug);
2304 /// ParseDirectiveCFIStartProc
2305 /// ::= .cfi_startproc
2306 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2307 SMLoc DirectiveLoc) {
2308 getStreamer().EmitCFIStartProc();
2312 /// ParseDirectiveCFIEndProc
2313 /// ::= .cfi_endproc
2314 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2315 getStreamer().EmitCFIEndProc();
2319 /// ParseRegisterOrRegisterNumber - parse register name or number.
2320 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2321 SMLoc DirectiveLoc) {
2324 if (getLexer().is(AsmToken::Percent)) {
2325 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2328 Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2330 return getParser().ParseAbsoluteExpression(Register);
2335 /// ParseDirectiveCFIDefCfa
2336 /// ::= .cfi_def_cfa register, offset
2337 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2338 SMLoc DirectiveLoc) {
2339 int64_t Register = 0;
2340 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2343 if (getLexer().isNot(AsmToken::Comma))
2344 return TokError("unexpected token in directive");
2348 if (getParser().ParseAbsoluteExpression(Offset))
2351 getStreamer().EmitCFIDefCfa(Register, Offset);
2355 /// ParseDirectiveCFIDefCfaOffset
2356 /// ::= .cfi_def_cfa_offset offset
2357 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2358 SMLoc DirectiveLoc) {
2360 if (getParser().ParseAbsoluteExpression(Offset))
2363 getStreamer().EmitCFIDefCfaOffset(Offset);
2367 /// ParseDirectiveCFIAdjustCfaOffset
2368 /// ::= .cfi_adjust_cfa_offset adjustment
2369 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2370 SMLoc DirectiveLoc) {
2371 int64_t Adjustment = 0;
2372 if (getParser().ParseAbsoluteExpression(Adjustment))
2375 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2379 /// ParseDirectiveCFIDefCfaRegister
2380 /// ::= .cfi_def_cfa_register register
2381 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2382 SMLoc DirectiveLoc) {
2383 int64_t Register = 0;
2384 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2387 getStreamer().EmitCFIDefCfaRegister(Register);
2391 /// ParseDirectiveCFIOffset
2392 /// ::= .cfi_offset register, offset
2393 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2394 int64_t Register = 0;
2397 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2400 if (getLexer().isNot(AsmToken::Comma))
2401 return TokError("unexpected token in directive");
2404 if (getParser().ParseAbsoluteExpression(Offset))
2407 getStreamer().EmitCFIOffset(Register, Offset);
2411 /// ParseDirectiveCFIRelOffset
2412 /// ::= .cfi_rel_offset register, offset
2413 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2414 SMLoc DirectiveLoc) {
2415 int64_t Register = 0;
2417 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2420 if (getLexer().isNot(AsmToken::Comma))
2421 return TokError("unexpected token in directive");
2425 if (getParser().ParseAbsoluteExpression(Offset))
2428 getStreamer().EmitCFIRelOffset(Register, Offset);
2432 static bool isValidEncoding(int64_t Encoding) {
2433 if (Encoding & ~0xff)
2436 if (Encoding == dwarf::DW_EH_PE_omit)
2439 const unsigned Format = Encoding & 0xf;
2440 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2441 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2442 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2443 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2446 const unsigned Application = Encoding & 0x70;
2447 if (Application != dwarf::DW_EH_PE_absptr &&
2448 Application != dwarf::DW_EH_PE_pcrel)
2454 /// ParseDirectiveCFIPersonalityOrLsda
2455 /// ::= .cfi_personality encoding, [symbol_name]
2456 /// ::= .cfi_lsda encoding, [symbol_name]
2457 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2458 SMLoc DirectiveLoc) {
2459 int64_t Encoding = 0;
2460 if (getParser().ParseAbsoluteExpression(Encoding))
2462 if (Encoding == dwarf::DW_EH_PE_omit)
2465 if (!isValidEncoding(Encoding))
2466 return TokError("unsupported encoding.");
2468 if (getLexer().isNot(AsmToken::Comma))
2469 return TokError("unexpected token in directive");
2473 if (getParser().ParseIdentifier(Name))
2474 return TokError("expected identifier in directive");
2476 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2478 if (IDVal == ".cfi_personality")
2479 getStreamer().EmitCFIPersonality(Sym, Encoding);
2481 assert(IDVal == ".cfi_lsda");
2482 getStreamer().EmitCFILsda(Sym, Encoding);
2487 /// ParseDirectiveCFIRememberState
2488 /// ::= .cfi_remember_state
2489 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2490 SMLoc DirectiveLoc) {
2491 getStreamer().EmitCFIRememberState();
2495 /// ParseDirectiveCFIRestoreState
2496 /// ::= .cfi_remember_state
2497 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2498 SMLoc DirectiveLoc) {
2499 getStreamer().EmitCFIRestoreState();
2503 /// ParseDirectiveCFISameValue
2504 /// ::= .cfi_same_value register
2505 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2506 SMLoc DirectiveLoc) {
2507 int64_t Register = 0;
2509 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2512 getStreamer().EmitCFISameValue(Register);
2517 /// ParseDirectiveMacrosOnOff
2520 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2521 SMLoc DirectiveLoc) {
2522 if (getLexer().isNot(AsmToken::EndOfStatement))
2523 return Error(getLexer().getLoc(),
2524 "unexpected token in '" + Directive + "' directive");
2526 getParser().MacrosEnabled = Directive == ".macros_on";
2531 /// ParseDirectiveMacro
2533 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2534 SMLoc DirectiveLoc) {
2536 if (getParser().ParseIdentifier(Name))
2537 return TokError("expected identifier in directive");
2539 if (getLexer().isNot(AsmToken::EndOfStatement))
2540 return TokError("unexpected token in '.macro' directive");
2542 // Eat the end of statement.
2545 AsmToken EndToken, StartToken = getTok();
2547 // Lex the macro definition.
2549 // Check whether we have reached the end of the file.
2550 if (getLexer().is(AsmToken::Eof))
2551 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2553 // Otherwise, check whether we have reach the .endmacro.
2554 if (getLexer().is(AsmToken::Identifier) &&
2555 (getTok().getIdentifier() == ".endm" ||
2556 getTok().getIdentifier() == ".endmacro")) {
2557 EndToken = getTok();
2559 if (getLexer().isNot(AsmToken::EndOfStatement))
2560 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2565 // Otherwise, scan til the end of the statement.
2566 getParser().EatToEndOfStatement();
2569 if (getParser().MacroMap.lookup(Name)) {
2570 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2573 const char *BodyStart = StartToken.getLoc().getPointer();
2574 const char *BodyEnd = EndToken.getLoc().getPointer();
2575 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2576 getParser().MacroMap[Name] = new Macro(Name, Body);
2580 /// ParseDirectiveEndMacro
2583 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2584 SMLoc DirectiveLoc) {
2585 if (getLexer().isNot(AsmToken::EndOfStatement))
2586 return TokError("unexpected token in '" + Directive + "' directive");
2588 // If we are inside a macro instantiation, terminate the current
2590 if (!getParser().ActiveMacros.empty()) {
2591 getParser().HandleMacroExit();
2595 // Otherwise, this .endmacro is a stray entry in the file; well formed
2596 // .endmacro directives are handled during the macro definition parsing.
2597 return TokError("unexpected '" + Directive + "' in file, "
2598 "no current macro definition");
2601 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2602 getParser().CheckForValidSection();
2604 const MCExpr *Value;
2606 if (getParser().ParseExpression(Value))
2609 if (getLexer().isNot(AsmToken::EndOfStatement))
2610 return TokError("unexpected token in directive");
2612 if (DirName[1] == 's')
2613 getStreamer().EmitSLEB128Value(Value);
2615 getStreamer().EmitULEB128Value(Value);
2621 /// \brief Create an MCAsmParser instance.
2622 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2623 MCContext &C, MCStreamer &Out,
2624 const MCAsmInfo &MAI) {
2625 return new AsmParser(T, SM, C, Out, MAI);