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/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/raw_ostream.h"
43 FatalAssemblerWarnings("fatal-assembler-warnings",
44 cl::desc("Consider warnings as error"));
48 /// \brief Helper class for tracking macro definitions.
52 std::vector<StringRef> Parameters;
55 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
56 Name(N), Body(B), Parameters(P) {}
59 /// \brief Helper class for storing information about an active macro
61 struct MacroInstantiation {
62 /// The macro being instantiated.
63 const Macro *TheMacro;
65 /// The macro instantiation with substitutions.
66 MemoryBuffer *Instantiation;
68 /// The location of the instantiation.
69 SMLoc InstantiationLoc;
71 /// The location where parsing should resume upon instantiation completion.
75 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
79 /// \brief The concrete assembly parser instance.
80 class AsmParser : public MCAsmParser {
81 friend class GenericAsmParser;
83 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
84 void operator=(const AsmParser &); // DO NOT IMPLEMENT
91 SourceMgr::DiagHandlerTy SavedDiagHandler;
92 void *SavedDiagContext;
93 MCAsmParserExtension *GenericParser;
94 MCAsmParserExtension *PlatformParser;
96 /// This is the current buffer index we're lexing from as managed by the
100 AsmCond TheCondState;
101 std::vector<AsmCond> TheCondStack;
103 /// DirectiveMap - This is a table handlers for directives. Each handler is
104 /// invoked after the directive identifier is read and is responsible for
105 /// parsing and validating the rest of the directive. The handler is passed
106 /// in the directive name and the location of the directive keyword.
107 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
109 /// MacroMap - Map of currently defined macros.
110 StringMap<Macro*> MacroMap;
112 /// ActiveMacros - Stack of active macro instantiations.
113 std::vector<MacroInstantiation*> ActiveMacros;
115 /// Boolean tracking whether macro substitution is enabled.
116 unsigned MacrosEnabled : 1;
118 /// Flag tracking whether any errors have been encountered.
119 unsigned HadError : 1;
121 /// The values from the last parsed cpp hash file line comment if any.
122 StringRef CppHashFilename;
123 int64_t CppHashLineNumber;
126 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
127 unsigned AssemblerDialect;
130 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
131 const MCAsmInfo &MAI);
134 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
136 void AddDirectiveHandler(MCAsmParserExtension *Object,
138 DirectiveHandler Handler) {
139 DirectiveMap[Directive] = std::make_pair(Object, Handler);
143 /// @name MCAsmParser Interface
146 virtual SourceMgr &getSourceManager() { return SrcMgr; }
147 virtual MCAsmLexer &getLexer() { return Lexer; }
148 virtual MCContext &getContext() { return Ctx; }
149 virtual MCStreamer &getStreamer() { return Out; }
150 virtual unsigned getAssemblerDialect() {
151 if (AssemblerDialect == ~0U)
152 return MAI.getAssemblerDialect();
154 return AssemblerDialect;
156 virtual void setAssemblerDialect(unsigned i) {
157 AssemblerDialect = i;
160 virtual bool Warning(SMLoc L, const Twine &Msg,
161 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
162 virtual bool Error(SMLoc L, const Twine &Msg,
163 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
165 const AsmToken &Lex();
167 bool ParseExpression(const MCExpr *&Res);
168 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
169 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
170 virtual bool ParseAbsoluteExpression(int64_t &Res);
175 void CheckForValidSection();
177 bool ParseStatement();
178 void EatToEndOfLine();
179 bool ParseCppHashLineFilenameComment(const SMLoc &L);
181 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
182 bool expandMacro(SmallString<256> &Buf, StringRef Body,
183 const std::vector<StringRef> &Parameters,
184 const std::vector<std::vector<AsmToken> > &A,
186 void HandleMacroExit();
188 void PrintMacroInstantiations();
189 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
190 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
191 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
193 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
195 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
196 bool EnterIncludeFile(const std::string &Filename);
197 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
198 /// This returns true on failure.
199 bool ProcessIncbinFile(const std::string &Filename);
201 /// \brief Reset the current lexer position to that given by \arg Loc. The
202 /// current token is not set; clients should ensure Lex() is called
204 void JumpToLoc(SMLoc Loc);
206 void EatToEndOfStatement();
208 /// \brief Parse up to the end of statement and a return the contents from the
209 /// current token until the end of the statement; the current token on exit
210 /// will be either the EndOfStatement or EOF.
211 StringRef ParseStringToEndOfStatement();
213 bool ParseAssignment(StringRef Name, bool allow_redef);
215 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
216 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
217 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
218 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
220 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
221 /// and set \arg Res to the identifier contents.
222 bool ParseIdentifier(StringRef &Res);
224 // Directive Parsing.
226 // ".ascii", ".asciiz", ".string"
227 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
228 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
229 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
230 bool ParseDirectiveFill(); // ".fill"
231 bool ParseDirectiveSpace(); // ".space"
232 bool ParseDirectiveZero(); // ".zero"
233 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
234 bool ParseDirectiveOrg(); // ".org"
235 // ".align{,32}", ".p2align{,w,l}"
236 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
238 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
239 /// accepts a single symbol (which should be a label or an external).
240 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
242 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
244 bool ParseDirectiveAbort(); // ".abort"
245 bool ParseDirectiveInclude(); // ".include"
246 bool ParseDirectiveIncbin(); // ".incbin"
248 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
249 // ".ifdef" or ".ifndef", depending on expect_defined
250 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
251 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
252 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
253 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
255 /// ParseEscapedString - Parse the current token as a string which may include
256 /// escaped characters and return the string contents.
257 bool ParseEscapedString(std::string &Data);
259 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
260 MCSymbolRefExpr::VariantKind Variant);
263 /// \brief Generic implementations of directive handling, etc. which is shared
264 /// (or the default, at least) for all assembler parser.
265 class GenericAsmParser : public MCAsmParserExtension {
266 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
267 void AddDirectiveHandler(StringRef Directive) {
268 getParser().AddDirectiveHandler(this, Directive,
269 HandleDirective<GenericAsmParser, Handler>);
272 GenericAsmParser() {}
274 AsmParser &getParser() {
275 return (AsmParser&) this->MCAsmParserExtension::getParser();
278 virtual void Initialize(MCAsmParser &Parser) {
279 // Call the base implementation.
280 this->MCAsmParserExtension::Initialize(Parser);
282 // Debugging directives.
283 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
285 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
289 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
291 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
293 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
295 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
297 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
298 ".cfi_def_cfa_offset");
299 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
300 ".cfi_adjust_cfa_offset");
301 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
302 ".cfi_def_cfa_register");
303 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
305 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
308 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
310 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
312 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
314 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
316 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
318 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
320 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
322 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
325 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
327 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
329 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
330 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
331 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
333 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
334 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
337 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
339 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
340 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
341 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
342 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
343 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
344 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
345 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
346 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
347 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
348 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
349 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
350 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
351 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
352 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
353 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
354 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
355 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
356 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
357 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
358 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
360 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
361 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
362 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
364 bool ParseDirectiveLEB128(StringRef, SMLoc);
371 extern MCAsmParserExtension *createDarwinAsmParser();
372 extern MCAsmParserExtension *createELFAsmParser();
373 extern MCAsmParserExtension *createCOFFAsmParser();
377 enum { DEFAULT_ADDRSPACE = 0 };
379 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
380 MCStreamer &_Out, const MCAsmInfo &_MAI)
381 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
382 GenericParser(new GenericAsmParser), PlatformParser(0),
383 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
384 AssemblerDialect(~0U) {
385 // Save the old handler.
386 SavedDiagHandler = SrcMgr.getDiagHandler();
387 SavedDiagContext = SrcMgr.getDiagContext();
388 // Set our own handler which calls the saved handler.
389 SrcMgr.setDiagHandler(DiagHandler, this);
390 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
392 // Initialize the generic parser.
393 GenericParser->Initialize(*this);
395 // Initialize the platform / file format parser.
397 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
399 if (_MAI.hasMicrosoftFastStdCallMangling()) {
400 PlatformParser = createCOFFAsmParser();
401 PlatformParser->Initialize(*this);
402 } else if (_MAI.hasSubsectionsViaSymbols()) {
403 PlatformParser = createDarwinAsmParser();
404 PlatformParser->Initialize(*this);
406 PlatformParser = createELFAsmParser();
407 PlatformParser->Initialize(*this);
411 AsmParser::~AsmParser() {
412 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
414 // Destroy any macros.
415 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
416 ie = MacroMap.end(); it != ie; ++it)
417 delete it->getValue();
419 delete PlatformParser;
420 delete GenericParser;
423 void AsmParser::PrintMacroInstantiations() {
424 // Print the active macro instantiation stack.
425 for (std::vector<MacroInstantiation*>::const_reverse_iterator
426 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
427 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
428 "while in macro instantiation");
431 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
432 if (FatalAssemblerWarnings)
433 return Error(L, Msg, Ranges);
434 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
435 PrintMacroInstantiations();
439 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
441 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
442 PrintMacroInstantiations();
446 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
447 std::string IncludedFile;
448 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
454 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
459 /// Process the specified .incbin file by seaching for it in the include paths
460 /// then just emiting the byte contents of the file to the streamer. This
461 /// returns true on failure.
462 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
463 std::string IncludedFile;
464 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
468 // Pick up the bytes from the file and emit them.
469 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
474 void AsmParser::JumpToLoc(SMLoc Loc) {
475 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
476 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
479 const AsmToken &AsmParser::Lex() {
480 const AsmToken *tok = &Lexer.Lex();
482 if (tok->is(AsmToken::Eof)) {
483 // If this is the end of an included file, pop the parent file off the
485 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
486 if (ParentIncludeLoc != SMLoc()) {
487 JumpToLoc(ParentIncludeLoc);
492 if (tok->is(AsmToken::Error))
493 Error(Lexer.getErrLoc(), Lexer.getErr());
498 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
499 // Create the initial section, if requested.
500 if (!NoInitialTextSection)
507 AsmCond StartingCondState = TheCondState;
509 // If we are generating dwarf for assembly source files save the initial text
510 // section and generate a .file directive.
511 if (getContext().getGenDwarfForAssembly()) {
512 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
513 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
514 getStreamer().EmitLabel(SectionStartSym);
515 getContext().setGenDwarfSectionStartSym(SectionStartSym);
516 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
517 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
520 // While we have input, parse each statement.
521 while (Lexer.isNot(AsmToken::Eof)) {
522 if (!ParseStatement()) continue;
524 // We had an error, validate that one was emitted and recover by skipping to
526 assert(HadError && "Parse statement returned an error, but none emitted!");
527 EatToEndOfStatement();
530 if (TheCondState.TheCond != StartingCondState.TheCond ||
531 TheCondState.Ignore != StartingCondState.Ignore)
532 return TokError("unmatched .ifs or .elses");
534 // Check to see there are no empty DwarfFile slots.
535 const std::vector<MCDwarfFile *> &MCDwarfFiles =
536 getContext().getMCDwarfFiles();
537 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
538 if (!MCDwarfFiles[i])
539 TokError("unassigned file number: " + Twine(i) + " for .file directives");
542 // Check to see that all assembler local symbols were actually defined.
543 // Targets that don't do subsections via symbols may not want this, though,
544 // so conservatively exclude them. Only do this if we're finalizing, though,
545 // as otherwise we won't necessarilly have seen everything yet.
546 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
547 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
548 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
551 MCSymbol *Sym = i->getValue();
552 // Variable symbols may not be marked as defined, so check those
553 // explicitly. If we know it's a variable, we have a definition for
554 // the purposes of this check.
555 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
556 // FIXME: We would really like to refer back to where the symbol was
557 // first referenced for a source location. We need to add something
558 // to track that. Currently, we just point to the end of the file.
559 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
560 "assembler local symbol '" + Sym->getName() +
566 // Finalize the output stream if there are no errors and if the client wants
568 if (!HadError && !NoFinalize)
574 void AsmParser::CheckForValidSection() {
575 if (!getStreamer().getCurrentSection()) {
576 TokError("expected section directive before assembly directive");
577 Out.SwitchSection(Ctx.getMachOSection(
579 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
580 0, SectionKind::getText()));
584 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
585 void AsmParser::EatToEndOfStatement() {
586 while (Lexer.isNot(AsmToken::EndOfStatement) &&
587 Lexer.isNot(AsmToken::Eof))
591 if (Lexer.is(AsmToken::EndOfStatement))
595 StringRef AsmParser::ParseStringToEndOfStatement() {
596 const char *Start = getTok().getLoc().getPointer();
598 while (Lexer.isNot(AsmToken::EndOfStatement) &&
599 Lexer.isNot(AsmToken::Eof))
602 const char *End = getTok().getLoc().getPointer();
603 return StringRef(Start, End - Start);
606 /// ParseParenExpr - Parse a paren expression and return it.
607 /// NOTE: This assumes the leading '(' has already been consumed.
609 /// parenexpr ::= expr)
611 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
612 if (ParseExpression(Res)) return true;
613 if (Lexer.isNot(AsmToken::RParen))
614 return TokError("expected ')' in parentheses expression");
615 EndLoc = Lexer.getLoc();
620 /// ParseBracketExpr - Parse a bracket expression and return it.
621 /// NOTE: This assumes the leading '[' has already been consumed.
623 /// bracketexpr ::= expr]
625 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
626 if (ParseExpression(Res)) return true;
627 if (Lexer.isNot(AsmToken::RBrac))
628 return TokError("expected ']' in brackets expression");
629 EndLoc = Lexer.getLoc();
634 /// ParsePrimaryExpr - Parse a primary expression and return it.
635 /// primaryexpr ::= (parenexpr
636 /// primaryexpr ::= symbol
637 /// primaryexpr ::= number
638 /// primaryexpr ::= '.'
639 /// primaryexpr ::= ~,+,- primaryexpr
640 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
641 switch (Lexer.getKind()) {
643 return TokError("unknown token in expression");
644 // If we have an error assume that we've already handled it.
645 case AsmToken::Error:
647 case AsmToken::Exclaim:
648 Lex(); // Eat the operator.
649 if (ParsePrimaryExpr(Res, EndLoc))
651 Res = MCUnaryExpr::CreateLNot(Res, getContext());
653 case AsmToken::Dollar:
654 case AsmToken::String:
655 case AsmToken::Identifier: {
656 EndLoc = Lexer.getLoc();
658 StringRef Identifier;
659 if (ParseIdentifier(Identifier))
662 // This is a symbol reference.
663 std::pair<StringRef, StringRef> Split = Identifier.split('@');
664 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
666 // Lookup the symbol variant if used.
667 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
668 if (Split.first.size() != Identifier.size()) {
669 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
670 if (Variant == MCSymbolRefExpr::VK_Invalid) {
671 Variant = MCSymbolRefExpr::VK_None;
672 return TokError("invalid variant '" + Split.second + "'");
676 // If this is an absolute variable reference, substitute it now to preserve
677 // semantics in the face of reassignment.
678 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
680 return Error(EndLoc, "unexpected modifier on variable reference");
682 Res = Sym->getVariableValue();
686 // Otherwise create a symbol ref.
687 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
690 case AsmToken::Integer: {
691 SMLoc Loc = getTok().getLoc();
692 int64_t IntVal = getTok().getIntVal();
693 Res = MCConstantExpr::Create(IntVal, getContext());
694 EndLoc = Lexer.getLoc();
696 // Look for 'b' or 'f' following an Integer as a directional label
697 if (Lexer.getKind() == AsmToken::Identifier) {
698 StringRef IDVal = getTok().getString();
699 if (IDVal == "f" || IDVal == "b"){
700 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
701 IDVal == "f" ? 1 : 0);
702 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
704 if(IDVal == "b" && Sym->isUndefined())
705 return Error(Loc, "invalid reference to undefined symbol");
706 EndLoc = Lexer.getLoc();
707 Lex(); // Eat identifier.
712 case AsmToken::Real: {
713 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
714 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
715 Res = MCConstantExpr::Create(IntVal, getContext());
719 case AsmToken::Dot: {
720 // This is a '.' reference, which references the current PC. Emit a
721 // temporary label to the streamer and refer to it.
722 MCSymbol *Sym = Ctx.CreateTempSymbol();
724 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
725 EndLoc = Lexer.getLoc();
726 Lex(); // Eat identifier.
729 case AsmToken::LParen:
730 Lex(); // Eat the '('.
731 return ParseParenExpr(Res, EndLoc);
732 case AsmToken::LBrac:
733 if (!PlatformParser->HasBracketExpressions())
734 return TokError("brackets expression not supported on this target");
735 Lex(); // Eat the '['.
736 return ParseBracketExpr(Res, EndLoc);
737 case AsmToken::Minus:
738 Lex(); // Eat the operator.
739 if (ParsePrimaryExpr(Res, EndLoc))
741 Res = MCUnaryExpr::CreateMinus(Res, getContext());
744 Lex(); // Eat the operator.
745 if (ParsePrimaryExpr(Res, EndLoc))
747 Res = MCUnaryExpr::CreatePlus(Res, getContext());
749 case AsmToken::Tilde:
750 Lex(); // Eat the operator.
751 if (ParsePrimaryExpr(Res, EndLoc))
753 Res = MCUnaryExpr::CreateNot(Res, getContext());
758 bool AsmParser::ParseExpression(const MCExpr *&Res) {
760 return ParseExpression(Res, EndLoc);
764 AsmParser::ApplyModifierToExpr(const MCExpr *E,
765 MCSymbolRefExpr::VariantKind Variant) {
766 // Recurse over the given expression, rebuilding it to apply the given variant
767 // if there is exactly one symbol.
768 switch (E->getKind()) {
770 case MCExpr::Constant:
773 case MCExpr::SymbolRef: {
774 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
776 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
777 TokError("invalid variant on expression '" +
778 getTok().getIdentifier() + "' (already modified)");
782 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
785 case MCExpr::Unary: {
786 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
787 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
790 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
793 case MCExpr::Binary: {
794 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
795 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
796 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
801 if (!LHS) LHS = BE->getLHS();
802 if (!RHS) RHS = BE->getRHS();
804 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
808 assert(0 && "Invalid expression kind!");
812 /// ParseExpression - Parse an expression and return it.
814 /// expr ::= expr &&,|| expr -> lowest.
815 /// expr ::= expr |,^,&,! expr
816 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
817 /// expr ::= expr <<,>> expr
818 /// expr ::= expr +,- expr
819 /// expr ::= expr *,/,% expr -> highest.
820 /// expr ::= primaryexpr
822 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
823 // Parse the expression.
825 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
828 // As a special case, we support 'a op b @ modifier' by rewriting the
829 // expression to include the modifier. This is inefficient, but in general we
830 // expect users to use 'a@modifier op b'.
831 if (Lexer.getKind() == AsmToken::At) {
834 if (Lexer.isNot(AsmToken::Identifier))
835 return TokError("unexpected symbol modifier following '@'");
837 MCSymbolRefExpr::VariantKind Variant =
838 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
839 if (Variant == MCSymbolRefExpr::VK_Invalid)
840 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
842 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
844 return TokError("invalid modifier '" + getTok().getIdentifier() +
845 "' (no symbols present)");
852 // Try to constant fold it up front, if possible.
854 if (Res->EvaluateAsAbsolute(Value))
855 Res = MCConstantExpr::Create(Value, getContext());
860 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
862 return ParseParenExpr(Res, EndLoc) ||
863 ParseBinOpRHS(1, Res, EndLoc);
866 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
869 SMLoc StartLoc = Lexer.getLoc();
870 if (ParseExpression(Expr))
873 if (!Expr->EvaluateAsAbsolute(Res))
874 return Error(StartLoc, "expected absolute expression");
879 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
880 MCBinaryExpr::Opcode &Kind) {
883 return 0; // not a binop.
885 // Lowest Precedence: &&, ||
886 case AsmToken::AmpAmp:
887 Kind = MCBinaryExpr::LAnd;
889 case AsmToken::PipePipe:
890 Kind = MCBinaryExpr::LOr;
894 // Low Precedence: |, &, ^
896 // FIXME: gas seems to support '!' as an infix operator?
898 Kind = MCBinaryExpr::Or;
900 case AsmToken::Caret:
901 Kind = MCBinaryExpr::Xor;
904 Kind = MCBinaryExpr::And;
907 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
908 case AsmToken::EqualEqual:
909 Kind = MCBinaryExpr::EQ;
911 case AsmToken::ExclaimEqual:
912 case AsmToken::LessGreater:
913 Kind = MCBinaryExpr::NE;
916 Kind = MCBinaryExpr::LT;
918 case AsmToken::LessEqual:
919 Kind = MCBinaryExpr::LTE;
921 case AsmToken::Greater:
922 Kind = MCBinaryExpr::GT;
924 case AsmToken::GreaterEqual:
925 Kind = MCBinaryExpr::GTE;
928 // Intermediate Precedence: <<, >>
929 case AsmToken::LessLess:
930 Kind = MCBinaryExpr::Shl;
932 case AsmToken::GreaterGreater:
933 Kind = MCBinaryExpr::Shr;
936 // High Intermediate Precedence: +, -
938 Kind = MCBinaryExpr::Add;
940 case AsmToken::Minus:
941 Kind = MCBinaryExpr::Sub;
944 // Highest Precedence: *, /, %
946 Kind = MCBinaryExpr::Mul;
948 case AsmToken::Slash:
949 Kind = MCBinaryExpr::Div;
951 case AsmToken::Percent:
952 Kind = MCBinaryExpr::Mod;
958 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
959 /// Res contains the LHS of the expression on input.
960 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
963 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
964 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
966 // If the next token is lower precedence than we are allowed to eat, return
967 // successfully with what we ate already.
968 if (TokPrec < Precedence)
973 // Eat the next primary expression.
975 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
977 // If BinOp binds less tightly with RHS than the operator after RHS, let
978 // the pending operator take RHS as its LHS.
979 MCBinaryExpr::Opcode Dummy;
980 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
981 if (TokPrec < NextTokPrec) {
982 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
985 // Merge LHS and RHS according to operator.
986 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
994 /// ::= EndOfStatement
995 /// ::= Label* Directive ...Operands... EndOfStatement
996 /// ::= Label* Identifier OperandList* EndOfStatement
997 bool AsmParser::ParseStatement() {
998 if (Lexer.is(AsmToken::EndOfStatement)) {
1004 // Statements always start with an identifier or are a full line comment.
1005 AsmToken ID = getTok();
1006 SMLoc IDLoc = ID.getLoc();
1008 int64_t LocalLabelVal = -1;
1009 // A full line comment is a '#' as the first token.
1010 if (Lexer.is(AsmToken::Hash))
1011 return ParseCppHashLineFilenameComment(IDLoc);
1013 // Allow an integer followed by a ':' as a directional local label.
1014 if (Lexer.is(AsmToken::Integer)) {
1015 LocalLabelVal = getTok().getIntVal();
1016 if (LocalLabelVal < 0) {
1017 if (!TheCondState.Ignore)
1018 return TokError("unexpected token at start of statement");
1022 IDVal = getTok().getString();
1023 Lex(); // Consume the integer token to be used as an identifier token.
1024 if (Lexer.getKind() != AsmToken::Colon) {
1025 if (!TheCondState.Ignore)
1026 return TokError("unexpected token at start of statement");
1030 } else if (Lexer.is(AsmToken::Dot)) {
1031 // Treat '.' as a valid identifier in this context.
1035 } else if (ParseIdentifier(IDVal)) {
1036 if (!TheCondState.Ignore)
1037 return TokError("unexpected token at start of statement");
1042 // Handle conditional assembly here before checking for skipping. We
1043 // have to do this so that .endif isn't skipped in a ".if 0" block for
1046 return ParseDirectiveIf(IDLoc);
1047 if (IDVal == ".ifdef")
1048 return ParseDirectiveIfdef(IDLoc, true);
1049 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1050 return ParseDirectiveIfdef(IDLoc, false);
1051 if (IDVal == ".elseif")
1052 return ParseDirectiveElseIf(IDLoc);
1053 if (IDVal == ".else")
1054 return ParseDirectiveElse(IDLoc);
1055 if (IDVal == ".endif")
1056 return ParseDirectiveEndIf(IDLoc);
1058 // If we are in a ".if 0" block, ignore this statement.
1059 if (TheCondState.Ignore) {
1060 EatToEndOfStatement();
1064 // FIXME: Recurse on local labels?
1066 // See what kind of statement we have.
1067 switch (Lexer.getKind()) {
1068 case AsmToken::Colon: {
1069 CheckForValidSection();
1071 // identifier ':' -> Label.
1074 // Diagnose attempt to use '.' as a label.
1076 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1078 // Diagnose attempt to use a variable as a label.
1080 // FIXME: Diagnostics. Note the location of the definition as a label.
1081 // FIXME: This doesn't diagnose assignment to a symbol which has been
1082 // implicitly marked as external.
1084 if (LocalLabelVal == -1)
1085 Sym = getContext().GetOrCreateSymbol(IDVal);
1087 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1088 if (!Sym->isUndefined() || Sym->isVariable())
1089 return Error(IDLoc, "invalid symbol redefinition");
1094 // If we are generating dwarf for assembly source files then gather the
1095 // info to make a dwarf label entry for this label if needed.
1096 if (getContext().getGenDwarfForAssembly())
1097 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1100 // Consume any end of statement token, if present, to avoid spurious
1101 // AddBlankLine calls().
1102 if (Lexer.is(AsmToken::EndOfStatement)) {
1104 if (Lexer.is(AsmToken::Eof))
1108 return ParseStatement();
1111 case AsmToken::Equal:
1112 // identifier '=' ... -> assignment statement
1115 return ParseAssignment(IDVal, true);
1117 default: // Normal instruction or directive.
1121 // If macros are enabled, check to see if this is a macro instantiation.
1123 if (const Macro *M = MacroMap.lookup(IDVal))
1124 return HandleMacroEntry(IDVal, IDLoc, M);
1126 // Otherwise, we have a normal instruction or directive.
1127 if (IDVal[0] == '.' && IDVal != ".") {
1128 // Assembler features
1129 if (IDVal == ".set" || IDVal == ".equ")
1130 return ParseDirectiveSet(IDVal, true);
1131 if (IDVal == ".equiv")
1132 return ParseDirectiveSet(IDVal, false);
1136 if (IDVal == ".ascii")
1137 return ParseDirectiveAscii(IDVal, false);
1138 if (IDVal == ".asciz" || IDVal == ".string")
1139 return ParseDirectiveAscii(IDVal, true);
1141 if (IDVal == ".byte")
1142 return ParseDirectiveValue(1);
1143 if (IDVal == ".short")
1144 return ParseDirectiveValue(2);
1145 if (IDVal == ".value")
1146 return ParseDirectiveValue(2);
1147 if (IDVal == ".2byte")
1148 return ParseDirectiveValue(2);
1149 if (IDVal == ".long")
1150 return ParseDirectiveValue(4);
1151 if (IDVal == ".int")
1152 return ParseDirectiveValue(4);
1153 if (IDVal == ".4byte")
1154 return ParseDirectiveValue(4);
1155 if (IDVal == ".quad")
1156 return ParseDirectiveValue(8);
1157 if (IDVal == ".8byte")
1158 return ParseDirectiveValue(8);
1159 if (IDVal == ".single" || IDVal == ".float")
1160 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1161 if (IDVal == ".double")
1162 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1164 if (IDVal == ".align") {
1165 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1166 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1168 if (IDVal == ".align32") {
1169 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1170 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1172 if (IDVal == ".balign")
1173 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1174 if (IDVal == ".balignw")
1175 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1176 if (IDVal == ".balignl")
1177 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1178 if (IDVal == ".p2align")
1179 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1180 if (IDVal == ".p2alignw")
1181 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1182 if (IDVal == ".p2alignl")
1183 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1185 if (IDVal == ".org")
1186 return ParseDirectiveOrg();
1188 if (IDVal == ".fill")
1189 return ParseDirectiveFill();
1190 if (IDVal == ".space" || IDVal == ".skip")
1191 return ParseDirectiveSpace();
1192 if (IDVal == ".zero")
1193 return ParseDirectiveZero();
1195 // Symbol attribute directives
1197 if (IDVal == ".globl" || IDVal == ".global")
1198 return ParseDirectiveSymbolAttribute(MCSA_Global);
1199 if (IDVal == ".indirect_symbol")
1200 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1201 if (IDVal == ".lazy_reference")
1202 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1203 if (IDVal == ".no_dead_strip")
1204 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1205 if (IDVal == ".symbol_resolver")
1206 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1207 if (IDVal == ".private_extern")
1208 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1209 if (IDVal == ".reference")
1210 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1211 if (IDVal == ".weak_definition")
1212 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1213 if (IDVal == ".weak_reference")
1214 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1215 if (IDVal == ".weak_def_can_be_hidden")
1216 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1218 if (IDVal == ".comm" || IDVal == ".common")
1219 return ParseDirectiveComm(/*IsLocal=*/false);
1220 if (IDVal == ".lcomm")
1221 return ParseDirectiveComm(/*IsLocal=*/true);
1223 if (IDVal == ".abort")
1224 return ParseDirectiveAbort();
1225 if (IDVal == ".include")
1226 return ParseDirectiveInclude();
1227 if (IDVal == ".incbin")
1228 return ParseDirectiveIncbin();
1230 if (IDVal == ".code16")
1231 return TokError(Twine(IDVal) + " not supported yet");
1233 // Look up the handler in the handler table.
1234 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1235 DirectiveMap.lookup(IDVal);
1237 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1239 // Target hook for parsing target specific directives.
1240 if (!getTargetParser().ParseDirective(ID))
1243 bool retval = Warning(IDLoc, "ignoring directive for now");
1244 EatToEndOfStatement();
1248 CheckForValidSection();
1250 // Canonicalize the opcode to lower case.
1251 SmallString<128> Opcode;
1252 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1253 Opcode.push_back(tolower(IDVal[i]));
1255 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1256 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1259 // Dump the parsed representation, if requested.
1260 if (getShowParsedOperands()) {
1261 SmallString<256> Str;
1262 raw_svector_ostream OS(Str);
1263 OS << "parsed instruction: [";
1264 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1267 ParsedOperands[i]->print(OS);
1271 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1274 // If we are generating dwarf for assembly source files and the current
1275 // section is the initial text section then generate a .loc directive for
1277 if (!HadError && getContext().getGenDwarfForAssembly() &&
1278 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1279 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1280 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1281 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1282 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1286 // If parsing succeeded, match the instruction.
1288 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1291 // Free any parsed operands.
1292 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1293 delete ParsedOperands[i];
1295 // Don't skip the rest of the line, the instruction parser is responsible for
1300 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1301 /// since they may not be able to be tokenized to get to the end of line token.
1302 void AsmParser::EatToEndOfLine() {
1303 if (!Lexer.is(AsmToken::EndOfStatement))
1304 Lexer.LexUntilEndOfLine();
1309 /// ParseCppHashLineFilenameComment as this:
1310 /// ::= # number "filename"
1311 /// or just as a full line comment if it doesn't have a number and a string.
1312 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1313 Lex(); // Eat the hash token.
1315 if (getLexer().isNot(AsmToken::Integer)) {
1316 // Consume the line since in cases it is not a well-formed line directive,
1317 // as if were simply a full line comment.
1322 int64_t LineNumber = getTok().getIntVal();
1325 if (getLexer().isNot(AsmToken::String)) {
1330 StringRef Filename = getTok().getString();
1331 // Get rid of the enclosing quotes.
1332 Filename = Filename.substr(1, Filename.size()-2);
1334 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1336 CppHashFilename = Filename;
1337 CppHashLineNumber = LineNumber;
1339 // Ignore any trailing characters, they're just comment.
1344 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1345 /// for the Filename and LineNo if any in the diagnostic.
1346 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1347 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1348 raw_ostream &OS = errs();
1350 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1351 const SMLoc &DiagLoc = Diag.getLoc();
1352 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1353 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1355 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1356 // before printing the message.
1357 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1358 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1359 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1360 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1363 // If we have not parsed a cpp hash line filename comment or the source
1364 // manager changed or buffer changed (like in a nested include) then just
1365 // print the normal diagnostic using its Filename and LineNo.
1366 if (!Parser->CppHashLineNumber ||
1367 &DiagSrcMgr != &Parser->SrcMgr ||
1368 DiagBuf != CppHashBuf) {
1369 if (Parser->SavedDiagHandler)
1370 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1376 // Use the CppHashFilename and calculate a line number based on the
1377 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1379 const std::string Filename = Parser->CppHashFilename;
1381 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1382 int CppHashLocLineNo =
1383 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1384 int LineNo = Parser->CppHashLineNumber - 1 +
1385 (DiagLocLineNo - CppHashLocLineNo);
1387 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1388 Filename, LineNo, Diag.getColumnNo(),
1389 Diag.getKind(), Diag.getMessage(),
1390 Diag.getLineContents(), Diag.getRanges());
1392 if (Parser->SavedDiagHandler)
1393 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1395 NewDiag.print(0, OS);
1398 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1399 const std::vector<StringRef> &Parameters,
1400 const std::vector<std::vector<AsmToken> > &A,
1402 raw_svector_ostream OS(Buf);
1403 unsigned NParameters = Parameters.size();
1404 if (NParameters != 0 && NParameters != A.size())
1405 return Error(L, "Wrong number of arguments");
1407 while (!Body.empty()) {
1408 // Scan for the next substitution.
1409 std::size_t End = Body.size(), Pos = 0;
1410 for (; Pos != End; ++Pos) {
1411 // Check for a substitution or escape.
1413 // This macro has no parameters, look for $0, $1, etc.
1414 if (Body[Pos] != '$' || Pos + 1 == End)
1417 char Next = Body[Pos + 1];
1418 if (Next == '$' || Next == 'n' || isdigit(Next))
1421 // This macro has parameters, look for \foo, \bar, etc.
1422 if (Body[Pos] == '\\' && Pos + 1 != End)
1428 OS << Body.slice(0, Pos);
1430 // Check if we reached the end.
1435 switch (Body[Pos+1]) {
1441 // $n => number of arguments
1446 // $[0-9] => argument
1448 // Missing arguments are ignored.
1449 unsigned Index = Body[Pos+1] - '0';
1450 if (Index >= A.size())
1453 // Otherwise substitute with the token values, with spaces eliminated.
1454 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1455 ie = A[Index].end(); it != ie; ++it)
1456 OS << it->getString();
1462 unsigned I = Pos + 1;
1463 while (isalnum(Body[I]) && I + 1 != End)
1466 const char *Begin = Body.data() + Pos +1;
1467 StringRef Argument(Begin, I - (Pos +1));
1469 for (; Index < NParameters; ++Index)
1470 if (Parameters[Index] == Argument)
1473 // FIXME: We should error at the macro definition.
1474 if (Index == NParameters)
1475 return Error(L, "Parameter not found");
1477 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1478 ie = A[Index].end(); it != ie; ++it)
1479 OS << it->getString();
1481 Pos += 1 + Argument.size();
1483 // Update the scan point.
1484 Body = Body.substr(Pos);
1487 // We include the .endmacro in the buffer as our queue to exit the macro
1489 OS << ".endmacro\n";
1493 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1495 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1499 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1501 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1502 // this, although we should protect against infinite loops.
1503 if (ActiveMacros.size() == 20)
1504 return TokError("macros cannot be nested more than 20 levels deep");
1506 // Parse the macro instantiation arguments.
1507 std::vector<std::vector<AsmToken> > MacroArguments;
1508 MacroArguments.push_back(std::vector<AsmToken>());
1509 unsigned ParenLevel = 0;
1511 if (Lexer.is(AsmToken::Eof))
1512 return TokError("unexpected token in macro instantiation");
1513 if (Lexer.is(AsmToken::EndOfStatement))
1516 // If we aren't inside parentheses and this is a comma, start a new token
1518 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1519 MacroArguments.push_back(std::vector<AsmToken>());
1521 // Adjust the current parentheses level.
1522 if (Lexer.is(AsmToken::LParen))
1524 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1527 // Append the token to the current argument list.
1528 MacroArguments.back().push_back(getTok());
1533 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1534 // to hold the macro body with substitutions.
1535 SmallString<256> Buf;
1536 StringRef Body = M->Body;
1538 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1541 MemoryBuffer *Instantiation =
1542 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1544 // Create the macro instantiation object and add to the current macro
1545 // instantiation stack.
1546 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1549 ActiveMacros.push_back(MI);
1551 // Jump to the macro instantiation and prime the lexer.
1552 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1553 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1559 void AsmParser::HandleMacroExit() {
1560 // Jump to the EndOfStatement we should return to, and consume it.
1561 JumpToLoc(ActiveMacros.back()->ExitLoc);
1564 // Pop the instantiation entry.
1565 delete ActiveMacros.back();
1566 ActiveMacros.pop_back();
1569 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1570 switch (Value->getKind()) {
1571 case MCExpr::Binary: {
1572 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1573 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1576 case MCExpr::Target:
1577 case MCExpr::Constant:
1579 case MCExpr::SymbolRef: {
1580 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1582 return IsUsedIn(Sym, S.getVariableValue());
1586 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1589 llvm_unreachable("Unknown expr kind!");
1592 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1593 // FIXME: Use better location, we should use proper tokens.
1594 SMLoc EqualLoc = Lexer.getLoc();
1596 const MCExpr *Value;
1597 if (ParseExpression(Value))
1600 // Note: we don't count b as used in "a = b". This is to allow
1604 if (Lexer.isNot(AsmToken::EndOfStatement))
1605 return TokError("unexpected token in assignment");
1607 // Error on assignment to '.'.
1609 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1610 "(use '.space' or '.org').)"));
1613 // Eat the end of statement marker.
1616 // Validate that the LHS is allowed to be a variable (either it has not been
1617 // used as a symbol, or it is an absolute symbol).
1618 MCSymbol *Sym = getContext().LookupSymbol(Name);
1620 // Diagnose assignment to a label.
1622 // FIXME: Diagnostics. Note the location of the definition as a label.
1623 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1624 if (IsUsedIn(Sym, Value))
1625 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1626 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1627 ; // Allow redefinitions of undefined symbols only used in directives.
1628 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1629 return Error(EqualLoc, "redefinition of '" + Name + "'");
1630 else if (!Sym->isVariable())
1631 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1632 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1633 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1636 // Don't count these checks as uses.
1637 Sym->setUsed(false);
1639 Sym = getContext().GetOrCreateSymbol(Name);
1641 // FIXME: Handle '.'.
1643 // Do the assignment.
1644 Out.EmitAssignment(Sym, Value);
1649 /// ParseIdentifier:
1652 bool AsmParser::ParseIdentifier(StringRef &Res) {
1653 // The assembler has relaxed rules for accepting identifiers, in particular we
1654 // allow things like '.globl $foo', which would normally be separate
1655 // tokens. At this level, we have already lexed so we cannot (currently)
1656 // handle this as a context dependent token, instead we detect adjacent tokens
1657 // and return the combined identifier.
1658 if (Lexer.is(AsmToken::Dollar)) {
1659 SMLoc DollarLoc = getLexer().getLoc();
1661 // Consume the dollar sign, and check for a following identifier.
1663 if (Lexer.isNot(AsmToken::Identifier))
1666 // We have a '$' followed by an identifier, make sure they are adjacent.
1667 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1670 // Construct the joined identifier and consume the token.
1671 Res = StringRef(DollarLoc.getPointer(),
1672 getTok().getIdentifier().size() + 1);
1677 if (Lexer.isNot(AsmToken::Identifier) &&
1678 Lexer.isNot(AsmToken::String))
1681 Res = getTok().getIdentifier();
1683 Lex(); // Consume the identifier token.
1688 /// ParseDirectiveSet:
1689 /// ::= .equ identifier ',' expression
1690 /// ::= .equiv identifier ',' expression
1691 /// ::= .set identifier ',' expression
1692 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1695 if (ParseIdentifier(Name))
1696 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1698 if (getLexer().isNot(AsmToken::Comma))
1699 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1702 return ParseAssignment(Name, allow_redef);
1705 bool AsmParser::ParseEscapedString(std::string &Data) {
1706 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1709 StringRef Str = getTok().getStringContents();
1710 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1711 if (Str[i] != '\\') {
1716 // Recognize escaped characters. Note that this escape semantics currently
1717 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1720 return TokError("unexpected backslash at end of string");
1722 // Recognize octal sequences.
1723 if ((unsigned) (Str[i] - '0') <= 7) {
1724 // Consume up to three octal characters.
1725 unsigned Value = Str[i] - '0';
1727 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1729 Value = Value * 8 + (Str[i] - '0');
1731 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1733 Value = Value * 8 + (Str[i] - '0');
1738 return TokError("invalid octal escape sequence (out of range)");
1740 Data += (unsigned char) Value;
1744 // Otherwise recognize individual escapes.
1747 // Just reject invalid escape sequences for now.
1748 return TokError("invalid escape sequence (unrecognized character)");
1750 case 'b': Data += '\b'; break;
1751 case 'f': Data += '\f'; break;
1752 case 'n': Data += '\n'; break;
1753 case 'r': Data += '\r'; break;
1754 case 't': Data += '\t'; break;
1755 case '"': Data += '"'; break;
1756 case '\\': Data += '\\'; break;
1763 /// ParseDirectiveAscii:
1764 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1765 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1766 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1767 CheckForValidSection();
1770 if (getLexer().isNot(AsmToken::String))
1771 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1774 if (ParseEscapedString(Data))
1777 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1779 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1783 if (getLexer().is(AsmToken::EndOfStatement))
1786 if (getLexer().isNot(AsmToken::Comma))
1787 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1796 /// ParseDirectiveValue
1797 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1798 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1799 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1800 CheckForValidSection();
1803 const MCExpr *Value;
1804 SMLoc ExprLoc = getLexer().getLoc();
1805 if (ParseExpression(Value))
1808 // Special case constant expressions to match code generator.
1809 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1810 assert(Size <= 8 && "Invalid size");
1811 uint64_t IntValue = MCE->getValue();
1812 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1813 return Error(ExprLoc, "literal value out of range for directive");
1814 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1816 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1818 if (getLexer().is(AsmToken::EndOfStatement))
1821 // FIXME: Improve diagnostic.
1822 if (getLexer().isNot(AsmToken::Comma))
1823 return TokError("unexpected token in directive");
1832 /// ParseDirectiveRealValue
1833 /// ::= (.single | .double) [ expression (, expression)* ]
1834 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1835 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1836 CheckForValidSection();
1839 // We don't truly support arithmetic on floating point expressions, so we
1840 // have to manually parse unary prefixes.
1842 if (getLexer().is(AsmToken::Minus)) {
1845 } else if (getLexer().is(AsmToken::Plus))
1848 if (getLexer().isNot(AsmToken::Integer) &&
1849 getLexer().isNot(AsmToken::Real) &&
1850 getLexer().isNot(AsmToken::Identifier))
1851 return TokError("unexpected token in directive");
1853 // Convert to an APFloat.
1854 APFloat Value(Semantics);
1855 StringRef IDVal = getTok().getString();
1856 if (getLexer().is(AsmToken::Identifier)) {
1857 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1858 Value = APFloat::getInf(Semantics);
1859 else if (!IDVal.compare_lower("nan"))
1860 Value = APFloat::getNaN(Semantics, false, ~0);
1862 return TokError("invalid floating point literal");
1863 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1864 APFloat::opInvalidOp)
1865 return TokError("invalid floating point literal");
1869 // Consume the numeric token.
1872 // Emit the value as an integer.
1873 APInt AsInt = Value.bitcastToAPInt();
1874 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1875 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1877 if (getLexer().is(AsmToken::EndOfStatement))
1880 if (getLexer().isNot(AsmToken::Comma))
1881 return TokError("unexpected token in directive");
1890 /// ParseDirectiveSpace
1891 /// ::= .space expression [ , expression ]
1892 bool AsmParser::ParseDirectiveSpace() {
1893 CheckForValidSection();
1896 if (ParseAbsoluteExpression(NumBytes))
1899 int64_t FillExpr = 0;
1900 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1901 if (getLexer().isNot(AsmToken::Comma))
1902 return TokError("unexpected token in '.space' directive");
1905 if (ParseAbsoluteExpression(FillExpr))
1908 if (getLexer().isNot(AsmToken::EndOfStatement))
1909 return TokError("unexpected token in '.space' directive");
1915 return TokError("invalid number of bytes in '.space' directive");
1917 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1918 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1923 /// ParseDirectiveZero
1924 /// ::= .zero expression
1925 bool AsmParser::ParseDirectiveZero() {
1926 CheckForValidSection();
1929 if (ParseAbsoluteExpression(NumBytes))
1933 if (getLexer().is(AsmToken::Comma)) {
1935 if (ParseAbsoluteExpression(Val))
1939 if (getLexer().isNot(AsmToken::EndOfStatement))
1940 return TokError("unexpected token in '.zero' directive");
1944 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1949 /// ParseDirectiveFill
1950 /// ::= .fill expression , expression , expression
1951 bool AsmParser::ParseDirectiveFill() {
1952 CheckForValidSection();
1955 if (ParseAbsoluteExpression(NumValues))
1958 if (getLexer().isNot(AsmToken::Comma))
1959 return TokError("unexpected token in '.fill' directive");
1963 if (ParseAbsoluteExpression(FillSize))
1966 if (getLexer().isNot(AsmToken::Comma))
1967 return TokError("unexpected token in '.fill' directive");
1971 if (ParseAbsoluteExpression(FillExpr))
1974 if (getLexer().isNot(AsmToken::EndOfStatement))
1975 return TokError("unexpected token in '.fill' directive");
1979 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1980 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1982 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1983 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1988 /// ParseDirectiveOrg
1989 /// ::= .org expression [ , expression ]
1990 bool AsmParser::ParseDirectiveOrg() {
1991 CheckForValidSection();
1993 const MCExpr *Offset;
1994 SMLoc Loc = getTok().getLoc();
1995 if (ParseExpression(Offset))
1998 // Parse optional fill expression.
1999 int64_t FillExpr = 0;
2000 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2001 if (getLexer().isNot(AsmToken::Comma))
2002 return TokError("unexpected token in '.org' directive");
2005 if (ParseAbsoluteExpression(FillExpr))
2008 if (getLexer().isNot(AsmToken::EndOfStatement))
2009 return TokError("unexpected token in '.org' directive");
2014 // Only limited forms of relocatable expressions are accepted here, it
2015 // has to be relative to the current section. The streamer will return
2016 // 'true' if the expression wasn't evaluatable.
2017 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2018 return Error(Loc, "expected assembly-time absolute expression");
2023 /// ParseDirectiveAlign
2024 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2025 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2026 CheckForValidSection();
2028 SMLoc AlignmentLoc = getLexer().getLoc();
2030 if (ParseAbsoluteExpression(Alignment))
2034 bool HasFillExpr = false;
2035 int64_t FillExpr = 0;
2036 int64_t MaxBytesToFill = 0;
2037 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2038 if (getLexer().isNot(AsmToken::Comma))
2039 return TokError("unexpected token in directive");
2042 // The fill expression can be omitted while specifying a maximum number of
2043 // alignment bytes, e.g:
2045 if (getLexer().isNot(AsmToken::Comma)) {
2047 if (ParseAbsoluteExpression(FillExpr))
2051 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2052 if (getLexer().isNot(AsmToken::Comma))
2053 return TokError("unexpected token in directive");
2056 MaxBytesLoc = getLexer().getLoc();
2057 if (ParseAbsoluteExpression(MaxBytesToFill))
2060 if (getLexer().isNot(AsmToken::EndOfStatement))
2061 return TokError("unexpected token in directive");
2070 // Compute alignment in bytes.
2072 // FIXME: Diagnose overflow.
2073 if (Alignment >= 32) {
2074 Error(AlignmentLoc, "invalid alignment value");
2078 Alignment = 1ULL << Alignment;
2081 // Diagnose non-sensical max bytes to align.
2082 if (MaxBytesLoc.isValid()) {
2083 if (MaxBytesToFill < 1) {
2084 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2085 "many bytes, ignoring maximum bytes expression");
2089 if (MaxBytesToFill >= Alignment) {
2090 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2096 // Check whether we should use optimal code alignment for this .align
2098 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2099 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2100 ValueSize == 1 && UseCodeAlign) {
2101 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2103 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2104 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2111 /// ParseDirectiveSymbolAttribute
2112 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2113 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2114 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2117 SMLoc Loc = getTok().getLoc();
2119 if (ParseIdentifier(Name))
2120 return Error(Loc, "expected identifier in directive");
2122 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2124 // Assembler local symbols don't make any sense here. Complain loudly.
2125 if (Sym->isTemporary())
2126 return Error(Loc, "non-local symbol required in directive");
2128 getStreamer().EmitSymbolAttribute(Sym, Attr);
2130 if (getLexer().is(AsmToken::EndOfStatement))
2133 if (getLexer().isNot(AsmToken::Comma))
2134 return TokError("unexpected token in directive");
2143 /// ParseDirectiveComm
2144 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2145 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2146 CheckForValidSection();
2148 SMLoc IDLoc = getLexer().getLoc();
2150 if (ParseIdentifier(Name))
2151 return TokError("expected identifier in directive");
2153 // Handle the identifier as the key symbol.
2154 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2156 if (getLexer().isNot(AsmToken::Comma))
2157 return TokError("unexpected token in directive");
2161 SMLoc SizeLoc = getLexer().getLoc();
2162 if (ParseAbsoluteExpression(Size))
2165 int64_t Pow2Alignment = 0;
2166 SMLoc Pow2AlignmentLoc;
2167 if (getLexer().is(AsmToken::Comma)) {
2169 Pow2AlignmentLoc = getLexer().getLoc();
2170 if (ParseAbsoluteExpression(Pow2Alignment))
2173 // If this target takes alignments in bytes (not log) validate and convert.
2174 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2175 if (!isPowerOf2_64(Pow2Alignment))
2176 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2177 Pow2Alignment = Log2_64(Pow2Alignment);
2181 if (getLexer().isNot(AsmToken::EndOfStatement))
2182 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2186 // NOTE: a size of zero for a .comm should create a undefined symbol
2187 // but a size of .lcomm creates a bss symbol of size zero.
2189 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2190 "be less than zero");
2192 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2193 // may internally end up wanting an alignment in bytes.
2194 // FIXME: Diagnose overflow.
2195 if (Pow2Alignment < 0)
2196 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2197 "alignment, can't be less than zero");
2199 if (!Sym->isUndefined())
2200 return Error(IDLoc, "invalid symbol redefinition");
2202 // '.lcomm' is equivalent to '.zerofill'.
2203 // Create the Symbol as a common or local common with Size and Pow2Alignment
2205 getStreamer().EmitZerofill(Ctx.getMachOSection(
2206 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2207 0, SectionKind::getBSS()),
2208 Sym, Size, 1 << Pow2Alignment);
2212 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2216 /// ParseDirectiveAbort
2217 /// ::= .abort [... message ...]
2218 bool AsmParser::ParseDirectiveAbort() {
2219 // FIXME: Use loc from directive.
2220 SMLoc Loc = getLexer().getLoc();
2222 StringRef Str = ParseStringToEndOfStatement();
2223 if (getLexer().isNot(AsmToken::EndOfStatement))
2224 return TokError("unexpected token in '.abort' directive");
2229 Error(Loc, ".abort detected. Assembly stopping.");
2231 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2232 // FIXME: Actually abort assembly here.
2237 /// ParseDirectiveInclude
2238 /// ::= .include "filename"
2239 bool AsmParser::ParseDirectiveInclude() {
2240 if (getLexer().isNot(AsmToken::String))
2241 return TokError("expected string in '.include' directive");
2243 std::string Filename = getTok().getString();
2244 SMLoc IncludeLoc = getLexer().getLoc();
2247 if (getLexer().isNot(AsmToken::EndOfStatement))
2248 return TokError("unexpected token in '.include' directive");
2250 // Strip the quotes.
2251 Filename = Filename.substr(1, Filename.size()-2);
2253 // Attempt to switch the lexer to the included file before consuming the end
2254 // of statement to avoid losing it when we switch.
2255 if (EnterIncludeFile(Filename)) {
2256 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2263 /// ParseDirectiveIncbin
2264 /// ::= .incbin "filename"
2265 bool AsmParser::ParseDirectiveIncbin() {
2266 if (getLexer().isNot(AsmToken::String))
2267 return TokError("expected string in '.incbin' directive");
2269 std::string Filename = getTok().getString();
2270 SMLoc IncbinLoc = getLexer().getLoc();
2273 if (getLexer().isNot(AsmToken::EndOfStatement))
2274 return TokError("unexpected token in '.incbin' directive");
2276 // Strip the quotes.
2277 Filename = Filename.substr(1, Filename.size()-2);
2279 // Attempt to process the included file.
2280 if (ProcessIncbinFile(Filename)) {
2281 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2288 /// ParseDirectiveIf
2289 /// ::= .if expression
2290 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2291 TheCondStack.push_back(TheCondState);
2292 TheCondState.TheCond = AsmCond::IfCond;
2293 if(TheCondState.Ignore) {
2294 EatToEndOfStatement();
2298 if (ParseAbsoluteExpression(ExprValue))
2301 if (getLexer().isNot(AsmToken::EndOfStatement))
2302 return TokError("unexpected token in '.if' directive");
2306 TheCondState.CondMet = ExprValue;
2307 TheCondState.Ignore = !TheCondState.CondMet;
2313 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2315 TheCondStack.push_back(TheCondState);
2316 TheCondState.TheCond = AsmCond::IfCond;
2318 if (TheCondState.Ignore) {
2319 EatToEndOfStatement();
2321 if (ParseIdentifier(Name))
2322 return TokError("expected identifier after '.ifdef'");
2326 MCSymbol *Sym = getContext().LookupSymbol(Name);
2329 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2331 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2332 TheCondState.Ignore = !TheCondState.CondMet;
2338 /// ParseDirectiveElseIf
2339 /// ::= .elseif expression
2340 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2341 if (TheCondState.TheCond != AsmCond::IfCond &&
2342 TheCondState.TheCond != AsmCond::ElseIfCond)
2343 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2345 TheCondState.TheCond = AsmCond::ElseIfCond;
2347 bool LastIgnoreState = false;
2348 if (!TheCondStack.empty())
2349 LastIgnoreState = TheCondStack.back().Ignore;
2350 if (LastIgnoreState || TheCondState.CondMet) {
2351 TheCondState.Ignore = true;
2352 EatToEndOfStatement();
2356 if (ParseAbsoluteExpression(ExprValue))
2359 if (getLexer().isNot(AsmToken::EndOfStatement))
2360 return TokError("unexpected token in '.elseif' directive");
2363 TheCondState.CondMet = ExprValue;
2364 TheCondState.Ignore = !TheCondState.CondMet;
2370 /// ParseDirectiveElse
2372 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2373 if (getLexer().isNot(AsmToken::EndOfStatement))
2374 return TokError("unexpected token in '.else' directive");
2378 if (TheCondState.TheCond != AsmCond::IfCond &&
2379 TheCondState.TheCond != AsmCond::ElseIfCond)
2380 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2382 TheCondState.TheCond = AsmCond::ElseCond;
2383 bool LastIgnoreState = false;
2384 if (!TheCondStack.empty())
2385 LastIgnoreState = TheCondStack.back().Ignore;
2386 if (LastIgnoreState || TheCondState.CondMet)
2387 TheCondState.Ignore = true;
2389 TheCondState.Ignore = false;
2394 /// ParseDirectiveEndIf
2396 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2397 if (getLexer().isNot(AsmToken::EndOfStatement))
2398 return TokError("unexpected token in '.endif' directive");
2402 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2403 TheCondStack.empty())
2404 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2406 if (!TheCondStack.empty()) {
2407 TheCondState = TheCondStack.back();
2408 TheCondStack.pop_back();
2414 /// ParseDirectiveFile
2415 /// ::= .file [number] filename
2416 /// ::= .file number directory filename
2417 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2418 // FIXME: I'm not sure what this is.
2419 int64_t FileNumber = -1;
2420 SMLoc FileNumberLoc = getLexer().getLoc();
2421 if (getLexer().is(AsmToken::Integer)) {
2422 FileNumber = getTok().getIntVal();
2426 return TokError("file number less than one");
2429 if (getLexer().isNot(AsmToken::String))
2430 return TokError("unexpected token in '.file' directive");
2432 // Usually the directory and filename together, otherwise just the directory.
2433 StringRef Path = getTok().getString();
2434 Path = Path.substr(1, Path.size()-2);
2437 StringRef Directory;
2439 if (getLexer().is(AsmToken::String)) {
2440 if (FileNumber == -1)
2441 return TokError("explicit path specified, but no file number");
2442 Filename = getTok().getString();
2443 Filename = Filename.substr(1, Filename.size()-2);
2450 if (getLexer().isNot(AsmToken::EndOfStatement))
2451 return TokError("unexpected token in '.file' directive");
2453 if (FileNumber == -1)
2454 getStreamer().EmitFileDirective(Filename);
2456 if (getContext().getGenDwarfForAssembly() == true)
2457 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2458 "used to generate dwarf debug info for assembly code");
2460 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2461 Error(FileNumberLoc, "file number already allocated");
2467 /// ParseDirectiveLine
2468 /// ::= .line [number]
2469 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2470 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2471 if (getLexer().isNot(AsmToken::Integer))
2472 return TokError("unexpected token in '.line' directive");
2474 int64_t LineNumber = getTok().getIntVal();
2478 // FIXME: Do something with the .line.
2481 if (getLexer().isNot(AsmToken::EndOfStatement))
2482 return TokError("unexpected token in '.line' directive");
2488 /// ParseDirectiveLoc
2489 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2490 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2491 /// The first number is a file number, must have been previously assigned with
2492 /// a .file directive, the second number is the line number and optionally the
2493 /// third number is a column position (zero if not specified). The remaining
2494 /// optional items are .loc sub-directives.
2495 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2497 if (getLexer().isNot(AsmToken::Integer))
2498 return TokError("unexpected token in '.loc' directive");
2499 int64_t FileNumber = getTok().getIntVal();
2501 return TokError("file number less than one in '.loc' directive");
2502 if (!getContext().isValidDwarfFileNumber(FileNumber))
2503 return TokError("unassigned file number in '.loc' directive");
2506 int64_t LineNumber = 0;
2507 if (getLexer().is(AsmToken::Integer)) {
2508 LineNumber = getTok().getIntVal();
2510 return TokError("line number less than one in '.loc' directive");
2514 int64_t ColumnPos = 0;
2515 if (getLexer().is(AsmToken::Integer)) {
2516 ColumnPos = getTok().getIntVal();
2518 return TokError("column position less than zero in '.loc' directive");
2522 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2524 int64_t Discriminator = 0;
2525 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2527 if (getLexer().is(AsmToken::EndOfStatement))
2531 SMLoc Loc = getTok().getLoc();
2532 if (getParser().ParseIdentifier(Name))
2533 return TokError("unexpected token in '.loc' directive");
2535 if (Name == "basic_block")
2536 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2537 else if (Name == "prologue_end")
2538 Flags |= DWARF2_FLAG_PROLOGUE_END;
2539 else if (Name == "epilogue_begin")
2540 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2541 else if (Name == "is_stmt") {
2542 SMLoc Loc = getTok().getLoc();
2543 const MCExpr *Value;
2544 if (getParser().ParseExpression(Value))
2546 // The expression must be the constant 0 or 1.
2547 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2548 int Value = MCE->getValue();
2550 Flags &= ~DWARF2_FLAG_IS_STMT;
2551 else if (Value == 1)
2552 Flags |= DWARF2_FLAG_IS_STMT;
2554 return Error(Loc, "is_stmt value not 0 or 1");
2557 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2560 else if (Name == "isa") {
2561 SMLoc Loc = getTok().getLoc();
2562 const MCExpr *Value;
2563 if (getParser().ParseExpression(Value))
2565 // The expression must be a constant greater or equal to 0.
2566 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2567 int Value = MCE->getValue();
2569 return Error(Loc, "isa number less than zero");
2573 return Error(Loc, "isa number not a constant value");
2576 else if (Name == "discriminator") {
2577 if (getParser().ParseAbsoluteExpression(Discriminator))
2581 return Error(Loc, "unknown sub-directive in '.loc' directive");
2584 if (getLexer().is(AsmToken::EndOfStatement))
2589 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2590 Isa, Discriminator, StringRef());
2595 /// ParseDirectiveStabs
2596 /// ::= .stabs string, number, number, number
2597 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2598 SMLoc DirectiveLoc) {
2599 return TokError("unsupported directive '" + Directive + "'");
2602 /// ParseDirectiveCFISections
2603 /// ::= .cfi_sections section [, section]
2604 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2605 SMLoc DirectiveLoc) {
2610 if (getParser().ParseIdentifier(Name))
2611 return TokError("Expected an identifier");
2613 if (Name == ".eh_frame")
2615 else if (Name == ".debug_frame")
2618 if (getLexer().is(AsmToken::Comma)) {
2621 if (getParser().ParseIdentifier(Name))
2622 return TokError("Expected an identifier");
2624 if (Name == ".eh_frame")
2626 else if (Name == ".debug_frame")
2630 getStreamer().EmitCFISections(EH, Debug);
2635 /// ParseDirectiveCFIStartProc
2636 /// ::= .cfi_startproc
2637 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2638 SMLoc DirectiveLoc) {
2639 getStreamer().EmitCFIStartProc();
2643 /// ParseDirectiveCFIEndProc
2644 /// ::= .cfi_endproc
2645 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2646 getStreamer().EmitCFIEndProc();
2650 /// ParseRegisterOrRegisterNumber - parse register name or number.
2651 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2652 SMLoc DirectiveLoc) {
2655 if (getLexer().isNot(AsmToken::Integer)) {
2656 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2659 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2661 return getParser().ParseAbsoluteExpression(Register);
2666 /// ParseDirectiveCFIDefCfa
2667 /// ::= .cfi_def_cfa register, offset
2668 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2669 SMLoc DirectiveLoc) {
2670 int64_t Register = 0;
2671 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2674 if (getLexer().isNot(AsmToken::Comma))
2675 return TokError("unexpected token in directive");
2679 if (getParser().ParseAbsoluteExpression(Offset))
2682 getStreamer().EmitCFIDefCfa(Register, Offset);
2686 /// ParseDirectiveCFIDefCfaOffset
2687 /// ::= .cfi_def_cfa_offset offset
2688 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2689 SMLoc DirectiveLoc) {
2691 if (getParser().ParseAbsoluteExpression(Offset))
2694 getStreamer().EmitCFIDefCfaOffset(Offset);
2698 /// ParseDirectiveCFIAdjustCfaOffset
2699 /// ::= .cfi_adjust_cfa_offset adjustment
2700 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2701 SMLoc DirectiveLoc) {
2702 int64_t Adjustment = 0;
2703 if (getParser().ParseAbsoluteExpression(Adjustment))
2706 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2710 /// ParseDirectiveCFIDefCfaRegister
2711 /// ::= .cfi_def_cfa_register register
2712 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2713 SMLoc DirectiveLoc) {
2714 int64_t Register = 0;
2715 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2718 getStreamer().EmitCFIDefCfaRegister(Register);
2722 /// ParseDirectiveCFIOffset
2723 /// ::= .cfi_offset register, offset
2724 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2725 int64_t Register = 0;
2728 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2731 if (getLexer().isNot(AsmToken::Comma))
2732 return TokError("unexpected token in directive");
2735 if (getParser().ParseAbsoluteExpression(Offset))
2738 getStreamer().EmitCFIOffset(Register, Offset);
2742 /// ParseDirectiveCFIRelOffset
2743 /// ::= .cfi_rel_offset register, offset
2744 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2745 SMLoc DirectiveLoc) {
2746 int64_t Register = 0;
2748 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2751 if (getLexer().isNot(AsmToken::Comma))
2752 return TokError("unexpected token in directive");
2756 if (getParser().ParseAbsoluteExpression(Offset))
2759 getStreamer().EmitCFIRelOffset(Register, Offset);
2763 static bool isValidEncoding(int64_t Encoding) {
2764 if (Encoding & ~0xff)
2767 if (Encoding == dwarf::DW_EH_PE_omit)
2770 const unsigned Format = Encoding & 0xf;
2771 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2772 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2773 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2774 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2777 const unsigned Application = Encoding & 0x70;
2778 if (Application != dwarf::DW_EH_PE_absptr &&
2779 Application != dwarf::DW_EH_PE_pcrel)
2785 /// ParseDirectiveCFIPersonalityOrLsda
2786 /// ::= .cfi_personality encoding, [symbol_name]
2787 /// ::= .cfi_lsda encoding, [symbol_name]
2788 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2789 SMLoc DirectiveLoc) {
2790 int64_t Encoding = 0;
2791 if (getParser().ParseAbsoluteExpression(Encoding))
2793 if (Encoding == dwarf::DW_EH_PE_omit)
2796 if (!isValidEncoding(Encoding))
2797 return TokError("unsupported encoding.");
2799 if (getLexer().isNot(AsmToken::Comma))
2800 return TokError("unexpected token in directive");
2804 if (getParser().ParseIdentifier(Name))
2805 return TokError("expected identifier in directive");
2807 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2809 if (IDVal == ".cfi_personality")
2810 getStreamer().EmitCFIPersonality(Sym, Encoding);
2812 assert(IDVal == ".cfi_lsda");
2813 getStreamer().EmitCFILsda(Sym, Encoding);
2818 /// ParseDirectiveCFIRememberState
2819 /// ::= .cfi_remember_state
2820 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2821 SMLoc DirectiveLoc) {
2822 getStreamer().EmitCFIRememberState();
2826 /// ParseDirectiveCFIRestoreState
2827 /// ::= .cfi_remember_state
2828 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2829 SMLoc DirectiveLoc) {
2830 getStreamer().EmitCFIRestoreState();
2834 /// ParseDirectiveCFISameValue
2835 /// ::= .cfi_same_value register
2836 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2837 SMLoc DirectiveLoc) {
2838 int64_t Register = 0;
2840 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2843 getStreamer().EmitCFISameValue(Register);
2848 /// ParseDirectiveCFIRestore
2849 /// ::= .cfi_restore register
2850 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2851 SMLoc DirectiveLoc) {
2852 int64_t Register = 0;
2853 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2856 getStreamer().EmitCFIRestore(Register);
2861 /// ParseDirectiveCFIEscape
2862 /// ::= .cfi_escape expression[,...]
2863 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2864 SMLoc DirectiveLoc) {
2867 if (getParser().ParseAbsoluteExpression(CurrValue))
2870 Values.push_back((uint8_t)CurrValue);
2872 while (getLexer().is(AsmToken::Comma)) {
2875 if (getParser().ParseAbsoluteExpression(CurrValue))
2878 Values.push_back((uint8_t)CurrValue);
2881 getStreamer().EmitCFIEscape(Values);
2885 /// ParseDirectiveCFISignalFrame
2886 /// ::= .cfi_signal_frame
2887 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2888 SMLoc DirectiveLoc) {
2889 if (getLexer().isNot(AsmToken::EndOfStatement))
2890 return Error(getLexer().getLoc(),
2891 "unexpected token in '" + Directive + "' directive");
2893 getStreamer().EmitCFISignalFrame();
2898 /// ParseDirectiveMacrosOnOff
2901 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2902 SMLoc DirectiveLoc) {
2903 if (getLexer().isNot(AsmToken::EndOfStatement))
2904 return Error(getLexer().getLoc(),
2905 "unexpected token in '" + Directive + "' directive");
2907 getParser().MacrosEnabled = Directive == ".macros_on";
2912 /// ParseDirectiveMacro
2913 /// ::= .macro name [parameters]
2914 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2915 SMLoc DirectiveLoc) {
2917 if (getParser().ParseIdentifier(Name))
2918 return TokError("expected identifier in directive");
2920 std::vector<StringRef> Parameters;
2921 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2923 StringRef Parameter;
2924 if (getParser().ParseIdentifier(Parameter))
2925 return TokError("expected identifier in directive");
2926 Parameters.push_back(Parameter);
2928 if (getLexer().isNot(AsmToken::Comma))
2934 if (getLexer().isNot(AsmToken::EndOfStatement))
2935 return TokError("unexpected token in '.macro' directive");
2937 // Eat the end of statement.
2940 AsmToken EndToken, StartToken = getTok();
2942 // Lex the macro definition.
2944 // Check whether we have reached the end of the file.
2945 if (getLexer().is(AsmToken::Eof))
2946 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2948 // Otherwise, check whether we have reach the .endmacro.
2949 if (getLexer().is(AsmToken::Identifier) &&
2950 (getTok().getIdentifier() == ".endm" ||
2951 getTok().getIdentifier() == ".endmacro")) {
2952 EndToken = getTok();
2954 if (getLexer().isNot(AsmToken::EndOfStatement))
2955 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2960 // Otherwise, scan til the end of the statement.
2961 getParser().EatToEndOfStatement();
2964 if (getParser().MacroMap.lookup(Name)) {
2965 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2968 const char *BodyStart = StartToken.getLoc().getPointer();
2969 const char *BodyEnd = EndToken.getLoc().getPointer();
2970 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2971 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2975 /// ParseDirectiveEndMacro
2978 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2979 SMLoc DirectiveLoc) {
2980 if (getLexer().isNot(AsmToken::EndOfStatement))
2981 return TokError("unexpected token in '" + Directive + "' directive");
2983 // If we are inside a macro instantiation, terminate the current
2985 if (!getParser().ActiveMacros.empty()) {
2986 getParser().HandleMacroExit();
2990 // Otherwise, this .endmacro is a stray entry in the file; well formed
2991 // .endmacro directives are handled during the macro definition parsing.
2992 return TokError("unexpected '" + Directive + "' in file, "
2993 "no current macro definition");
2996 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2997 getParser().CheckForValidSection();
2999 const MCExpr *Value;
3001 if (getParser().ParseExpression(Value))
3004 if (getLexer().isNot(AsmToken::EndOfStatement))
3005 return TokError("unexpected token in directive");
3007 if (DirName[1] == 's')
3008 getStreamer().EmitSLEB128Value(Value);
3010 getStreamer().EmitULEB128Value(Value);
3016 /// \brief Create an MCAsmParser instance.
3017 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3018 MCContext &C, MCStreamer &Out,
3019 const MCAsmInfo &MAI) {
3020 return new AsmParser(SM, C, Out, MAI);