1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCParser/AsmCond.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCTargetAsmParser.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/raw_ostream.h"
42 FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
47 /// \brief Helper class for tracking macro definitions.
51 std::vector<StringRef> Parameters;
54 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
58 /// \brief Helper class for storing information about an active macro
60 struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
70 /// The location where parsing should resume upon instantiation completion.
74 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
78 /// \brief The concrete assembly parser instance.
79 class AsmParser : public MCAsmParser {
80 friend class GenericAsmParser;
82 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
90 SourceMgr::DiagHandlerTy SavedDiagHandler;
91 void *SavedDiagContext;
92 MCAsmParserExtension *GenericParser;
93 MCAsmParserExtension *PlatformParser;
95 /// This is the current buffer index we're lexing from as managed by the
100 std::vector<AsmCond> TheCondStack;
102 /// DirectiveMap - This is a table handlers for directives. Each handler is
103 /// invoked after the directive identifier is read and is responsible for
104 /// parsing and validating the rest of the directive. The handler is passed
105 /// in the directive name and the location of the directive keyword.
106 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
108 /// MacroMap - Map of currently defined macros.
109 StringMap<Macro*> MacroMap;
111 /// ActiveMacros - Stack of active macro instantiations.
112 std::vector<MacroInstantiation*> ActiveMacros;
114 /// Boolean tracking whether macro substitution is enabled.
115 unsigned MacrosEnabled : 1;
117 /// Flag tracking whether any errors have been encountered.
118 unsigned HadError : 1;
120 /// The values from the last parsed cpp hash file line comment if any.
121 StringRef CppHashFilename;
122 int64_t CppHashLineNumber;
126 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
127 const MCAsmInfo &MAI);
130 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
132 void AddDirectiveHandler(MCAsmParserExtension *Object,
134 DirectiveHandler Handler) {
135 DirectiveMap[Directive] = std::make_pair(Object, Handler);
139 /// @name MCAsmParser Interface
142 virtual SourceMgr &getSourceManager() { return SrcMgr; }
143 virtual MCAsmLexer &getLexer() { return Lexer; }
144 virtual MCContext &getContext() { return Ctx; }
145 virtual MCStreamer &getStreamer() { return Out; }
147 virtual bool Warning(SMLoc L, const Twine &Msg,
148 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
149 virtual bool Error(SMLoc L, const Twine &Msg,
150 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
152 const AsmToken &Lex();
154 bool ParseExpression(const MCExpr *&Res);
155 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
156 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
157 virtual bool ParseAbsoluteExpression(int64_t &Res);
162 void CheckForValidSection();
164 bool ParseStatement();
165 void EatToEndOfLine();
166 bool ParseCppHashLineFilenameComment(const SMLoc &L);
168 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
169 bool expandMacro(SmallString<256> &Buf, StringRef Body,
170 const std::vector<StringRef> &Parameters,
171 const std::vector<std::vector<AsmToken> > &A,
173 void HandleMacroExit();
175 void PrintMacroInstantiations();
176 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
177 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
178 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
180 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
182 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
183 bool EnterIncludeFile(const std::string &Filename);
184 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
185 /// This returns true on failure.
186 bool ProcessIncbinFile(const std::string &Filename);
188 /// \brief Reset the current lexer position to that given by \arg Loc. The
189 /// current token is not set; clients should ensure Lex() is called
191 void JumpToLoc(SMLoc Loc);
193 void EatToEndOfStatement();
195 /// \brief Parse up to the end of statement and a return the contents from the
196 /// current token until the end of the statement; the current token on exit
197 /// will be either the EndOfStatement or EOF.
198 StringRef ParseStringToEndOfStatement();
200 bool ParseAssignment(StringRef Name, bool allow_redef);
202 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
203 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
204 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
205 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
207 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
208 /// and set \arg Res to the identifier contents.
209 bool ParseIdentifier(StringRef &Res);
211 // Directive Parsing.
213 // ".ascii", ".asciiz", ".string"
214 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
215 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
216 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
217 bool ParseDirectiveFill(); // ".fill"
218 bool ParseDirectiveSpace(); // ".space"
219 bool ParseDirectiveZero(); // ".zero"
220 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
221 bool ParseDirectiveOrg(); // ".org"
222 // ".align{,32}", ".p2align{,w,l}"
223 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
225 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
226 /// accepts a single symbol (which should be a label or an external).
227 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
229 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
231 bool ParseDirectiveAbort(); // ".abort"
232 bool ParseDirectiveInclude(); // ".include"
233 bool ParseDirectiveIncbin(); // ".incbin"
235 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
236 // ".ifdef" or ".ifndef", depending on expect_defined
237 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
238 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
239 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
240 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
242 /// ParseEscapedString - Parse the current token as a string which may include
243 /// escaped characters and return the string contents.
244 bool ParseEscapedString(std::string &Data);
246 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
247 MCSymbolRefExpr::VariantKind Variant);
250 /// \brief Generic implementations of directive handling, etc. which is shared
251 /// (or the default, at least) for all assembler parser.
252 class GenericAsmParser : public MCAsmParserExtension {
253 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
254 void AddDirectiveHandler(StringRef Directive) {
255 getParser().AddDirectiveHandler(this, Directive,
256 HandleDirective<GenericAsmParser, Handler>);
259 GenericAsmParser() {}
261 AsmParser &getParser() {
262 return (AsmParser&) this->MCAsmParserExtension::getParser();
265 virtual void Initialize(MCAsmParser &Parser) {
266 // Call the base implementation.
267 this->MCAsmParserExtension::Initialize(Parser);
269 // Debugging directives.
270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
278 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
280 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
282 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
285 ".cfi_def_cfa_offset");
286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
287 ".cfi_adjust_cfa_offset");
288 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
289 ".cfi_def_cfa_register");
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
295 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
297 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
299 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
301 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
303 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
308 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
310 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
311 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
312 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
314 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
315 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
318 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
320 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
321 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
322 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
323 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
324 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
325 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
326 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
327 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
328 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
329 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
330 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
331 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
332 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
333 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
334 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
335 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
336 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
338 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
339 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
340 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
342 bool ParseDirectiveLEB128(StringRef, SMLoc);
349 extern MCAsmParserExtension *createDarwinAsmParser();
350 extern MCAsmParserExtension *createELFAsmParser();
351 extern MCAsmParserExtension *createCOFFAsmParser();
355 enum { DEFAULT_ADDRSPACE = 0 };
357 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
358 MCStreamer &_Out, const MCAsmInfo &_MAI)
359 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
360 GenericParser(new GenericAsmParser), PlatformParser(0),
361 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0) {
362 // Save the old handler.
363 SavedDiagHandler = SrcMgr.getDiagHandler();
364 SavedDiagContext = SrcMgr.getDiagContext();
365 // Set our own handler which calls the saved handler.
366 SrcMgr.setDiagHandler(DiagHandler, this);
367 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
369 // Initialize the generic parser.
370 GenericParser->Initialize(*this);
372 // Initialize the platform / file format parser.
374 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
376 if (_MAI.hasMicrosoftFastStdCallMangling()) {
377 PlatformParser = createCOFFAsmParser();
378 PlatformParser->Initialize(*this);
379 } else if (_MAI.hasSubsectionsViaSymbols()) {
380 PlatformParser = createDarwinAsmParser();
381 PlatformParser->Initialize(*this);
383 PlatformParser = createELFAsmParser();
384 PlatformParser->Initialize(*this);
388 AsmParser::~AsmParser() {
389 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
391 // Destroy any macros.
392 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
393 ie = MacroMap.end(); it != ie; ++it)
394 delete it->getValue();
396 delete PlatformParser;
397 delete GenericParser;
400 void AsmParser::PrintMacroInstantiations() {
401 // Print the active macro instantiation stack.
402 for (std::vector<MacroInstantiation*>::const_reverse_iterator
403 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
404 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
405 "while in macro instantiation");
408 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
409 if (FatalAssemblerWarnings)
410 return Error(L, Msg, Ranges);
411 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
412 PrintMacroInstantiations();
416 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
418 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
419 PrintMacroInstantiations();
423 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
424 std::string IncludedFile;
425 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
431 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
436 /// Process the specified .incbin file by seaching for it in the include paths
437 /// then just emiting the byte contents of the file to the streamer. This
438 /// returns true on failure.
439 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
440 std::string IncludedFile;
441 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
445 // Loop picking the bytes from the file and emitting them.
446 const char *BufferStart = SrcMgr.getMemoryBuffer(NewBuf)->getBufferStart();
447 const char *BufferEnd = SrcMgr.getMemoryBuffer(NewBuf)->getBufferEnd();
448 for(const char *p = BufferStart; p < BufferEnd; p++)
449 getStreamer().EmitIntValue(*p, 1, DEFAULT_ADDRSPACE);
454 void AsmParser::JumpToLoc(SMLoc Loc) {
455 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
456 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
459 const AsmToken &AsmParser::Lex() {
460 const AsmToken *tok = &Lexer.Lex();
462 if (tok->is(AsmToken::Eof)) {
463 // If this is the end of an included file, pop the parent file off the
465 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
466 if (ParentIncludeLoc != SMLoc()) {
467 JumpToLoc(ParentIncludeLoc);
472 if (tok->is(AsmToken::Error))
473 Error(Lexer.getErrLoc(), Lexer.getErr());
478 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
479 // Create the initial section, if requested.
480 if (!NoInitialTextSection)
487 AsmCond StartingCondState = TheCondState;
489 // If we are generating dwarf for assembly source files save the initial text
490 // section and generate a .file directive.
491 if (getContext().getGenDwarfForAssembly()) {
492 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
493 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
494 getStreamer().EmitLabel(SectionStartSym);
495 getContext().setGenDwarfSectionStartSym(SectionStartSym);
496 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
497 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
500 // While we have input, parse each statement.
501 while (Lexer.isNot(AsmToken::Eof)) {
502 if (!ParseStatement()) continue;
504 // We had an error, validate that one was emitted and recover by skipping to
506 assert(HadError && "Parse statement returned an error, but none emitted!");
507 EatToEndOfStatement();
510 if (TheCondState.TheCond != StartingCondState.TheCond ||
511 TheCondState.Ignore != StartingCondState.Ignore)
512 return TokError("unmatched .ifs or .elses");
514 // Check to see there are no empty DwarfFile slots.
515 const std::vector<MCDwarfFile *> &MCDwarfFiles =
516 getContext().getMCDwarfFiles();
517 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
518 if (!MCDwarfFiles[i])
519 TokError("unassigned file number: " + Twine(i) + " for .file directives");
522 // Check to see that all assembler local symbols were actually defined.
523 // Targets that don't do subsections via symbols may not want this, though,
524 // so conservatively exclude them. Only do this if we're finalizing, though,
525 // as otherwise we won't necessarilly have seen everything yet.
526 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
527 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
528 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
531 MCSymbol *Sym = i->getValue();
532 // Variable symbols may not be marked as defined, so check those
533 // explicitly. If we know it's a variable, we have a definition for
534 // the purposes of this check.
535 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
536 // FIXME: We would really like to refer back to where the symbol was
537 // first referenced for a source location. We need to add something
538 // to track that. Currently, we just point to the end of the file.
539 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
540 "assembler local symbol '" + Sym->getName() +
546 // Finalize the output stream if there are no errors and if the client wants
548 if (!HadError && !NoFinalize)
554 void AsmParser::CheckForValidSection() {
555 if (!getStreamer().getCurrentSection()) {
556 TokError("expected section directive before assembly directive");
557 Out.SwitchSection(Ctx.getMachOSection(
559 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
560 0, SectionKind::getText()));
564 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
565 void AsmParser::EatToEndOfStatement() {
566 while (Lexer.isNot(AsmToken::EndOfStatement) &&
567 Lexer.isNot(AsmToken::Eof))
571 if (Lexer.is(AsmToken::EndOfStatement))
575 StringRef AsmParser::ParseStringToEndOfStatement() {
576 const char *Start = getTok().getLoc().getPointer();
578 while (Lexer.isNot(AsmToken::EndOfStatement) &&
579 Lexer.isNot(AsmToken::Eof))
582 const char *End = getTok().getLoc().getPointer();
583 return StringRef(Start, End - Start);
586 /// ParseParenExpr - Parse a paren expression and return it.
587 /// NOTE: This assumes the leading '(' has already been consumed.
589 /// parenexpr ::= expr)
591 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
592 if (ParseExpression(Res)) return true;
593 if (Lexer.isNot(AsmToken::RParen))
594 return TokError("expected ')' in parentheses expression");
595 EndLoc = Lexer.getLoc();
600 /// ParseBracketExpr - Parse a bracket expression and return it.
601 /// NOTE: This assumes the leading '[' has already been consumed.
603 /// bracketexpr ::= expr]
605 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
606 if (ParseExpression(Res)) return true;
607 if (Lexer.isNot(AsmToken::RBrac))
608 return TokError("expected ']' in brackets expression");
609 EndLoc = Lexer.getLoc();
614 /// ParsePrimaryExpr - Parse a primary expression and return it.
615 /// primaryexpr ::= (parenexpr
616 /// primaryexpr ::= symbol
617 /// primaryexpr ::= number
618 /// primaryexpr ::= '.'
619 /// primaryexpr ::= ~,+,- primaryexpr
620 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
621 switch (Lexer.getKind()) {
623 return TokError("unknown token in expression");
624 // If we have an error assume that we've already handled it.
625 case AsmToken::Error:
627 case AsmToken::Exclaim:
628 Lex(); // Eat the operator.
629 if (ParsePrimaryExpr(Res, EndLoc))
631 Res = MCUnaryExpr::CreateLNot(Res, getContext());
633 case AsmToken::Dollar:
634 case AsmToken::String:
635 case AsmToken::Identifier: {
636 EndLoc = Lexer.getLoc();
638 StringRef Identifier;
639 if (ParseIdentifier(Identifier))
642 // This is a symbol reference.
643 std::pair<StringRef, StringRef> Split = Identifier.split('@');
644 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
646 // Lookup the symbol variant if used.
647 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
648 if (Split.first.size() != Identifier.size()) {
649 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
650 if (Variant == MCSymbolRefExpr::VK_Invalid) {
651 Variant = MCSymbolRefExpr::VK_None;
652 return TokError("invalid variant '" + Split.second + "'");
656 // If this is an absolute variable reference, substitute it now to preserve
657 // semantics in the face of reassignment.
658 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
660 return Error(EndLoc, "unexpected modifier on variable reference");
662 Res = Sym->getVariableValue();
666 // Otherwise create a symbol ref.
667 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
670 case AsmToken::Integer: {
671 SMLoc Loc = getTok().getLoc();
672 int64_t IntVal = getTok().getIntVal();
673 Res = MCConstantExpr::Create(IntVal, getContext());
674 EndLoc = Lexer.getLoc();
676 // Look for 'b' or 'f' following an Integer as a directional label
677 if (Lexer.getKind() == AsmToken::Identifier) {
678 StringRef IDVal = getTok().getString();
679 if (IDVal == "f" || IDVal == "b"){
680 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
681 IDVal == "f" ? 1 : 0);
682 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
684 if(IDVal == "b" && Sym->isUndefined())
685 return Error(Loc, "invalid reference to undefined symbol");
686 EndLoc = Lexer.getLoc();
687 Lex(); // Eat identifier.
692 case AsmToken::Real: {
693 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
694 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
695 Res = MCConstantExpr::Create(IntVal, getContext());
699 case AsmToken::Dot: {
700 // This is a '.' reference, which references the current PC. Emit a
701 // temporary label to the streamer and refer to it.
702 MCSymbol *Sym = Ctx.CreateTempSymbol();
704 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
705 EndLoc = Lexer.getLoc();
706 Lex(); // Eat identifier.
709 case AsmToken::LParen:
710 Lex(); // Eat the '('.
711 return ParseParenExpr(Res, EndLoc);
712 case AsmToken::LBrac:
713 if (!PlatformParser->HasBracketExpressions())
714 return TokError("brackets expression not supported on this target");
715 Lex(); // Eat the '['.
716 return ParseBracketExpr(Res, EndLoc);
717 case AsmToken::Minus:
718 Lex(); // Eat the operator.
719 if (ParsePrimaryExpr(Res, EndLoc))
721 Res = MCUnaryExpr::CreateMinus(Res, getContext());
724 Lex(); // Eat the operator.
725 if (ParsePrimaryExpr(Res, EndLoc))
727 Res = MCUnaryExpr::CreatePlus(Res, getContext());
729 case AsmToken::Tilde:
730 Lex(); // Eat the operator.
731 if (ParsePrimaryExpr(Res, EndLoc))
733 Res = MCUnaryExpr::CreateNot(Res, getContext());
738 bool AsmParser::ParseExpression(const MCExpr *&Res) {
740 return ParseExpression(Res, EndLoc);
744 AsmParser::ApplyModifierToExpr(const MCExpr *E,
745 MCSymbolRefExpr::VariantKind Variant) {
746 // Recurse over the given expression, rebuilding it to apply the given variant
747 // if there is exactly one symbol.
748 switch (E->getKind()) {
750 case MCExpr::Constant:
753 case MCExpr::SymbolRef: {
754 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
756 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
757 TokError("invalid variant on expression '" +
758 getTok().getIdentifier() + "' (already modified)");
762 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
765 case MCExpr::Unary: {
766 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
767 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
770 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
773 case MCExpr::Binary: {
774 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
775 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
776 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
781 if (!LHS) LHS = BE->getLHS();
782 if (!RHS) RHS = BE->getRHS();
784 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
788 assert(0 && "Invalid expression kind!");
792 /// ParseExpression - Parse an expression and return it.
794 /// expr ::= expr &&,|| expr -> lowest.
795 /// expr ::= expr |,^,&,! expr
796 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
797 /// expr ::= expr <<,>> expr
798 /// expr ::= expr +,- expr
799 /// expr ::= expr *,/,% expr -> highest.
800 /// expr ::= primaryexpr
802 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
803 // Parse the expression.
805 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
808 // As a special case, we support 'a op b @ modifier' by rewriting the
809 // expression to include the modifier. This is inefficient, but in general we
810 // expect users to use 'a@modifier op b'.
811 if (Lexer.getKind() == AsmToken::At) {
814 if (Lexer.isNot(AsmToken::Identifier))
815 return TokError("unexpected symbol modifier following '@'");
817 MCSymbolRefExpr::VariantKind Variant =
818 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
819 if (Variant == MCSymbolRefExpr::VK_Invalid)
820 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
822 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
824 return TokError("invalid modifier '" + getTok().getIdentifier() +
825 "' (no symbols present)");
833 // Try to constant fold it up front, if possible.
835 if (Res->EvaluateAsAbsolute(Value))
836 Res = MCConstantExpr::Create(Value, getContext());
841 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
843 return ParseParenExpr(Res, EndLoc) ||
844 ParseBinOpRHS(1, Res, EndLoc);
847 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
850 SMLoc StartLoc = Lexer.getLoc();
851 if (ParseExpression(Expr))
854 if (!Expr->EvaluateAsAbsolute(Res))
855 return Error(StartLoc, "expected absolute expression");
860 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
861 MCBinaryExpr::Opcode &Kind) {
864 return 0; // not a binop.
866 // Lowest Precedence: &&, ||
867 case AsmToken::AmpAmp:
868 Kind = MCBinaryExpr::LAnd;
870 case AsmToken::PipePipe:
871 Kind = MCBinaryExpr::LOr;
875 // Low Precedence: |, &, ^
877 // FIXME: gas seems to support '!' as an infix operator?
879 Kind = MCBinaryExpr::Or;
881 case AsmToken::Caret:
882 Kind = MCBinaryExpr::Xor;
885 Kind = MCBinaryExpr::And;
888 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
889 case AsmToken::EqualEqual:
890 Kind = MCBinaryExpr::EQ;
892 case AsmToken::ExclaimEqual:
893 case AsmToken::LessGreater:
894 Kind = MCBinaryExpr::NE;
897 Kind = MCBinaryExpr::LT;
899 case AsmToken::LessEqual:
900 Kind = MCBinaryExpr::LTE;
902 case AsmToken::Greater:
903 Kind = MCBinaryExpr::GT;
905 case AsmToken::GreaterEqual:
906 Kind = MCBinaryExpr::GTE;
909 // Intermediate Precedence: <<, >>
910 case AsmToken::LessLess:
911 Kind = MCBinaryExpr::Shl;
913 case AsmToken::GreaterGreater:
914 Kind = MCBinaryExpr::Shr;
917 // High Intermediate Precedence: +, -
919 Kind = MCBinaryExpr::Add;
921 case AsmToken::Minus:
922 Kind = MCBinaryExpr::Sub;
925 // Highest Precedence: *, /, %
927 Kind = MCBinaryExpr::Mul;
929 case AsmToken::Slash:
930 Kind = MCBinaryExpr::Div;
932 case AsmToken::Percent:
933 Kind = MCBinaryExpr::Mod;
939 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
940 /// Res contains the LHS of the expression on input.
941 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
944 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
945 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
947 // If the next token is lower precedence than we are allowed to eat, return
948 // successfully with what we ate already.
949 if (TokPrec < Precedence)
954 // Eat the next primary expression.
956 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
958 // If BinOp binds less tightly with RHS than the operator after RHS, let
959 // the pending operator take RHS as its LHS.
960 MCBinaryExpr::Opcode Dummy;
961 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
962 if (TokPrec < NextTokPrec) {
963 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
966 // Merge LHS and RHS according to operator.
967 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
975 /// ::= EndOfStatement
976 /// ::= Label* Directive ...Operands... EndOfStatement
977 /// ::= Label* Identifier OperandList* EndOfStatement
978 bool AsmParser::ParseStatement() {
979 if (Lexer.is(AsmToken::EndOfStatement)) {
985 // Statements always start with an identifier or are a full line comment.
986 AsmToken ID = getTok();
987 SMLoc IDLoc = ID.getLoc();
989 int64_t LocalLabelVal = -1;
990 // A full line comment is a '#' as the first token.
991 if (Lexer.is(AsmToken::Hash))
992 return ParseCppHashLineFilenameComment(IDLoc);
994 // Allow an integer followed by a ':' as a directional local label.
995 if (Lexer.is(AsmToken::Integer)) {
996 LocalLabelVal = getTok().getIntVal();
997 if (LocalLabelVal < 0) {
998 if (!TheCondState.Ignore)
999 return TokError("unexpected token at start of statement");
1003 IDVal = getTok().getString();
1004 Lex(); // Consume the integer token to be used as an identifier token.
1005 if (Lexer.getKind() != AsmToken::Colon) {
1006 if (!TheCondState.Ignore)
1007 return TokError("unexpected token at start of statement");
1011 } else if (Lexer.is(AsmToken::Dot)) {
1012 // Treat '.' as a valid identifier in this context.
1016 } else if (ParseIdentifier(IDVal)) {
1017 if (!TheCondState.Ignore)
1018 return TokError("unexpected token at start of statement");
1023 // Handle conditional assembly here before checking for skipping. We
1024 // have to do this so that .endif isn't skipped in a ".if 0" block for
1027 return ParseDirectiveIf(IDLoc);
1028 if (IDVal == ".ifdef")
1029 return ParseDirectiveIfdef(IDLoc, true);
1030 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1031 return ParseDirectiveIfdef(IDLoc, false);
1032 if (IDVal == ".elseif")
1033 return ParseDirectiveElseIf(IDLoc);
1034 if (IDVal == ".else")
1035 return ParseDirectiveElse(IDLoc);
1036 if (IDVal == ".endif")
1037 return ParseDirectiveEndIf(IDLoc);
1039 // If we are in a ".if 0" block, ignore this statement.
1040 if (TheCondState.Ignore) {
1041 EatToEndOfStatement();
1045 // FIXME: Recurse on local labels?
1047 // See what kind of statement we have.
1048 switch (Lexer.getKind()) {
1049 case AsmToken::Colon: {
1050 CheckForValidSection();
1052 // identifier ':' -> Label.
1055 // Diagnose attempt to use '.' as a label.
1057 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1059 // Diagnose attempt to use a variable as a label.
1061 // FIXME: Diagnostics. Note the location of the definition as a label.
1062 // FIXME: This doesn't diagnose assignment to a symbol which has been
1063 // implicitly marked as external.
1065 if (LocalLabelVal == -1)
1066 Sym = getContext().GetOrCreateSymbol(IDVal);
1068 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1069 if (!Sym->isUndefined() || Sym->isVariable())
1070 return Error(IDLoc, "invalid symbol redefinition");
1075 // If we are generating dwarf for assembly source files then gather the
1076 // info to make a dwarf subprogram entry for this label if needed.
1077 if (getContext().getGenDwarfForAssembly())
1078 MCGenDwarfSubprogramEntry::Make(Sym, &getStreamer(), getSourceManager(),
1081 // Consume any end of statement token, if present, to avoid spurious
1082 // AddBlankLine calls().
1083 if (Lexer.is(AsmToken::EndOfStatement)) {
1085 if (Lexer.is(AsmToken::Eof))
1089 return ParseStatement();
1092 case AsmToken::Equal:
1093 // identifier '=' ... -> assignment statement
1096 return ParseAssignment(IDVal, true);
1098 default: // Normal instruction or directive.
1102 // If macros are enabled, check to see if this is a macro instantiation.
1104 if (const Macro *M = MacroMap.lookup(IDVal))
1105 return HandleMacroEntry(IDVal, IDLoc, M);
1107 // Otherwise, we have a normal instruction or directive.
1108 if (IDVal[0] == '.' && IDVal != ".") {
1109 // Assembler features
1110 if (IDVal == ".set" || IDVal == ".equ")
1111 return ParseDirectiveSet(IDVal, true);
1112 if (IDVal == ".equiv")
1113 return ParseDirectiveSet(IDVal, false);
1117 if (IDVal == ".ascii")
1118 return ParseDirectiveAscii(IDVal, false);
1119 if (IDVal == ".asciz" || IDVal == ".string")
1120 return ParseDirectiveAscii(IDVal, true);
1122 if (IDVal == ".byte")
1123 return ParseDirectiveValue(1);
1124 if (IDVal == ".short")
1125 return ParseDirectiveValue(2);
1126 if (IDVal == ".value")
1127 return ParseDirectiveValue(2);
1128 if (IDVal == ".2byte")
1129 return ParseDirectiveValue(2);
1130 if (IDVal == ".long")
1131 return ParseDirectiveValue(4);
1132 if (IDVal == ".int")
1133 return ParseDirectiveValue(4);
1134 if (IDVal == ".4byte")
1135 return ParseDirectiveValue(4);
1136 if (IDVal == ".quad")
1137 return ParseDirectiveValue(8);
1138 if (IDVal == ".8byte")
1139 return ParseDirectiveValue(8);
1140 if (IDVal == ".single" || IDVal == ".float")
1141 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1142 if (IDVal == ".double")
1143 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1145 if (IDVal == ".align") {
1146 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1147 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1149 if (IDVal == ".align32") {
1150 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1151 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1153 if (IDVal == ".balign")
1154 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1155 if (IDVal == ".balignw")
1156 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1157 if (IDVal == ".balignl")
1158 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1159 if (IDVal == ".p2align")
1160 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1161 if (IDVal == ".p2alignw")
1162 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1163 if (IDVal == ".p2alignl")
1164 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1166 if (IDVal == ".org")
1167 return ParseDirectiveOrg();
1169 if (IDVal == ".fill")
1170 return ParseDirectiveFill();
1171 if (IDVal == ".space" || IDVal == ".skip")
1172 return ParseDirectiveSpace();
1173 if (IDVal == ".zero")
1174 return ParseDirectiveZero();
1176 // Symbol attribute directives
1178 if (IDVal == ".globl" || IDVal == ".global")
1179 return ParseDirectiveSymbolAttribute(MCSA_Global);
1180 if (IDVal == ".indirect_symbol")
1181 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1182 if (IDVal == ".lazy_reference")
1183 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1184 if (IDVal == ".no_dead_strip")
1185 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1186 if (IDVal == ".symbol_resolver")
1187 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1188 if (IDVal == ".private_extern")
1189 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1190 if (IDVal == ".reference")
1191 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1192 if (IDVal == ".weak_definition")
1193 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1194 if (IDVal == ".weak_reference")
1195 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1196 if (IDVal == ".weak_def_can_be_hidden")
1197 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1199 if (IDVal == ".comm" || IDVal == ".common")
1200 return ParseDirectiveComm(/*IsLocal=*/false);
1201 if (IDVal == ".lcomm")
1202 return ParseDirectiveComm(/*IsLocal=*/true);
1204 if (IDVal == ".abort")
1205 return ParseDirectiveAbort();
1206 if (IDVal == ".include")
1207 return ParseDirectiveInclude();
1208 if (IDVal == ".incbin")
1209 return ParseDirectiveIncbin();
1211 if (IDVal == ".code16")
1212 return TokError(Twine(IDVal) + " not supported yet");
1214 // Look up the handler in the handler table.
1215 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1216 DirectiveMap.lookup(IDVal);
1218 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1220 // Target hook for parsing target specific directives.
1221 if (!getTargetParser().ParseDirective(ID))
1224 bool retval = Warning(IDLoc, "ignoring directive for now");
1225 EatToEndOfStatement();
1229 CheckForValidSection();
1231 // Canonicalize the opcode to lower case.
1232 SmallString<128> Opcode;
1233 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1234 Opcode.push_back(tolower(IDVal[i]));
1236 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1237 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1240 // Dump the parsed representation, if requested.
1241 if (getShowParsedOperands()) {
1242 SmallString<256> Str;
1243 raw_svector_ostream OS(Str);
1244 OS << "parsed instruction: [";
1245 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1248 ParsedOperands[i]->print(OS);
1252 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1255 // If we are generating dwarf for assembly source files and the current
1256 // section is the initial text section then generate a .loc directive for
1258 if (!HadError && getContext().getGenDwarfForAssembly() &&
1259 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1260 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1261 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1262 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1263 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1267 // If parsing succeeded, match the instruction.
1269 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1272 // Free any parsed operands.
1273 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1274 delete ParsedOperands[i];
1276 // Don't skip the rest of the line, the instruction parser is responsible for
1281 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1282 /// since they may not be able to be tokenized to get to the end of line token.
1283 void AsmParser::EatToEndOfLine() {
1284 if (!Lexer.is(AsmToken::EndOfStatement))
1285 Lexer.LexUntilEndOfLine();
1290 /// ParseCppHashLineFilenameComment as this:
1291 /// ::= # number "filename"
1292 /// or just as a full line comment if it doesn't have a number and a string.
1293 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1294 Lex(); // Eat the hash token.
1296 if (getLexer().isNot(AsmToken::Integer)) {
1297 // Consume the line since in cases it is not a well-formed line directive,
1298 // as if were simply a full line comment.
1303 int64_t LineNumber = getTok().getIntVal();
1306 if (getLexer().isNot(AsmToken::String)) {
1311 StringRef Filename = getTok().getString();
1312 // Get rid of the enclosing quotes.
1313 Filename = Filename.substr(1, Filename.size()-2);
1315 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1317 CppHashFilename = Filename;
1318 CppHashLineNumber = LineNumber;
1320 // Ignore any trailing characters, they're just comment.
1325 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1326 /// for the Filename and LineNo if any in the diagnostic.
1327 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1328 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1329 raw_ostream &OS = errs();
1331 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1332 const SMLoc &DiagLoc = Diag.getLoc();
1333 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1334 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1336 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1337 // before printing the message.
1338 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1339 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1340 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1341 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1344 // If we have not parsed a cpp hash line filename comment or the source
1345 // manager changed or buffer changed (like in a nested include) then just
1346 // print the normal diagnostic using its Filename and LineNo.
1347 if (!Parser->CppHashLineNumber ||
1348 &DiagSrcMgr != &Parser->SrcMgr ||
1349 DiagBuf != CppHashBuf) {
1350 if (Parser->SavedDiagHandler)
1351 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1357 // Use the CppHashFilename and calculate a line number based on the
1358 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1360 const std::string Filename = Parser->CppHashFilename;
1362 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1363 int CppHashLocLineNo =
1364 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1365 int LineNo = Parser->CppHashLineNumber - 1 +
1366 (DiagLocLineNo - CppHashLocLineNo);
1368 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1369 Filename, LineNo, Diag.getColumnNo(),
1370 Diag.getKind(), Diag.getMessage(),
1371 Diag.getLineContents(), Diag.getRanges());
1373 if (Parser->SavedDiagHandler)
1374 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1376 NewDiag.print(0, OS);
1379 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1380 const std::vector<StringRef> &Parameters,
1381 const std::vector<std::vector<AsmToken> > &A,
1383 raw_svector_ostream OS(Buf);
1384 unsigned NParameters = Parameters.size();
1385 if (NParameters != 0 && NParameters != A.size())
1386 return Error(L, "Wrong number of arguments");
1388 while (!Body.empty()) {
1389 // Scan for the next substitution.
1390 std::size_t End = Body.size(), Pos = 0;
1391 for (; Pos != End; ++Pos) {
1392 // Check for a substitution or escape.
1394 // This macro has no parameters, look for $0, $1, etc.
1395 if (Body[Pos] != '$' || Pos + 1 == End)
1398 char Next = Body[Pos + 1];
1399 if (Next == '$' || Next == 'n' || isdigit(Next))
1402 // This macro has parameters, look for \foo, \bar, etc.
1403 if (Body[Pos] == '\\' && Pos + 1 != End)
1409 OS << Body.slice(0, Pos);
1411 // Check if we reached the end.
1416 switch (Body[Pos+1]) {
1422 // $n => number of arguments
1427 // $[0-9] => argument
1429 // Missing arguments are ignored.
1430 unsigned Index = Body[Pos+1] - '0';
1431 if (Index >= A.size())
1434 // Otherwise substitute with the token values, with spaces eliminated.
1435 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1436 ie = A[Index].end(); it != ie; ++it)
1437 OS << it->getString();
1443 unsigned I = Pos + 1;
1444 while (isalnum(Body[I]) && I + 1 != End)
1447 const char *Begin = Body.data() + Pos +1;
1448 StringRef Argument(Begin, I - (Pos +1));
1450 for (; Index < NParameters; ++Index)
1451 if (Parameters[Index] == Argument)
1454 // FIXME: We should error at the macro definition.
1455 if (Index == NParameters)
1456 return Error(L, "Parameter not found");
1458 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1459 ie = A[Index].end(); it != ie; ++it)
1460 OS << it->getString();
1462 Pos += 1 + Argument.size();
1464 // Update the scan point.
1465 Body = Body.substr(Pos);
1468 // We include the .endmacro in the buffer as our queue to exit the macro
1470 OS << ".endmacro\n";
1474 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1476 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1480 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1482 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1483 // this, although we should protect against infinite loops.
1484 if (ActiveMacros.size() == 20)
1485 return TokError("macros cannot be nested more than 20 levels deep");
1487 // Parse the macro instantiation arguments.
1488 std::vector<std::vector<AsmToken> > MacroArguments;
1489 MacroArguments.push_back(std::vector<AsmToken>());
1490 unsigned ParenLevel = 0;
1492 if (Lexer.is(AsmToken::Eof))
1493 return TokError("unexpected token in macro instantiation");
1494 if (Lexer.is(AsmToken::EndOfStatement))
1497 // If we aren't inside parentheses and this is a comma, start a new token
1499 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1500 MacroArguments.push_back(std::vector<AsmToken>());
1502 // Adjust the current parentheses level.
1503 if (Lexer.is(AsmToken::LParen))
1505 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1508 // Append the token to the current argument list.
1509 MacroArguments.back().push_back(getTok());
1514 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1515 // to hold the macro body with substitutions.
1516 SmallString<256> Buf;
1517 StringRef Body = M->Body;
1519 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1522 MemoryBuffer *Instantiation =
1523 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1525 // Create the macro instantiation object and add to the current macro
1526 // instantiation stack.
1527 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1530 ActiveMacros.push_back(MI);
1532 // Jump to the macro instantiation and prime the lexer.
1533 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1534 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1540 void AsmParser::HandleMacroExit() {
1541 // Jump to the EndOfStatement we should return to, and consume it.
1542 JumpToLoc(ActiveMacros.back()->ExitLoc);
1545 // Pop the instantiation entry.
1546 delete ActiveMacros.back();
1547 ActiveMacros.pop_back();
1550 static void MarkUsed(const MCExpr *Value) {
1551 switch (Value->getKind()) {
1552 case MCExpr::Binary:
1553 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1554 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1556 case MCExpr::Target:
1557 case MCExpr::Constant:
1559 case MCExpr::SymbolRef: {
1560 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1564 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1569 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1570 // FIXME: Use better location, we should use proper tokens.
1571 SMLoc EqualLoc = Lexer.getLoc();
1573 const MCExpr *Value;
1574 if (ParseExpression(Value))
1579 if (Lexer.isNot(AsmToken::EndOfStatement))
1580 return TokError("unexpected token in assignment");
1582 // Error on assignment to '.'.
1584 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1585 "(use '.space' or '.org').)"));
1588 // Eat the end of statement marker.
1591 // Validate that the LHS is allowed to be a variable (either it has not been
1592 // used as a symbol, or it is an absolute symbol).
1593 MCSymbol *Sym = getContext().LookupSymbol(Name);
1595 // Diagnose assignment to a label.
1597 // FIXME: Diagnostics. Note the location of the definition as a label.
1598 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1599 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1600 ; // Allow redefinitions of undefined symbols only used in directives.
1601 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1602 return Error(EqualLoc, "redefinition of '" + Name + "'");
1603 else if (!Sym->isVariable())
1604 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1605 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1606 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1609 // Don't count these checks as uses.
1610 Sym->setUsed(false);
1612 Sym = getContext().GetOrCreateSymbol(Name);
1614 // FIXME: Handle '.'.
1616 // Do the assignment.
1617 Out.EmitAssignment(Sym, Value);
1622 /// ParseIdentifier:
1625 bool AsmParser::ParseIdentifier(StringRef &Res) {
1626 // The assembler has relaxed rules for accepting identifiers, in particular we
1627 // allow things like '.globl $foo', which would normally be separate
1628 // tokens. At this level, we have already lexed so we cannot (currently)
1629 // handle this as a context dependent token, instead we detect adjacent tokens
1630 // and return the combined identifier.
1631 if (Lexer.is(AsmToken::Dollar)) {
1632 SMLoc DollarLoc = getLexer().getLoc();
1634 // Consume the dollar sign, and check for a following identifier.
1636 if (Lexer.isNot(AsmToken::Identifier))
1639 // We have a '$' followed by an identifier, make sure they are adjacent.
1640 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1643 // Construct the joined identifier and consume the token.
1644 Res = StringRef(DollarLoc.getPointer(),
1645 getTok().getIdentifier().size() + 1);
1650 if (Lexer.isNot(AsmToken::Identifier) &&
1651 Lexer.isNot(AsmToken::String))
1654 Res = getTok().getIdentifier();
1656 Lex(); // Consume the identifier token.
1661 /// ParseDirectiveSet:
1662 /// ::= .equ identifier ',' expression
1663 /// ::= .equiv identifier ',' expression
1664 /// ::= .set identifier ',' expression
1665 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1668 if (ParseIdentifier(Name))
1669 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1671 if (getLexer().isNot(AsmToken::Comma))
1672 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1675 return ParseAssignment(Name, allow_redef);
1678 bool AsmParser::ParseEscapedString(std::string &Data) {
1679 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1682 StringRef Str = getTok().getStringContents();
1683 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1684 if (Str[i] != '\\') {
1689 // Recognize escaped characters. Note that this escape semantics currently
1690 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1693 return TokError("unexpected backslash at end of string");
1695 // Recognize octal sequences.
1696 if ((unsigned) (Str[i] - '0') <= 7) {
1697 // Consume up to three octal characters.
1698 unsigned Value = Str[i] - '0';
1700 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1702 Value = Value * 8 + (Str[i] - '0');
1704 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1706 Value = Value * 8 + (Str[i] - '0');
1711 return TokError("invalid octal escape sequence (out of range)");
1713 Data += (unsigned char) Value;
1717 // Otherwise recognize individual escapes.
1720 // Just reject invalid escape sequences for now.
1721 return TokError("invalid escape sequence (unrecognized character)");
1723 case 'b': Data += '\b'; break;
1724 case 'f': Data += '\f'; break;
1725 case 'n': Data += '\n'; break;
1726 case 'r': Data += '\r'; break;
1727 case 't': Data += '\t'; break;
1728 case '"': Data += '"'; break;
1729 case '\\': Data += '\\'; break;
1736 /// ParseDirectiveAscii:
1737 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1738 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1739 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1740 CheckForValidSection();
1743 if (getLexer().isNot(AsmToken::String))
1744 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1747 if (ParseEscapedString(Data))
1750 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1752 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1756 if (getLexer().is(AsmToken::EndOfStatement))
1759 if (getLexer().isNot(AsmToken::Comma))
1760 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1769 /// ParseDirectiveValue
1770 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1771 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1772 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1773 CheckForValidSection();
1776 const MCExpr *Value;
1777 SMLoc ExprLoc = getLexer().getLoc();
1778 if (ParseExpression(Value))
1781 // Special case constant expressions to match code generator.
1782 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1783 assert(Size <= 8 && "Invalid size");
1784 uint64_t IntValue = MCE->getValue();
1785 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1786 return Error(ExprLoc, "literal value out of range for directive");
1787 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1789 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1791 if (getLexer().is(AsmToken::EndOfStatement))
1794 // FIXME: Improve diagnostic.
1795 if (getLexer().isNot(AsmToken::Comma))
1796 return TokError("unexpected token in directive");
1805 /// ParseDirectiveRealValue
1806 /// ::= (.single | .double) [ expression (, expression)* ]
1807 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1808 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1809 CheckForValidSection();
1812 // We don't truly support arithmetic on floating point expressions, so we
1813 // have to manually parse unary prefixes.
1815 if (getLexer().is(AsmToken::Minus)) {
1818 } else if (getLexer().is(AsmToken::Plus))
1821 if (getLexer().isNot(AsmToken::Integer) &&
1822 getLexer().isNot(AsmToken::Real) &&
1823 getLexer().isNot(AsmToken::Identifier))
1824 return TokError("unexpected token in directive");
1826 // Convert to an APFloat.
1827 APFloat Value(Semantics);
1828 StringRef IDVal = getTok().getString();
1829 if (getLexer().is(AsmToken::Identifier)) {
1830 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1831 Value = APFloat::getInf(Semantics);
1832 else if (!IDVal.compare_lower("nan"))
1833 Value = APFloat::getNaN(Semantics, false, ~0);
1835 return TokError("invalid floating point literal");
1836 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1837 APFloat::opInvalidOp)
1838 return TokError("invalid floating point literal");
1842 // Consume the numeric token.
1845 // Emit the value as an integer.
1846 APInt AsInt = Value.bitcastToAPInt();
1847 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1848 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1850 if (getLexer().is(AsmToken::EndOfStatement))
1853 if (getLexer().isNot(AsmToken::Comma))
1854 return TokError("unexpected token in directive");
1863 /// ParseDirectiveSpace
1864 /// ::= .space expression [ , expression ]
1865 bool AsmParser::ParseDirectiveSpace() {
1866 CheckForValidSection();
1869 if (ParseAbsoluteExpression(NumBytes))
1872 int64_t FillExpr = 0;
1873 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1874 if (getLexer().isNot(AsmToken::Comma))
1875 return TokError("unexpected token in '.space' directive");
1878 if (ParseAbsoluteExpression(FillExpr))
1881 if (getLexer().isNot(AsmToken::EndOfStatement))
1882 return TokError("unexpected token in '.space' directive");
1888 return TokError("invalid number of bytes in '.space' directive");
1890 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1891 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1896 /// ParseDirectiveZero
1897 /// ::= .zero expression
1898 bool AsmParser::ParseDirectiveZero() {
1899 CheckForValidSection();
1902 if (ParseAbsoluteExpression(NumBytes))
1906 if (getLexer().is(AsmToken::Comma)) {
1908 if (ParseAbsoluteExpression(Val))
1912 if (getLexer().isNot(AsmToken::EndOfStatement))
1913 return TokError("unexpected token in '.zero' directive");
1917 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1922 /// ParseDirectiveFill
1923 /// ::= .fill expression , expression , expression
1924 bool AsmParser::ParseDirectiveFill() {
1925 CheckForValidSection();
1928 if (ParseAbsoluteExpression(NumValues))
1931 if (getLexer().isNot(AsmToken::Comma))
1932 return TokError("unexpected token in '.fill' directive");
1936 if (ParseAbsoluteExpression(FillSize))
1939 if (getLexer().isNot(AsmToken::Comma))
1940 return TokError("unexpected token in '.fill' directive");
1944 if (ParseAbsoluteExpression(FillExpr))
1947 if (getLexer().isNot(AsmToken::EndOfStatement))
1948 return TokError("unexpected token in '.fill' directive");
1952 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1953 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1955 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1956 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1961 /// ParseDirectiveOrg
1962 /// ::= .org expression [ , expression ]
1963 bool AsmParser::ParseDirectiveOrg() {
1964 CheckForValidSection();
1966 const MCExpr *Offset;
1967 if (ParseExpression(Offset))
1970 // Parse optional fill expression.
1971 int64_t FillExpr = 0;
1972 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1973 if (getLexer().isNot(AsmToken::Comma))
1974 return TokError("unexpected token in '.org' directive");
1977 if (ParseAbsoluteExpression(FillExpr))
1980 if (getLexer().isNot(AsmToken::EndOfStatement))
1981 return TokError("unexpected token in '.org' directive");
1986 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1987 // has to be relative to the current section.
1988 getStreamer().EmitValueToOffset(Offset, FillExpr);
1993 /// ParseDirectiveAlign
1994 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1995 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1996 CheckForValidSection();
1998 SMLoc AlignmentLoc = getLexer().getLoc();
2000 if (ParseAbsoluteExpression(Alignment))
2004 bool HasFillExpr = false;
2005 int64_t FillExpr = 0;
2006 int64_t MaxBytesToFill = 0;
2007 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2008 if (getLexer().isNot(AsmToken::Comma))
2009 return TokError("unexpected token in directive");
2012 // The fill expression can be omitted while specifying a maximum number of
2013 // alignment bytes, e.g:
2015 if (getLexer().isNot(AsmToken::Comma)) {
2017 if (ParseAbsoluteExpression(FillExpr))
2021 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2022 if (getLexer().isNot(AsmToken::Comma))
2023 return TokError("unexpected token in directive");
2026 MaxBytesLoc = getLexer().getLoc();
2027 if (ParseAbsoluteExpression(MaxBytesToFill))
2030 if (getLexer().isNot(AsmToken::EndOfStatement))
2031 return TokError("unexpected token in directive");
2040 // Compute alignment in bytes.
2042 // FIXME: Diagnose overflow.
2043 if (Alignment >= 32) {
2044 Error(AlignmentLoc, "invalid alignment value");
2048 Alignment = 1ULL << Alignment;
2051 // Diagnose non-sensical max bytes to align.
2052 if (MaxBytesLoc.isValid()) {
2053 if (MaxBytesToFill < 1) {
2054 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2055 "many bytes, ignoring maximum bytes expression");
2059 if (MaxBytesToFill >= Alignment) {
2060 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2066 // Check whether we should use optimal code alignment for this .align
2068 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2069 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2070 ValueSize == 1 && UseCodeAlign) {
2071 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2073 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2074 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2081 /// ParseDirectiveSymbolAttribute
2082 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2083 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2084 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2087 SMLoc Loc = getTok().getLoc();
2089 if (ParseIdentifier(Name))
2090 return Error(Loc, "expected identifier in directive");
2092 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2094 // Assembler local symbols don't make any sense here. Complain loudly.
2095 if (Sym->isTemporary())
2096 return Error(Loc, "non-local symbol required in directive");
2098 getStreamer().EmitSymbolAttribute(Sym, Attr);
2100 if (getLexer().is(AsmToken::EndOfStatement))
2103 if (getLexer().isNot(AsmToken::Comma))
2104 return TokError("unexpected token in directive");
2113 /// ParseDirectiveComm
2114 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2115 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2116 CheckForValidSection();
2118 SMLoc IDLoc = getLexer().getLoc();
2120 if (ParseIdentifier(Name))
2121 return TokError("expected identifier in directive");
2123 // Handle the identifier as the key symbol.
2124 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2126 if (getLexer().isNot(AsmToken::Comma))
2127 return TokError("unexpected token in directive");
2131 SMLoc SizeLoc = getLexer().getLoc();
2132 if (ParseAbsoluteExpression(Size))
2135 int64_t Pow2Alignment = 0;
2136 SMLoc Pow2AlignmentLoc;
2137 if (getLexer().is(AsmToken::Comma)) {
2139 Pow2AlignmentLoc = getLexer().getLoc();
2140 if (ParseAbsoluteExpression(Pow2Alignment))
2143 // If this target takes alignments in bytes (not log) validate and convert.
2144 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2145 if (!isPowerOf2_64(Pow2Alignment))
2146 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2147 Pow2Alignment = Log2_64(Pow2Alignment);
2151 if (getLexer().isNot(AsmToken::EndOfStatement))
2152 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2156 // NOTE: a size of zero for a .comm should create a undefined symbol
2157 // but a size of .lcomm creates a bss symbol of size zero.
2159 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2160 "be less than zero");
2162 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2163 // may internally end up wanting an alignment in bytes.
2164 // FIXME: Diagnose overflow.
2165 if (Pow2Alignment < 0)
2166 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2167 "alignment, can't be less than zero");
2169 if (!Sym->isUndefined())
2170 return Error(IDLoc, "invalid symbol redefinition");
2172 // '.lcomm' is equivalent to '.zerofill'.
2173 // Create the Symbol as a common or local common with Size and Pow2Alignment
2175 getStreamer().EmitZerofill(Ctx.getMachOSection(
2176 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2177 0, SectionKind::getBSS()),
2178 Sym, Size, 1 << Pow2Alignment);
2182 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2186 /// ParseDirectiveAbort
2187 /// ::= .abort [... message ...]
2188 bool AsmParser::ParseDirectiveAbort() {
2189 // FIXME: Use loc from directive.
2190 SMLoc Loc = getLexer().getLoc();
2192 StringRef Str = ParseStringToEndOfStatement();
2193 if (getLexer().isNot(AsmToken::EndOfStatement))
2194 return TokError("unexpected token in '.abort' directive");
2199 Error(Loc, ".abort detected. Assembly stopping.");
2201 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2202 // FIXME: Actually abort assembly here.
2207 /// ParseDirectiveInclude
2208 /// ::= .include "filename"
2209 bool AsmParser::ParseDirectiveInclude() {
2210 if (getLexer().isNot(AsmToken::String))
2211 return TokError("expected string in '.include' directive");
2213 std::string Filename = getTok().getString();
2214 SMLoc IncludeLoc = getLexer().getLoc();
2217 if (getLexer().isNot(AsmToken::EndOfStatement))
2218 return TokError("unexpected token in '.include' directive");
2220 // Strip the quotes.
2221 Filename = Filename.substr(1, Filename.size()-2);
2223 // Attempt to switch the lexer to the included file before consuming the end
2224 // of statement to avoid losing it when we switch.
2225 if (EnterIncludeFile(Filename)) {
2226 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2233 /// ParseDirectiveIncbin
2234 /// ::= .incbin "filename"
2235 bool AsmParser::ParseDirectiveIncbin() {
2236 if (getLexer().isNot(AsmToken::String))
2237 return TokError("expected string in '.incbin' directive");
2239 std::string Filename = getTok().getString();
2240 SMLoc IncbinLoc = getLexer().getLoc();
2243 if (getLexer().isNot(AsmToken::EndOfStatement))
2244 return TokError("unexpected token in '.incbin' directive");
2246 // Strip the quotes.
2247 Filename = Filename.substr(1, Filename.size()-2);
2249 // Attempt to process the included file.
2250 if (ProcessIncbinFile(Filename)) {
2251 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2258 /// ParseDirectiveIf
2259 /// ::= .if expression
2260 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2261 TheCondStack.push_back(TheCondState);
2262 TheCondState.TheCond = AsmCond::IfCond;
2263 if(TheCondState.Ignore) {
2264 EatToEndOfStatement();
2268 if (ParseAbsoluteExpression(ExprValue))
2271 if (getLexer().isNot(AsmToken::EndOfStatement))
2272 return TokError("unexpected token in '.if' directive");
2276 TheCondState.CondMet = ExprValue;
2277 TheCondState.Ignore = !TheCondState.CondMet;
2283 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2285 TheCondStack.push_back(TheCondState);
2286 TheCondState.TheCond = AsmCond::IfCond;
2288 if (TheCondState.Ignore) {
2289 EatToEndOfStatement();
2291 if (ParseIdentifier(Name))
2292 return TokError("expected identifier after '.ifdef'");
2296 MCSymbol *Sym = getContext().LookupSymbol(Name);
2299 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2301 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2302 TheCondState.Ignore = !TheCondState.CondMet;
2308 /// ParseDirectiveElseIf
2309 /// ::= .elseif expression
2310 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2311 if (TheCondState.TheCond != AsmCond::IfCond &&
2312 TheCondState.TheCond != AsmCond::ElseIfCond)
2313 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2315 TheCondState.TheCond = AsmCond::ElseIfCond;
2317 bool LastIgnoreState = false;
2318 if (!TheCondStack.empty())
2319 LastIgnoreState = TheCondStack.back().Ignore;
2320 if (LastIgnoreState || TheCondState.CondMet) {
2321 TheCondState.Ignore = true;
2322 EatToEndOfStatement();
2326 if (ParseAbsoluteExpression(ExprValue))
2329 if (getLexer().isNot(AsmToken::EndOfStatement))
2330 return TokError("unexpected token in '.elseif' directive");
2333 TheCondState.CondMet = ExprValue;
2334 TheCondState.Ignore = !TheCondState.CondMet;
2340 /// ParseDirectiveElse
2342 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2343 if (getLexer().isNot(AsmToken::EndOfStatement))
2344 return TokError("unexpected token in '.else' directive");
2348 if (TheCondState.TheCond != AsmCond::IfCond &&
2349 TheCondState.TheCond != AsmCond::ElseIfCond)
2350 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2352 TheCondState.TheCond = AsmCond::ElseCond;
2353 bool LastIgnoreState = false;
2354 if (!TheCondStack.empty())
2355 LastIgnoreState = TheCondStack.back().Ignore;
2356 if (LastIgnoreState || TheCondState.CondMet)
2357 TheCondState.Ignore = true;
2359 TheCondState.Ignore = false;
2364 /// ParseDirectiveEndIf
2366 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2367 if (getLexer().isNot(AsmToken::EndOfStatement))
2368 return TokError("unexpected token in '.endif' directive");
2372 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2373 TheCondStack.empty())
2374 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2376 if (!TheCondStack.empty()) {
2377 TheCondState = TheCondStack.back();
2378 TheCondStack.pop_back();
2384 /// ParseDirectiveFile
2385 /// ::= .file [number] filename
2386 /// ::= .file number directory filename
2387 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2388 // FIXME: I'm not sure what this is.
2389 int64_t FileNumber = -1;
2390 SMLoc FileNumberLoc = getLexer().getLoc();
2391 if (getLexer().is(AsmToken::Integer)) {
2392 FileNumber = getTok().getIntVal();
2396 return TokError("file number less than one");
2399 if (getLexer().isNot(AsmToken::String))
2400 return TokError("unexpected token in '.file' directive");
2402 // Usually the directory and filename together, otherwise just the directory.
2403 StringRef Path = getTok().getString();
2404 Path = Path.substr(1, Path.size()-2);
2407 StringRef Directory;
2409 if (getLexer().is(AsmToken::String)) {
2410 if (FileNumber == -1)
2411 return TokError("explicit path specified, but no file number");
2412 Filename = getTok().getString();
2413 Filename = Filename.substr(1, Filename.size()-2);
2420 if (getLexer().isNot(AsmToken::EndOfStatement))
2421 return TokError("unexpected token in '.file' directive");
2423 if (getContext().getGenDwarfForAssembly() == true)
2424 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2425 "used to generate dwarf debug info for assembly code");
2427 if (FileNumber == -1)
2428 getStreamer().EmitFileDirective(Filename);
2430 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2431 Error(FileNumberLoc, "file number already allocated");
2437 /// ParseDirectiveLine
2438 /// ::= .line [number]
2439 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2440 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2441 if (getLexer().isNot(AsmToken::Integer))
2442 return TokError("unexpected token in '.line' directive");
2444 int64_t LineNumber = getTok().getIntVal();
2448 // FIXME: Do something with the .line.
2451 if (getLexer().isNot(AsmToken::EndOfStatement))
2452 return TokError("unexpected token in '.line' directive");
2458 /// ParseDirectiveLoc
2459 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2460 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2461 /// The first number is a file number, must have been previously assigned with
2462 /// a .file directive, the second number is the line number and optionally the
2463 /// third number is a column position (zero if not specified). The remaining
2464 /// optional items are .loc sub-directives.
2465 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2467 if (getLexer().isNot(AsmToken::Integer))
2468 return TokError("unexpected token in '.loc' directive");
2469 int64_t FileNumber = getTok().getIntVal();
2471 return TokError("file number less than one in '.loc' directive");
2472 if (!getContext().isValidDwarfFileNumber(FileNumber))
2473 return TokError("unassigned file number in '.loc' directive");
2476 int64_t LineNumber = 0;
2477 if (getLexer().is(AsmToken::Integer)) {
2478 LineNumber = getTok().getIntVal();
2480 return TokError("line number less than one in '.loc' directive");
2484 int64_t ColumnPos = 0;
2485 if (getLexer().is(AsmToken::Integer)) {
2486 ColumnPos = getTok().getIntVal();
2488 return TokError("column position less than zero in '.loc' directive");
2492 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2494 int64_t Discriminator = 0;
2495 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2497 if (getLexer().is(AsmToken::EndOfStatement))
2501 SMLoc Loc = getTok().getLoc();
2502 if (getParser().ParseIdentifier(Name))
2503 return TokError("unexpected token in '.loc' directive");
2505 if (Name == "basic_block")
2506 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2507 else if (Name == "prologue_end")
2508 Flags |= DWARF2_FLAG_PROLOGUE_END;
2509 else if (Name == "epilogue_begin")
2510 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2511 else if (Name == "is_stmt") {
2512 SMLoc Loc = getTok().getLoc();
2513 const MCExpr *Value;
2514 if (getParser().ParseExpression(Value))
2516 // The expression must be the constant 0 or 1.
2517 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2518 int Value = MCE->getValue();
2520 Flags &= ~DWARF2_FLAG_IS_STMT;
2521 else if (Value == 1)
2522 Flags |= DWARF2_FLAG_IS_STMT;
2524 return Error(Loc, "is_stmt value not 0 or 1");
2527 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2530 else if (Name == "isa") {
2531 SMLoc Loc = getTok().getLoc();
2532 const MCExpr *Value;
2533 if (getParser().ParseExpression(Value))
2535 // The expression must be a constant greater or equal to 0.
2536 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2537 int Value = MCE->getValue();
2539 return Error(Loc, "isa number less than zero");
2543 return Error(Loc, "isa number not a constant value");
2546 else if (Name == "discriminator") {
2547 if (getParser().ParseAbsoluteExpression(Discriminator))
2551 return Error(Loc, "unknown sub-directive in '.loc' directive");
2554 if (getLexer().is(AsmToken::EndOfStatement))
2559 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2560 Isa, Discriminator, StringRef());
2565 /// ParseDirectiveStabs
2566 /// ::= .stabs string, number, number, number
2567 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2568 SMLoc DirectiveLoc) {
2569 return TokError("unsupported directive '" + Directive + "'");
2572 /// ParseDirectiveCFISections
2573 /// ::= .cfi_sections section [, section]
2574 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2575 SMLoc DirectiveLoc) {
2580 if (getParser().ParseIdentifier(Name))
2581 return TokError("Expected an identifier");
2583 if (Name == ".eh_frame")
2585 else if (Name == ".debug_frame")
2588 if (getLexer().is(AsmToken::Comma)) {
2591 if (getParser().ParseIdentifier(Name))
2592 return TokError("Expected an identifier");
2594 if (Name == ".eh_frame")
2596 else if (Name == ".debug_frame")
2600 getStreamer().EmitCFISections(EH, Debug);
2605 /// ParseDirectiveCFIStartProc
2606 /// ::= .cfi_startproc
2607 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2608 SMLoc DirectiveLoc) {
2609 getStreamer().EmitCFIStartProc();
2613 /// ParseDirectiveCFIEndProc
2614 /// ::= .cfi_endproc
2615 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2616 getStreamer().EmitCFIEndProc();
2620 /// ParseRegisterOrRegisterNumber - parse register name or number.
2621 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2622 SMLoc DirectiveLoc) {
2625 if (getLexer().isNot(AsmToken::Integer)) {
2626 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2629 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2631 return getParser().ParseAbsoluteExpression(Register);
2636 /// ParseDirectiveCFIDefCfa
2637 /// ::= .cfi_def_cfa register, offset
2638 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2639 SMLoc DirectiveLoc) {
2640 int64_t Register = 0;
2641 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2644 if (getLexer().isNot(AsmToken::Comma))
2645 return TokError("unexpected token in directive");
2649 if (getParser().ParseAbsoluteExpression(Offset))
2652 getStreamer().EmitCFIDefCfa(Register, Offset);
2656 /// ParseDirectiveCFIDefCfaOffset
2657 /// ::= .cfi_def_cfa_offset offset
2658 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2659 SMLoc DirectiveLoc) {
2661 if (getParser().ParseAbsoluteExpression(Offset))
2664 getStreamer().EmitCFIDefCfaOffset(Offset);
2668 /// ParseDirectiveCFIAdjustCfaOffset
2669 /// ::= .cfi_adjust_cfa_offset adjustment
2670 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2671 SMLoc DirectiveLoc) {
2672 int64_t Adjustment = 0;
2673 if (getParser().ParseAbsoluteExpression(Adjustment))
2676 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2680 /// ParseDirectiveCFIDefCfaRegister
2681 /// ::= .cfi_def_cfa_register register
2682 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2683 SMLoc DirectiveLoc) {
2684 int64_t Register = 0;
2685 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2688 getStreamer().EmitCFIDefCfaRegister(Register);
2692 /// ParseDirectiveCFIOffset
2693 /// ::= .cfi_offset register, offset
2694 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2695 int64_t Register = 0;
2698 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2701 if (getLexer().isNot(AsmToken::Comma))
2702 return TokError("unexpected token in directive");
2705 if (getParser().ParseAbsoluteExpression(Offset))
2708 getStreamer().EmitCFIOffset(Register, Offset);
2712 /// ParseDirectiveCFIRelOffset
2713 /// ::= .cfi_rel_offset register, offset
2714 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2715 SMLoc DirectiveLoc) {
2716 int64_t Register = 0;
2718 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2721 if (getLexer().isNot(AsmToken::Comma))
2722 return TokError("unexpected token in directive");
2726 if (getParser().ParseAbsoluteExpression(Offset))
2729 getStreamer().EmitCFIRelOffset(Register, Offset);
2733 static bool isValidEncoding(int64_t Encoding) {
2734 if (Encoding & ~0xff)
2737 if (Encoding == dwarf::DW_EH_PE_omit)
2740 const unsigned Format = Encoding & 0xf;
2741 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2742 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2743 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2744 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2747 const unsigned Application = Encoding & 0x70;
2748 if (Application != dwarf::DW_EH_PE_absptr &&
2749 Application != dwarf::DW_EH_PE_pcrel)
2755 /// ParseDirectiveCFIPersonalityOrLsda
2756 /// ::= .cfi_personality encoding, [symbol_name]
2757 /// ::= .cfi_lsda encoding, [symbol_name]
2758 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2759 SMLoc DirectiveLoc) {
2760 int64_t Encoding = 0;
2761 if (getParser().ParseAbsoluteExpression(Encoding))
2763 if (Encoding == dwarf::DW_EH_PE_omit)
2766 if (!isValidEncoding(Encoding))
2767 return TokError("unsupported encoding.");
2769 if (getLexer().isNot(AsmToken::Comma))
2770 return TokError("unexpected token in directive");
2774 if (getParser().ParseIdentifier(Name))
2775 return TokError("expected identifier in directive");
2777 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2779 if (IDVal == ".cfi_personality")
2780 getStreamer().EmitCFIPersonality(Sym, Encoding);
2782 assert(IDVal == ".cfi_lsda");
2783 getStreamer().EmitCFILsda(Sym, Encoding);
2788 /// ParseDirectiveCFIRememberState
2789 /// ::= .cfi_remember_state
2790 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2791 SMLoc DirectiveLoc) {
2792 getStreamer().EmitCFIRememberState();
2796 /// ParseDirectiveCFIRestoreState
2797 /// ::= .cfi_remember_state
2798 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2799 SMLoc DirectiveLoc) {
2800 getStreamer().EmitCFIRestoreState();
2804 /// ParseDirectiveCFISameValue
2805 /// ::= .cfi_same_value register
2806 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2807 SMLoc DirectiveLoc) {
2808 int64_t Register = 0;
2810 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2813 getStreamer().EmitCFISameValue(Register);
2818 /// ParseDirectiveMacrosOnOff
2821 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2822 SMLoc DirectiveLoc) {
2823 if (getLexer().isNot(AsmToken::EndOfStatement))
2824 return Error(getLexer().getLoc(),
2825 "unexpected token in '" + Directive + "' directive");
2827 getParser().MacrosEnabled = Directive == ".macros_on";
2832 /// ParseDirectiveMacro
2833 /// ::= .macro name [parameters]
2834 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2835 SMLoc DirectiveLoc) {
2837 if (getParser().ParseIdentifier(Name))
2838 return TokError("expected identifier in directive");
2840 std::vector<StringRef> Parameters;
2841 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2843 StringRef Parameter;
2844 if (getParser().ParseIdentifier(Parameter))
2845 return TokError("expected identifier in directive");
2846 Parameters.push_back(Parameter);
2848 if (getLexer().isNot(AsmToken::Comma))
2854 if (getLexer().isNot(AsmToken::EndOfStatement))
2855 return TokError("unexpected token in '.macro' directive");
2857 // Eat the end of statement.
2860 AsmToken EndToken, StartToken = getTok();
2862 // Lex the macro definition.
2864 // Check whether we have reached the end of the file.
2865 if (getLexer().is(AsmToken::Eof))
2866 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2868 // Otherwise, check whether we have reach the .endmacro.
2869 if (getLexer().is(AsmToken::Identifier) &&
2870 (getTok().getIdentifier() == ".endm" ||
2871 getTok().getIdentifier() == ".endmacro")) {
2872 EndToken = getTok();
2874 if (getLexer().isNot(AsmToken::EndOfStatement))
2875 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2880 // Otherwise, scan til the end of the statement.
2881 getParser().EatToEndOfStatement();
2884 if (getParser().MacroMap.lookup(Name)) {
2885 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2888 const char *BodyStart = StartToken.getLoc().getPointer();
2889 const char *BodyEnd = EndToken.getLoc().getPointer();
2890 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2891 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2895 /// ParseDirectiveEndMacro
2898 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2899 SMLoc DirectiveLoc) {
2900 if (getLexer().isNot(AsmToken::EndOfStatement))
2901 return TokError("unexpected token in '" + Directive + "' directive");
2903 // If we are inside a macro instantiation, terminate the current
2905 if (!getParser().ActiveMacros.empty()) {
2906 getParser().HandleMacroExit();
2910 // Otherwise, this .endmacro is a stray entry in the file; well formed
2911 // .endmacro directives are handled during the macro definition parsing.
2912 return TokError("unexpected '" + Directive + "' in file, "
2913 "no current macro definition");
2916 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2917 getParser().CheckForValidSection();
2919 const MCExpr *Value;
2921 if (getParser().ParseExpression(Value))
2924 if (getLexer().isNot(AsmToken::EndOfStatement))
2925 return TokError("unexpected token in directive");
2927 if (DirName[1] == 's')
2928 getStreamer().EmitSLEB128Value(Value);
2930 getStreamer().EmitULEB128Value(Value);
2936 /// \brief Create an MCAsmParser instance.
2937 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
2938 MCContext &C, MCStreamer &Out,
2939 const MCAsmInfo &MAI) {
2940 return new AsmParser(SM, C, Out, MAI);