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 llvm_unreachable("Invalid expression kind!");
811 /// ParseExpression - Parse an expression and return it.
813 /// expr ::= expr &&,|| expr -> lowest.
814 /// expr ::= expr |,^,&,! expr
815 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
816 /// expr ::= expr <<,>> expr
817 /// expr ::= expr +,- expr
818 /// expr ::= expr *,/,% expr -> highest.
819 /// expr ::= primaryexpr
821 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
822 // Parse the expression.
824 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
827 // As a special case, we support 'a op b @ modifier' by rewriting the
828 // expression to include the modifier. This is inefficient, but in general we
829 // expect users to use 'a@modifier op b'.
830 if (Lexer.getKind() == AsmToken::At) {
833 if (Lexer.isNot(AsmToken::Identifier))
834 return TokError("unexpected symbol modifier following '@'");
836 MCSymbolRefExpr::VariantKind Variant =
837 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
838 if (Variant == MCSymbolRefExpr::VK_Invalid)
839 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
841 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
843 return TokError("invalid modifier '" + getTok().getIdentifier() +
844 "' (no symbols present)");
851 // Try to constant fold it up front, if possible.
853 if (Res->EvaluateAsAbsolute(Value))
854 Res = MCConstantExpr::Create(Value, getContext());
859 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
861 return ParseParenExpr(Res, EndLoc) ||
862 ParseBinOpRHS(1, Res, EndLoc);
865 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
868 SMLoc StartLoc = Lexer.getLoc();
869 if (ParseExpression(Expr))
872 if (!Expr->EvaluateAsAbsolute(Res))
873 return Error(StartLoc, "expected absolute expression");
878 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
879 MCBinaryExpr::Opcode &Kind) {
882 return 0; // not a binop.
884 // Lowest Precedence: &&, ||
885 case AsmToken::AmpAmp:
886 Kind = MCBinaryExpr::LAnd;
888 case AsmToken::PipePipe:
889 Kind = MCBinaryExpr::LOr;
893 // Low Precedence: |, &, ^
895 // FIXME: gas seems to support '!' as an infix operator?
897 Kind = MCBinaryExpr::Or;
899 case AsmToken::Caret:
900 Kind = MCBinaryExpr::Xor;
903 Kind = MCBinaryExpr::And;
906 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
907 case AsmToken::EqualEqual:
908 Kind = MCBinaryExpr::EQ;
910 case AsmToken::ExclaimEqual:
911 case AsmToken::LessGreater:
912 Kind = MCBinaryExpr::NE;
915 Kind = MCBinaryExpr::LT;
917 case AsmToken::LessEqual:
918 Kind = MCBinaryExpr::LTE;
920 case AsmToken::Greater:
921 Kind = MCBinaryExpr::GT;
923 case AsmToken::GreaterEqual:
924 Kind = MCBinaryExpr::GTE;
927 // Intermediate Precedence: <<, >>
928 case AsmToken::LessLess:
929 Kind = MCBinaryExpr::Shl;
931 case AsmToken::GreaterGreater:
932 Kind = MCBinaryExpr::Shr;
935 // High Intermediate Precedence: +, -
937 Kind = MCBinaryExpr::Add;
939 case AsmToken::Minus:
940 Kind = MCBinaryExpr::Sub;
943 // Highest Precedence: *, /, %
945 Kind = MCBinaryExpr::Mul;
947 case AsmToken::Slash:
948 Kind = MCBinaryExpr::Div;
950 case AsmToken::Percent:
951 Kind = MCBinaryExpr::Mod;
957 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
958 /// Res contains the LHS of the expression on input.
959 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
962 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
963 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
965 // If the next token is lower precedence than we are allowed to eat, return
966 // successfully with what we ate already.
967 if (TokPrec < Precedence)
972 // Eat the next primary expression.
974 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
976 // If BinOp binds less tightly with RHS than the operator after RHS, let
977 // the pending operator take RHS as its LHS.
978 MCBinaryExpr::Opcode Dummy;
979 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
980 if (TokPrec < NextTokPrec) {
981 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
984 // Merge LHS and RHS according to operator.
985 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
993 /// ::= EndOfStatement
994 /// ::= Label* Directive ...Operands... EndOfStatement
995 /// ::= Label* Identifier OperandList* EndOfStatement
996 bool AsmParser::ParseStatement() {
997 if (Lexer.is(AsmToken::EndOfStatement)) {
1003 // Statements always start with an identifier or are a full line comment.
1004 AsmToken ID = getTok();
1005 SMLoc IDLoc = ID.getLoc();
1007 int64_t LocalLabelVal = -1;
1008 // A full line comment is a '#' as the first token.
1009 if (Lexer.is(AsmToken::Hash))
1010 return ParseCppHashLineFilenameComment(IDLoc);
1012 // Allow an integer followed by a ':' as a directional local label.
1013 if (Lexer.is(AsmToken::Integer)) {
1014 LocalLabelVal = getTok().getIntVal();
1015 if (LocalLabelVal < 0) {
1016 if (!TheCondState.Ignore)
1017 return TokError("unexpected token at start of statement");
1021 IDVal = getTok().getString();
1022 Lex(); // Consume the integer token to be used as an identifier token.
1023 if (Lexer.getKind() != AsmToken::Colon) {
1024 if (!TheCondState.Ignore)
1025 return TokError("unexpected token at start of statement");
1029 } else if (Lexer.is(AsmToken::Dot)) {
1030 // Treat '.' as a valid identifier in this context.
1034 } else if (ParseIdentifier(IDVal)) {
1035 if (!TheCondState.Ignore)
1036 return TokError("unexpected token at start of statement");
1041 // Handle conditional assembly here before checking for skipping. We
1042 // have to do this so that .endif isn't skipped in a ".if 0" block for
1045 return ParseDirectiveIf(IDLoc);
1046 if (IDVal == ".ifdef")
1047 return ParseDirectiveIfdef(IDLoc, true);
1048 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1049 return ParseDirectiveIfdef(IDLoc, false);
1050 if (IDVal == ".elseif")
1051 return ParseDirectiveElseIf(IDLoc);
1052 if (IDVal == ".else")
1053 return ParseDirectiveElse(IDLoc);
1054 if (IDVal == ".endif")
1055 return ParseDirectiveEndIf(IDLoc);
1057 // If we are in a ".if 0" block, ignore this statement.
1058 if (TheCondState.Ignore) {
1059 EatToEndOfStatement();
1063 // FIXME: Recurse on local labels?
1065 // See what kind of statement we have.
1066 switch (Lexer.getKind()) {
1067 case AsmToken::Colon: {
1068 CheckForValidSection();
1070 // identifier ':' -> Label.
1073 // Diagnose attempt to use '.' as a label.
1075 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1077 // Diagnose attempt to use a variable as a label.
1079 // FIXME: Diagnostics. Note the location of the definition as a label.
1080 // FIXME: This doesn't diagnose assignment to a symbol which has been
1081 // implicitly marked as external.
1083 if (LocalLabelVal == -1)
1084 Sym = getContext().GetOrCreateSymbol(IDVal);
1086 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1087 if (!Sym->isUndefined() || Sym->isVariable())
1088 return Error(IDLoc, "invalid symbol redefinition");
1093 // If we are generating dwarf for assembly source files then gather the
1094 // info to make a dwarf label entry for this label if needed.
1095 if (getContext().getGenDwarfForAssembly())
1096 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1099 // Consume any end of statement token, if present, to avoid spurious
1100 // AddBlankLine calls().
1101 if (Lexer.is(AsmToken::EndOfStatement)) {
1103 if (Lexer.is(AsmToken::Eof))
1107 return ParseStatement();
1110 case AsmToken::Equal:
1111 // identifier '=' ... -> assignment statement
1114 return ParseAssignment(IDVal, true);
1116 default: // Normal instruction or directive.
1120 // If macros are enabled, check to see if this is a macro instantiation.
1122 if (const Macro *M = MacroMap.lookup(IDVal))
1123 return HandleMacroEntry(IDVal, IDLoc, M);
1125 // Otherwise, we have a normal instruction or directive.
1126 if (IDVal[0] == '.' && IDVal != ".") {
1127 // Assembler features
1128 if (IDVal == ".set" || IDVal == ".equ")
1129 return ParseDirectiveSet(IDVal, true);
1130 if (IDVal == ".equiv")
1131 return ParseDirectiveSet(IDVal, false);
1135 if (IDVal == ".ascii")
1136 return ParseDirectiveAscii(IDVal, false);
1137 if (IDVal == ".asciz" || IDVal == ".string")
1138 return ParseDirectiveAscii(IDVal, true);
1140 if (IDVal == ".byte")
1141 return ParseDirectiveValue(1);
1142 if (IDVal == ".short")
1143 return ParseDirectiveValue(2);
1144 if (IDVal == ".value")
1145 return ParseDirectiveValue(2);
1146 if (IDVal == ".2byte")
1147 return ParseDirectiveValue(2);
1148 if (IDVal == ".long")
1149 return ParseDirectiveValue(4);
1150 if (IDVal == ".int")
1151 return ParseDirectiveValue(4);
1152 if (IDVal == ".4byte")
1153 return ParseDirectiveValue(4);
1154 if (IDVal == ".quad")
1155 return ParseDirectiveValue(8);
1156 if (IDVal == ".8byte")
1157 return ParseDirectiveValue(8);
1158 if (IDVal == ".single" || IDVal == ".float")
1159 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1160 if (IDVal == ".double")
1161 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1163 if (IDVal == ".align") {
1164 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1165 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1167 if (IDVal == ".align32") {
1168 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1169 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1171 if (IDVal == ".balign")
1172 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1173 if (IDVal == ".balignw")
1174 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1175 if (IDVal == ".balignl")
1176 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1177 if (IDVal == ".p2align")
1178 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1179 if (IDVal == ".p2alignw")
1180 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1181 if (IDVal == ".p2alignl")
1182 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1184 if (IDVal == ".org")
1185 return ParseDirectiveOrg();
1187 if (IDVal == ".fill")
1188 return ParseDirectiveFill();
1189 if (IDVal == ".space" || IDVal == ".skip")
1190 return ParseDirectiveSpace();
1191 if (IDVal == ".zero")
1192 return ParseDirectiveZero();
1194 // Symbol attribute directives
1196 if (IDVal == ".globl" || IDVal == ".global")
1197 return ParseDirectiveSymbolAttribute(MCSA_Global);
1198 if (IDVal == ".indirect_symbol")
1199 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1200 if (IDVal == ".lazy_reference")
1201 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1202 if (IDVal == ".no_dead_strip")
1203 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1204 if (IDVal == ".symbol_resolver")
1205 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1206 if (IDVal == ".private_extern")
1207 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1208 if (IDVal == ".reference")
1209 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1210 if (IDVal == ".weak_definition")
1211 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1212 if (IDVal == ".weak_reference")
1213 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1214 if (IDVal == ".weak_def_can_be_hidden")
1215 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1217 if (IDVal == ".comm" || IDVal == ".common")
1218 return ParseDirectiveComm(/*IsLocal=*/false);
1219 if (IDVal == ".lcomm")
1220 return ParseDirectiveComm(/*IsLocal=*/true);
1222 if (IDVal == ".abort")
1223 return ParseDirectiveAbort();
1224 if (IDVal == ".include")
1225 return ParseDirectiveInclude();
1226 if (IDVal == ".incbin")
1227 return ParseDirectiveIncbin();
1229 if (IDVal == ".code16")
1230 return TokError(Twine(IDVal) + " not supported yet");
1232 // Look up the handler in the handler table.
1233 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1234 DirectiveMap.lookup(IDVal);
1236 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1238 // Target hook for parsing target specific directives.
1239 if (!getTargetParser().ParseDirective(ID))
1242 bool retval = Warning(IDLoc, "ignoring directive for now");
1243 EatToEndOfStatement();
1247 CheckForValidSection();
1249 // Canonicalize the opcode to lower case.
1250 SmallString<128> Opcode;
1251 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1252 Opcode.push_back(tolower(IDVal[i]));
1254 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1255 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1258 // Dump the parsed representation, if requested.
1259 if (getShowParsedOperands()) {
1260 SmallString<256> Str;
1261 raw_svector_ostream OS(Str);
1262 OS << "parsed instruction: [";
1263 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1266 ParsedOperands[i]->print(OS);
1270 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1273 // If we are generating dwarf for assembly source files and the current
1274 // section is the initial text section then generate a .loc directive for
1276 if (!HadError && getContext().getGenDwarfForAssembly() &&
1277 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1278 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1279 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1280 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1281 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1285 // If parsing succeeded, match the instruction.
1287 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1290 // Free any parsed operands.
1291 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1292 delete ParsedOperands[i];
1294 // Don't skip the rest of the line, the instruction parser is responsible for
1299 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1300 /// since they may not be able to be tokenized to get to the end of line token.
1301 void AsmParser::EatToEndOfLine() {
1302 if (!Lexer.is(AsmToken::EndOfStatement))
1303 Lexer.LexUntilEndOfLine();
1308 /// ParseCppHashLineFilenameComment as this:
1309 /// ::= # number "filename"
1310 /// or just as a full line comment if it doesn't have a number and a string.
1311 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1312 Lex(); // Eat the hash token.
1314 if (getLexer().isNot(AsmToken::Integer)) {
1315 // Consume the line since in cases it is not a well-formed line directive,
1316 // as if were simply a full line comment.
1321 int64_t LineNumber = getTok().getIntVal();
1324 if (getLexer().isNot(AsmToken::String)) {
1329 StringRef Filename = getTok().getString();
1330 // Get rid of the enclosing quotes.
1331 Filename = Filename.substr(1, Filename.size()-2);
1333 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1335 CppHashFilename = Filename;
1336 CppHashLineNumber = LineNumber;
1338 // Ignore any trailing characters, they're just comment.
1343 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1344 /// for the Filename and LineNo if any in the diagnostic.
1345 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1346 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1347 raw_ostream &OS = errs();
1349 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1350 const SMLoc &DiagLoc = Diag.getLoc();
1351 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1352 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1354 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1355 // before printing the message.
1356 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1357 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1358 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1359 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1362 // If we have not parsed a cpp hash line filename comment or the source
1363 // manager changed or buffer changed (like in a nested include) then just
1364 // print the normal diagnostic using its Filename and LineNo.
1365 if (!Parser->CppHashLineNumber ||
1366 &DiagSrcMgr != &Parser->SrcMgr ||
1367 DiagBuf != CppHashBuf) {
1368 if (Parser->SavedDiagHandler)
1369 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1375 // Use the CppHashFilename and calculate a line number based on the
1376 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1378 const std::string Filename = Parser->CppHashFilename;
1380 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1381 int CppHashLocLineNo =
1382 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1383 int LineNo = Parser->CppHashLineNumber - 1 +
1384 (DiagLocLineNo - CppHashLocLineNo);
1386 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1387 Filename, LineNo, Diag.getColumnNo(),
1388 Diag.getKind(), Diag.getMessage(),
1389 Diag.getLineContents(), Diag.getRanges());
1391 if (Parser->SavedDiagHandler)
1392 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1394 NewDiag.print(0, OS);
1397 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1398 const std::vector<StringRef> &Parameters,
1399 const std::vector<std::vector<AsmToken> > &A,
1401 raw_svector_ostream OS(Buf);
1402 unsigned NParameters = Parameters.size();
1403 if (NParameters != 0 && NParameters != A.size())
1404 return Error(L, "Wrong number of arguments");
1406 while (!Body.empty()) {
1407 // Scan for the next substitution.
1408 std::size_t End = Body.size(), Pos = 0;
1409 for (; Pos != End; ++Pos) {
1410 // Check for a substitution or escape.
1412 // This macro has no parameters, look for $0, $1, etc.
1413 if (Body[Pos] != '$' || Pos + 1 == End)
1416 char Next = Body[Pos + 1];
1417 if (Next == '$' || Next == 'n' || isdigit(Next))
1420 // This macro has parameters, look for \foo, \bar, etc.
1421 if (Body[Pos] == '\\' && Pos + 1 != End)
1427 OS << Body.slice(0, Pos);
1429 // Check if we reached the end.
1434 switch (Body[Pos+1]) {
1440 // $n => number of arguments
1445 // $[0-9] => argument
1447 // Missing arguments are ignored.
1448 unsigned Index = Body[Pos+1] - '0';
1449 if (Index >= A.size())
1452 // Otherwise substitute with the token values, with spaces eliminated.
1453 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1454 ie = A[Index].end(); it != ie; ++it)
1455 OS << it->getString();
1461 unsigned I = Pos + 1;
1462 while (isalnum(Body[I]) && I + 1 != End)
1465 const char *Begin = Body.data() + Pos +1;
1466 StringRef Argument(Begin, I - (Pos +1));
1468 for (; Index < NParameters; ++Index)
1469 if (Parameters[Index] == Argument)
1472 // FIXME: We should error at the macro definition.
1473 if (Index == NParameters)
1474 return Error(L, "Parameter not found");
1476 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1477 ie = A[Index].end(); it != ie; ++it)
1478 OS << it->getString();
1480 Pos += 1 + Argument.size();
1482 // Update the scan point.
1483 Body = Body.substr(Pos);
1486 // We include the .endmacro in the buffer as our queue to exit the macro
1488 OS << ".endmacro\n";
1492 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1494 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1498 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1500 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1501 // this, although we should protect against infinite loops.
1502 if (ActiveMacros.size() == 20)
1503 return TokError("macros cannot be nested more than 20 levels deep");
1505 // Parse the macro instantiation arguments.
1506 std::vector<std::vector<AsmToken> > MacroArguments;
1507 MacroArguments.push_back(std::vector<AsmToken>());
1508 unsigned ParenLevel = 0;
1510 if (Lexer.is(AsmToken::Eof))
1511 return TokError("unexpected token in macro instantiation");
1512 if (Lexer.is(AsmToken::EndOfStatement))
1515 // If we aren't inside parentheses and this is a comma, start a new token
1517 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1518 MacroArguments.push_back(std::vector<AsmToken>());
1520 // Adjust the current parentheses level.
1521 if (Lexer.is(AsmToken::LParen))
1523 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1526 // Append the token to the current argument list.
1527 MacroArguments.back().push_back(getTok());
1531 // If there weren't any arguments, erase the token vector so everything
1532 // else knows that. Leaving around the vestigal empty token list confuses
1534 if (MacroArguments.size() == 1 && MacroArguments.back().empty())
1535 MacroArguments.clear();
1537 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1538 // to hold the macro body with substitutions.
1539 SmallString<256> Buf;
1540 StringRef Body = M->Body;
1542 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1545 MemoryBuffer *Instantiation =
1546 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1548 // Create the macro instantiation object and add to the current macro
1549 // instantiation stack.
1550 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1553 ActiveMacros.push_back(MI);
1555 // Jump to the macro instantiation and prime the lexer.
1556 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1557 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1563 void AsmParser::HandleMacroExit() {
1564 // Jump to the EndOfStatement we should return to, and consume it.
1565 JumpToLoc(ActiveMacros.back()->ExitLoc);
1568 // Pop the instantiation entry.
1569 delete ActiveMacros.back();
1570 ActiveMacros.pop_back();
1573 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1574 switch (Value->getKind()) {
1575 case MCExpr::Binary: {
1576 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1577 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1580 case MCExpr::Target:
1581 case MCExpr::Constant:
1583 case MCExpr::SymbolRef: {
1584 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1586 return IsUsedIn(Sym, S.getVariableValue());
1590 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1593 llvm_unreachable("Unknown expr kind!");
1596 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1597 // FIXME: Use better location, we should use proper tokens.
1598 SMLoc EqualLoc = Lexer.getLoc();
1600 const MCExpr *Value;
1601 if (ParseExpression(Value))
1604 // Note: we don't count b as used in "a = b". This is to allow
1608 if (Lexer.isNot(AsmToken::EndOfStatement))
1609 return TokError("unexpected token in assignment");
1611 // Error on assignment to '.'.
1613 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1614 "(use '.space' or '.org').)"));
1617 // Eat the end of statement marker.
1620 // Validate that the LHS is allowed to be a variable (either it has not been
1621 // used as a symbol, or it is an absolute symbol).
1622 MCSymbol *Sym = getContext().LookupSymbol(Name);
1624 // Diagnose assignment to a label.
1626 // FIXME: Diagnostics. Note the location of the definition as a label.
1627 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1628 if (IsUsedIn(Sym, Value))
1629 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1630 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1631 ; // Allow redefinitions of undefined symbols only used in directives.
1632 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1633 return Error(EqualLoc, "redefinition of '" + Name + "'");
1634 else if (!Sym->isVariable())
1635 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1636 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1637 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1640 // Don't count these checks as uses.
1641 Sym->setUsed(false);
1643 Sym = getContext().GetOrCreateSymbol(Name);
1645 // FIXME: Handle '.'.
1647 // Do the assignment.
1648 Out.EmitAssignment(Sym, Value);
1653 /// ParseIdentifier:
1656 bool AsmParser::ParseIdentifier(StringRef &Res) {
1657 // The assembler has relaxed rules for accepting identifiers, in particular we
1658 // allow things like '.globl $foo', which would normally be separate
1659 // tokens. At this level, we have already lexed so we cannot (currently)
1660 // handle this as a context dependent token, instead we detect adjacent tokens
1661 // and return the combined identifier.
1662 if (Lexer.is(AsmToken::Dollar)) {
1663 SMLoc DollarLoc = getLexer().getLoc();
1665 // Consume the dollar sign, and check for a following identifier.
1667 if (Lexer.isNot(AsmToken::Identifier))
1670 // We have a '$' followed by an identifier, make sure they are adjacent.
1671 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1674 // Construct the joined identifier and consume the token.
1675 Res = StringRef(DollarLoc.getPointer(),
1676 getTok().getIdentifier().size() + 1);
1681 if (Lexer.isNot(AsmToken::Identifier) &&
1682 Lexer.isNot(AsmToken::String))
1685 Res = getTok().getIdentifier();
1687 Lex(); // Consume the identifier token.
1692 /// ParseDirectiveSet:
1693 /// ::= .equ identifier ',' expression
1694 /// ::= .equiv identifier ',' expression
1695 /// ::= .set identifier ',' expression
1696 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1699 if (ParseIdentifier(Name))
1700 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1702 if (getLexer().isNot(AsmToken::Comma))
1703 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1706 return ParseAssignment(Name, allow_redef);
1709 bool AsmParser::ParseEscapedString(std::string &Data) {
1710 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1713 StringRef Str = getTok().getStringContents();
1714 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1715 if (Str[i] != '\\') {
1720 // Recognize escaped characters. Note that this escape semantics currently
1721 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1724 return TokError("unexpected backslash at end of string");
1726 // Recognize octal sequences.
1727 if ((unsigned) (Str[i] - '0') <= 7) {
1728 // Consume up to three octal characters.
1729 unsigned Value = Str[i] - '0';
1731 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1733 Value = Value * 8 + (Str[i] - '0');
1735 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1737 Value = Value * 8 + (Str[i] - '0');
1742 return TokError("invalid octal escape sequence (out of range)");
1744 Data += (unsigned char) Value;
1748 // Otherwise recognize individual escapes.
1751 // Just reject invalid escape sequences for now.
1752 return TokError("invalid escape sequence (unrecognized character)");
1754 case 'b': Data += '\b'; break;
1755 case 'f': Data += '\f'; break;
1756 case 'n': Data += '\n'; break;
1757 case 'r': Data += '\r'; break;
1758 case 't': Data += '\t'; break;
1759 case '"': Data += '"'; break;
1760 case '\\': Data += '\\'; break;
1767 /// ParseDirectiveAscii:
1768 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1769 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1770 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1771 CheckForValidSection();
1774 if (getLexer().isNot(AsmToken::String))
1775 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1778 if (ParseEscapedString(Data))
1781 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1783 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1787 if (getLexer().is(AsmToken::EndOfStatement))
1790 if (getLexer().isNot(AsmToken::Comma))
1791 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1800 /// ParseDirectiveValue
1801 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1802 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1803 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1804 CheckForValidSection();
1807 const MCExpr *Value;
1808 SMLoc ExprLoc = getLexer().getLoc();
1809 if (ParseExpression(Value))
1812 // Special case constant expressions to match code generator.
1813 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1814 assert(Size <= 8 && "Invalid size");
1815 uint64_t IntValue = MCE->getValue();
1816 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1817 return Error(ExprLoc, "literal value out of range for directive");
1818 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1820 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1822 if (getLexer().is(AsmToken::EndOfStatement))
1825 // FIXME: Improve diagnostic.
1826 if (getLexer().isNot(AsmToken::Comma))
1827 return TokError("unexpected token in directive");
1836 /// ParseDirectiveRealValue
1837 /// ::= (.single | .double) [ expression (, expression)* ]
1838 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1839 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1840 CheckForValidSection();
1843 // We don't truly support arithmetic on floating point expressions, so we
1844 // have to manually parse unary prefixes.
1846 if (getLexer().is(AsmToken::Minus)) {
1849 } else if (getLexer().is(AsmToken::Plus))
1852 if (getLexer().isNot(AsmToken::Integer) &&
1853 getLexer().isNot(AsmToken::Real) &&
1854 getLexer().isNot(AsmToken::Identifier))
1855 return TokError("unexpected token in directive");
1857 // Convert to an APFloat.
1858 APFloat Value(Semantics);
1859 StringRef IDVal = getTok().getString();
1860 if (getLexer().is(AsmToken::Identifier)) {
1861 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1862 Value = APFloat::getInf(Semantics);
1863 else if (!IDVal.compare_lower("nan"))
1864 Value = APFloat::getNaN(Semantics, false, ~0);
1866 return TokError("invalid floating point literal");
1867 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1868 APFloat::opInvalidOp)
1869 return TokError("invalid floating point literal");
1873 // Consume the numeric token.
1876 // Emit the value as an integer.
1877 APInt AsInt = Value.bitcastToAPInt();
1878 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1879 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1881 if (getLexer().is(AsmToken::EndOfStatement))
1884 if (getLexer().isNot(AsmToken::Comma))
1885 return TokError("unexpected token in directive");
1894 /// ParseDirectiveSpace
1895 /// ::= .space expression [ , expression ]
1896 bool AsmParser::ParseDirectiveSpace() {
1897 CheckForValidSection();
1900 if (ParseAbsoluteExpression(NumBytes))
1903 int64_t FillExpr = 0;
1904 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1905 if (getLexer().isNot(AsmToken::Comma))
1906 return TokError("unexpected token in '.space' directive");
1909 if (ParseAbsoluteExpression(FillExpr))
1912 if (getLexer().isNot(AsmToken::EndOfStatement))
1913 return TokError("unexpected token in '.space' directive");
1919 return TokError("invalid number of bytes in '.space' directive");
1921 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1922 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1927 /// ParseDirectiveZero
1928 /// ::= .zero expression
1929 bool AsmParser::ParseDirectiveZero() {
1930 CheckForValidSection();
1933 if (ParseAbsoluteExpression(NumBytes))
1937 if (getLexer().is(AsmToken::Comma)) {
1939 if (ParseAbsoluteExpression(Val))
1943 if (getLexer().isNot(AsmToken::EndOfStatement))
1944 return TokError("unexpected token in '.zero' directive");
1948 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1953 /// ParseDirectiveFill
1954 /// ::= .fill expression , expression , expression
1955 bool AsmParser::ParseDirectiveFill() {
1956 CheckForValidSection();
1959 if (ParseAbsoluteExpression(NumValues))
1962 if (getLexer().isNot(AsmToken::Comma))
1963 return TokError("unexpected token in '.fill' directive");
1967 if (ParseAbsoluteExpression(FillSize))
1970 if (getLexer().isNot(AsmToken::Comma))
1971 return TokError("unexpected token in '.fill' directive");
1975 if (ParseAbsoluteExpression(FillExpr))
1978 if (getLexer().isNot(AsmToken::EndOfStatement))
1979 return TokError("unexpected token in '.fill' directive");
1983 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1984 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1986 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1987 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1992 /// ParseDirectiveOrg
1993 /// ::= .org expression [ , expression ]
1994 bool AsmParser::ParseDirectiveOrg() {
1995 CheckForValidSection();
1997 const MCExpr *Offset;
1998 SMLoc Loc = getTok().getLoc();
1999 if (ParseExpression(Offset))
2002 // Parse optional fill expression.
2003 int64_t FillExpr = 0;
2004 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2005 if (getLexer().isNot(AsmToken::Comma))
2006 return TokError("unexpected token in '.org' directive");
2009 if (ParseAbsoluteExpression(FillExpr))
2012 if (getLexer().isNot(AsmToken::EndOfStatement))
2013 return TokError("unexpected token in '.org' directive");
2018 // Only limited forms of relocatable expressions are accepted here, it
2019 // has to be relative to the current section. The streamer will return
2020 // 'true' if the expression wasn't evaluatable.
2021 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2022 return Error(Loc, "expected assembly-time absolute expression");
2027 /// ParseDirectiveAlign
2028 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2029 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2030 CheckForValidSection();
2032 SMLoc AlignmentLoc = getLexer().getLoc();
2034 if (ParseAbsoluteExpression(Alignment))
2038 bool HasFillExpr = false;
2039 int64_t FillExpr = 0;
2040 int64_t MaxBytesToFill = 0;
2041 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2042 if (getLexer().isNot(AsmToken::Comma))
2043 return TokError("unexpected token in directive");
2046 // The fill expression can be omitted while specifying a maximum number of
2047 // alignment bytes, e.g:
2049 if (getLexer().isNot(AsmToken::Comma)) {
2051 if (ParseAbsoluteExpression(FillExpr))
2055 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2056 if (getLexer().isNot(AsmToken::Comma))
2057 return TokError("unexpected token in directive");
2060 MaxBytesLoc = getLexer().getLoc();
2061 if (ParseAbsoluteExpression(MaxBytesToFill))
2064 if (getLexer().isNot(AsmToken::EndOfStatement))
2065 return TokError("unexpected token in directive");
2074 // Compute alignment in bytes.
2076 // FIXME: Diagnose overflow.
2077 if (Alignment >= 32) {
2078 Error(AlignmentLoc, "invalid alignment value");
2082 Alignment = 1ULL << Alignment;
2085 // Diagnose non-sensical max bytes to align.
2086 if (MaxBytesLoc.isValid()) {
2087 if (MaxBytesToFill < 1) {
2088 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2089 "many bytes, ignoring maximum bytes expression");
2093 if (MaxBytesToFill >= Alignment) {
2094 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2100 // Check whether we should use optimal code alignment for this .align
2102 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2103 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2104 ValueSize == 1 && UseCodeAlign) {
2105 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2107 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2108 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2115 /// ParseDirectiveSymbolAttribute
2116 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2117 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2118 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2121 SMLoc Loc = getTok().getLoc();
2123 if (ParseIdentifier(Name))
2124 return Error(Loc, "expected identifier in directive");
2126 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2128 // Assembler local symbols don't make any sense here. Complain loudly.
2129 if (Sym->isTemporary())
2130 return Error(Loc, "non-local symbol required in directive");
2132 getStreamer().EmitSymbolAttribute(Sym, Attr);
2134 if (getLexer().is(AsmToken::EndOfStatement))
2137 if (getLexer().isNot(AsmToken::Comma))
2138 return TokError("unexpected token in directive");
2147 /// ParseDirectiveComm
2148 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2149 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2150 CheckForValidSection();
2152 SMLoc IDLoc = getLexer().getLoc();
2154 if (ParseIdentifier(Name))
2155 return TokError("expected identifier in directive");
2157 // Handle the identifier as the key symbol.
2158 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2160 if (getLexer().isNot(AsmToken::Comma))
2161 return TokError("unexpected token in directive");
2165 SMLoc SizeLoc = getLexer().getLoc();
2166 if (ParseAbsoluteExpression(Size))
2169 int64_t Pow2Alignment = 0;
2170 SMLoc Pow2AlignmentLoc;
2171 if (getLexer().is(AsmToken::Comma)) {
2173 Pow2AlignmentLoc = getLexer().getLoc();
2174 if (ParseAbsoluteExpression(Pow2Alignment))
2177 // If this target takes alignments in bytes (not log) validate and convert.
2178 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2179 if (!isPowerOf2_64(Pow2Alignment))
2180 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2181 Pow2Alignment = Log2_64(Pow2Alignment);
2185 if (getLexer().isNot(AsmToken::EndOfStatement))
2186 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2190 // NOTE: a size of zero for a .comm should create a undefined symbol
2191 // but a size of .lcomm creates a bss symbol of size zero.
2193 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2194 "be less than zero");
2196 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2197 // may internally end up wanting an alignment in bytes.
2198 // FIXME: Diagnose overflow.
2199 if (Pow2Alignment < 0)
2200 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2201 "alignment, can't be less than zero");
2203 if (!Sym->isUndefined())
2204 return Error(IDLoc, "invalid symbol redefinition");
2206 // '.lcomm' is equivalent to '.zerofill'.
2207 // Create the Symbol as a common or local common with Size and Pow2Alignment
2209 getStreamer().EmitZerofill(Ctx.getMachOSection(
2210 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2211 0, SectionKind::getBSS()),
2212 Sym, Size, 1 << Pow2Alignment);
2216 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2220 /// ParseDirectiveAbort
2221 /// ::= .abort [... message ...]
2222 bool AsmParser::ParseDirectiveAbort() {
2223 // FIXME: Use loc from directive.
2224 SMLoc Loc = getLexer().getLoc();
2226 StringRef Str = ParseStringToEndOfStatement();
2227 if (getLexer().isNot(AsmToken::EndOfStatement))
2228 return TokError("unexpected token in '.abort' directive");
2233 Error(Loc, ".abort detected. Assembly stopping.");
2235 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2236 // FIXME: Actually abort assembly here.
2241 /// ParseDirectiveInclude
2242 /// ::= .include "filename"
2243 bool AsmParser::ParseDirectiveInclude() {
2244 if (getLexer().isNot(AsmToken::String))
2245 return TokError("expected string in '.include' directive");
2247 std::string Filename = getTok().getString();
2248 SMLoc IncludeLoc = getLexer().getLoc();
2251 if (getLexer().isNot(AsmToken::EndOfStatement))
2252 return TokError("unexpected token in '.include' directive");
2254 // Strip the quotes.
2255 Filename = Filename.substr(1, Filename.size()-2);
2257 // Attempt to switch the lexer to the included file before consuming the end
2258 // of statement to avoid losing it when we switch.
2259 if (EnterIncludeFile(Filename)) {
2260 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2267 /// ParseDirectiveIncbin
2268 /// ::= .incbin "filename"
2269 bool AsmParser::ParseDirectiveIncbin() {
2270 if (getLexer().isNot(AsmToken::String))
2271 return TokError("expected string in '.incbin' directive");
2273 std::string Filename = getTok().getString();
2274 SMLoc IncbinLoc = getLexer().getLoc();
2277 if (getLexer().isNot(AsmToken::EndOfStatement))
2278 return TokError("unexpected token in '.incbin' directive");
2280 // Strip the quotes.
2281 Filename = Filename.substr(1, Filename.size()-2);
2283 // Attempt to process the included file.
2284 if (ProcessIncbinFile(Filename)) {
2285 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2292 /// ParseDirectiveIf
2293 /// ::= .if expression
2294 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2295 TheCondStack.push_back(TheCondState);
2296 TheCondState.TheCond = AsmCond::IfCond;
2297 if(TheCondState.Ignore) {
2298 EatToEndOfStatement();
2302 if (ParseAbsoluteExpression(ExprValue))
2305 if (getLexer().isNot(AsmToken::EndOfStatement))
2306 return TokError("unexpected token in '.if' directive");
2310 TheCondState.CondMet = ExprValue;
2311 TheCondState.Ignore = !TheCondState.CondMet;
2317 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2319 TheCondStack.push_back(TheCondState);
2320 TheCondState.TheCond = AsmCond::IfCond;
2322 if (TheCondState.Ignore) {
2323 EatToEndOfStatement();
2325 if (ParseIdentifier(Name))
2326 return TokError("expected identifier after '.ifdef'");
2330 MCSymbol *Sym = getContext().LookupSymbol(Name);
2333 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2335 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2336 TheCondState.Ignore = !TheCondState.CondMet;
2342 /// ParseDirectiveElseIf
2343 /// ::= .elseif expression
2344 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2345 if (TheCondState.TheCond != AsmCond::IfCond &&
2346 TheCondState.TheCond != AsmCond::ElseIfCond)
2347 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2349 TheCondState.TheCond = AsmCond::ElseIfCond;
2351 bool LastIgnoreState = false;
2352 if (!TheCondStack.empty())
2353 LastIgnoreState = TheCondStack.back().Ignore;
2354 if (LastIgnoreState || TheCondState.CondMet) {
2355 TheCondState.Ignore = true;
2356 EatToEndOfStatement();
2360 if (ParseAbsoluteExpression(ExprValue))
2363 if (getLexer().isNot(AsmToken::EndOfStatement))
2364 return TokError("unexpected token in '.elseif' directive");
2367 TheCondState.CondMet = ExprValue;
2368 TheCondState.Ignore = !TheCondState.CondMet;
2374 /// ParseDirectiveElse
2376 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2377 if (getLexer().isNot(AsmToken::EndOfStatement))
2378 return TokError("unexpected token in '.else' directive");
2382 if (TheCondState.TheCond != AsmCond::IfCond &&
2383 TheCondState.TheCond != AsmCond::ElseIfCond)
2384 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2386 TheCondState.TheCond = AsmCond::ElseCond;
2387 bool LastIgnoreState = false;
2388 if (!TheCondStack.empty())
2389 LastIgnoreState = TheCondStack.back().Ignore;
2390 if (LastIgnoreState || TheCondState.CondMet)
2391 TheCondState.Ignore = true;
2393 TheCondState.Ignore = false;
2398 /// ParseDirectiveEndIf
2400 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2401 if (getLexer().isNot(AsmToken::EndOfStatement))
2402 return TokError("unexpected token in '.endif' directive");
2406 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2407 TheCondStack.empty())
2408 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2410 if (!TheCondStack.empty()) {
2411 TheCondState = TheCondStack.back();
2412 TheCondStack.pop_back();
2418 /// ParseDirectiveFile
2419 /// ::= .file [number] filename
2420 /// ::= .file number directory filename
2421 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2422 // FIXME: I'm not sure what this is.
2423 int64_t FileNumber = -1;
2424 SMLoc FileNumberLoc = getLexer().getLoc();
2425 if (getLexer().is(AsmToken::Integer)) {
2426 FileNumber = getTok().getIntVal();
2430 return TokError("file number less than one");
2433 if (getLexer().isNot(AsmToken::String))
2434 return TokError("unexpected token in '.file' directive");
2436 // Usually the directory and filename together, otherwise just the directory.
2437 StringRef Path = getTok().getString();
2438 Path = Path.substr(1, Path.size()-2);
2441 StringRef Directory;
2443 if (getLexer().is(AsmToken::String)) {
2444 if (FileNumber == -1)
2445 return TokError("explicit path specified, but no file number");
2446 Filename = getTok().getString();
2447 Filename = Filename.substr(1, Filename.size()-2);
2454 if (getLexer().isNot(AsmToken::EndOfStatement))
2455 return TokError("unexpected token in '.file' directive");
2457 if (FileNumber == -1)
2458 getStreamer().EmitFileDirective(Filename);
2460 if (getContext().getGenDwarfForAssembly() == true)
2461 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2462 "used to generate dwarf debug info for assembly code");
2464 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2465 Error(FileNumberLoc, "file number already allocated");
2471 /// ParseDirectiveLine
2472 /// ::= .line [number]
2473 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2474 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2475 if (getLexer().isNot(AsmToken::Integer))
2476 return TokError("unexpected token in '.line' directive");
2478 int64_t LineNumber = getTok().getIntVal();
2482 // FIXME: Do something with the .line.
2485 if (getLexer().isNot(AsmToken::EndOfStatement))
2486 return TokError("unexpected token in '.line' directive");
2492 /// ParseDirectiveLoc
2493 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2494 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2495 /// The first number is a file number, must have been previously assigned with
2496 /// a .file directive, the second number is the line number and optionally the
2497 /// third number is a column position (zero if not specified). The remaining
2498 /// optional items are .loc sub-directives.
2499 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2501 if (getLexer().isNot(AsmToken::Integer))
2502 return TokError("unexpected token in '.loc' directive");
2503 int64_t FileNumber = getTok().getIntVal();
2505 return TokError("file number less than one in '.loc' directive");
2506 if (!getContext().isValidDwarfFileNumber(FileNumber))
2507 return TokError("unassigned file number in '.loc' directive");
2510 int64_t LineNumber = 0;
2511 if (getLexer().is(AsmToken::Integer)) {
2512 LineNumber = getTok().getIntVal();
2514 return TokError("line number less than one in '.loc' directive");
2518 int64_t ColumnPos = 0;
2519 if (getLexer().is(AsmToken::Integer)) {
2520 ColumnPos = getTok().getIntVal();
2522 return TokError("column position less than zero in '.loc' directive");
2526 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2528 int64_t Discriminator = 0;
2529 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2531 if (getLexer().is(AsmToken::EndOfStatement))
2535 SMLoc Loc = getTok().getLoc();
2536 if (getParser().ParseIdentifier(Name))
2537 return TokError("unexpected token in '.loc' directive");
2539 if (Name == "basic_block")
2540 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2541 else if (Name == "prologue_end")
2542 Flags |= DWARF2_FLAG_PROLOGUE_END;
2543 else if (Name == "epilogue_begin")
2544 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2545 else if (Name == "is_stmt") {
2546 SMLoc Loc = getTok().getLoc();
2547 const MCExpr *Value;
2548 if (getParser().ParseExpression(Value))
2550 // The expression must be the constant 0 or 1.
2551 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2552 int Value = MCE->getValue();
2554 Flags &= ~DWARF2_FLAG_IS_STMT;
2555 else if (Value == 1)
2556 Flags |= DWARF2_FLAG_IS_STMT;
2558 return Error(Loc, "is_stmt value not 0 or 1");
2561 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2564 else if (Name == "isa") {
2565 SMLoc Loc = getTok().getLoc();
2566 const MCExpr *Value;
2567 if (getParser().ParseExpression(Value))
2569 // The expression must be a constant greater or equal to 0.
2570 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2571 int Value = MCE->getValue();
2573 return Error(Loc, "isa number less than zero");
2577 return Error(Loc, "isa number not a constant value");
2580 else if (Name == "discriminator") {
2581 if (getParser().ParseAbsoluteExpression(Discriminator))
2585 return Error(Loc, "unknown sub-directive in '.loc' directive");
2588 if (getLexer().is(AsmToken::EndOfStatement))
2593 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2594 Isa, Discriminator, StringRef());
2599 /// ParseDirectiveStabs
2600 /// ::= .stabs string, number, number, number
2601 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2602 SMLoc DirectiveLoc) {
2603 return TokError("unsupported directive '" + Directive + "'");
2606 /// ParseDirectiveCFISections
2607 /// ::= .cfi_sections section [, section]
2608 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2609 SMLoc DirectiveLoc) {
2614 if (getParser().ParseIdentifier(Name))
2615 return TokError("Expected an identifier");
2617 if (Name == ".eh_frame")
2619 else if (Name == ".debug_frame")
2622 if (getLexer().is(AsmToken::Comma)) {
2625 if (getParser().ParseIdentifier(Name))
2626 return TokError("Expected an identifier");
2628 if (Name == ".eh_frame")
2630 else if (Name == ".debug_frame")
2634 getStreamer().EmitCFISections(EH, Debug);
2639 /// ParseDirectiveCFIStartProc
2640 /// ::= .cfi_startproc
2641 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2642 SMLoc DirectiveLoc) {
2643 getStreamer().EmitCFIStartProc();
2647 /// ParseDirectiveCFIEndProc
2648 /// ::= .cfi_endproc
2649 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2650 getStreamer().EmitCFIEndProc();
2654 /// ParseRegisterOrRegisterNumber - parse register name or number.
2655 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2656 SMLoc DirectiveLoc) {
2659 if (getLexer().isNot(AsmToken::Integer)) {
2660 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2663 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2665 return getParser().ParseAbsoluteExpression(Register);
2670 /// ParseDirectiveCFIDefCfa
2671 /// ::= .cfi_def_cfa register, offset
2672 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2673 SMLoc DirectiveLoc) {
2674 int64_t Register = 0;
2675 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2678 if (getLexer().isNot(AsmToken::Comma))
2679 return TokError("unexpected token in directive");
2683 if (getParser().ParseAbsoluteExpression(Offset))
2686 getStreamer().EmitCFIDefCfa(Register, Offset);
2690 /// ParseDirectiveCFIDefCfaOffset
2691 /// ::= .cfi_def_cfa_offset offset
2692 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2693 SMLoc DirectiveLoc) {
2695 if (getParser().ParseAbsoluteExpression(Offset))
2698 getStreamer().EmitCFIDefCfaOffset(Offset);
2702 /// ParseDirectiveCFIAdjustCfaOffset
2703 /// ::= .cfi_adjust_cfa_offset adjustment
2704 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2705 SMLoc DirectiveLoc) {
2706 int64_t Adjustment = 0;
2707 if (getParser().ParseAbsoluteExpression(Adjustment))
2710 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2714 /// ParseDirectiveCFIDefCfaRegister
2715 /// ::= .cfi_def_cfa_register register
2716 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2717 SMLoc DirectiveLoc) {
2718 int64_t Register = 0;
2719 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2722 getStreamer().EmitCFIDefCfaRegister(Register);
2726 /// ParseDirectiveCFIOffset
2727 /// ::= .cfi_offset register, offset
2728 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2729 int64_t Register = 0;
2732 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2735 if (getLexer().isNot(AsmToken::Comma))
2736 return TokError("unexpected token in directive");
2739 if (getParser().ParseAbsoluteExpression(Offset))
2742 getStreamer().EmitCFIOffset(Register, Offset);
2746 /// ParseDirectiveCFIRelOffset
2747 /// ::= .cfi_rel_offset register, offset
2748 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2749 SMLoc DirectiveLoc) {
2750 int64_t Register = 0;
2752 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2755 if (getLexer().isNot(AsmToken::Comma))
2756 return TokError("unexpected token in directive");
2760 if (getParser().ParseAbsoluteExpression(Offset))
2763 getStreamer().EmitCFIRelOffset(Register, Offset);
2767 static bool isValidEncoding(int64_t Encoding) {
2768 if (Encoding & ~0xff)
2771 if (Encoding == dwarf::DW_EH_PE_omit)
2774 const unsigned Format = Encoding & 0xf;
2775 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2776 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2777 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2778 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2781 const unsigned Application = Encoding & 0x70;
2782 if (Application != dwarf::DW_EH_PE_absptr &&
2783 Application != dwarf::DW_EH_PE_pcrel)
2789 /// ParseDirectiveCFIPersonalityOrLsda
2790 /// ::= .cfi_personality encoding, [symbol_name]
2791 /// ::= .cfi_lsda encoding, [symbol_name]
2792 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2793 SMLoc DirectiveLoc) {
2794 int64_t Encoding = 0;
2795 if (getParser().ParseAbsoluteExpression(Encoding))
2797 if (Encoding == dwarf::DW_EH_PE_omit)
2800 if (!isValidEncoding(Encoding))
2801 return TokError("unsupported encoding.");
2803 if (getLexer().isNot(AsmToken::Comma))
2804 return TokError("unexpected token in directive");
2808 if (getParser().ParseIdentifier(Name))
2809 return TokError("expected identifier in directive");
2811 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2813 if (IDVal == ".cfi_personality")
2814 getStreamer().EmitCFIPersonality(Sym, Encoding);
2816 assert(IDVal == ".cfi_lsda");
2817 getStreamer().EmitCFILsda(Sym, Encoding);
2822 /// ParseDirectiveCFIRememberState
2823 /// ::= .cfi_remember_state
2824 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2825 SMLoc DirectiveLoc) {
2826 getStreamer().EmitCFIRememberState();
2830 /// ParseDirectiveCFIRestoreState
2831 /// ::= .cfi_remember_state
2832 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2833 SMLoc DirectiveLoc) {
2834 getStreamer().EmitCFIRestoreState();
2838 /// ParseDirectiveCFISameValue
2839 /// ::= .cfi_same_value register
2840 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2841 SMLoc DirectiveLoc) {
2842 int64_t Register = 0;
2844 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2847 getStreamer().EmitCFISameValue(Register);
2852 /// ParseDirectiveCFIRestore
2853 /// ::= .cfi_restore register
2854 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2855 SMLoc DirectiveLoc) {
2856 int64_t Register = 0;
2857 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2860 getStreamer().EmitCFIRestore(Register);
2865 /// ParseDirectiveCFIEscape
2866 /// ::= .cfi_escape expression[,...]
2867 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2868 SMLoc DirectiveLoc) {
2871 if (getParser().ParseAbsoluteExpression(CurrValue))
2874 Values.push_back((uint8_t)CurrValue);
2876 while (getLexer().is(AsmToken::Comma)) {
2879 if (getParser().ParseAbsoluteExpression(CurrValue))
2882 Values.push_back((uint8_t)CurrValue);
2885 getStreamer().EmitCFIEscape(Values);
2889 /// ParseDirectiveCFISignalFrame
2890 /// ::= .cfi_signal_frame
2891 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2892 SMLoc DirectiveLoc) {
2893 if (getLexer().isNot(AsmToken::EndOfStatement))
2894 return Error(getLexer().getLoc(),
2895 "unexpected token in '" + Directive + "' directive");
2897 getStreamer().EmitCFISignalFrame();
2902 /// ParseDirectiveMacrosOnOff
2905 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2906 SMLoc DirectiveLoc) {
2907 if (getLexer().isNot(AsmToken::EndOfStatement))
2908 return Error(getLexer().getLoc(),
2909 "unexpected token in '" + Directive + "' directive");
2911 getParser().MacrosEnabled = Directive == ".macros_on";
2916 /// ParseDirectiveMacro
2917 /// ::= .macro name [parameters]
2918 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2919 SMLoc DirectiveLoc) {
2921 if (getParser().ParseIdentifier(Name))
2922 return TokError("expected identifier in directive");
2924 std::vector<StringRef> Parameters;
2925 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2927 StringRef Parameter;
2928 if (getParser().ParseIdentifier(Parameter))
2929 return TokError("expected identifier in directive");
2930 Parameters.push_back(Parameter);
2932 if (getLexer().isNot(AsmToken::Comma))
2938 if (getLexer().isNot(AsmToken::EndOfStatement))
2939 return TokError("unexpected token in '.macro' directive");
2941 // Eat the end of statement.
2944 AsmToken EndToken, StartToken = getTok();
2946 // Lex the macro definition.
2948 // Check whether we have reached the end of the file.
2949 if (getLexer().is(AsmToken::Eof))
2950 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2952 // Otherwise, check whether we have reach the .endmacro.
2953 if (getLexer().is(AsmToken::Identifier) &&
2954 (getTok().getIdentifier() == ".endm" ||
2955 getTok().getIdentifier() == ".endmacro")) {
2956 EndToken = getTok();
2958 if (getLexer().isNot(AsmToken::EndOfStatement))
2959 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2964 // Otherwise, scan til the end of the statement.
2965 getParser().EatToEndOfStatement();
2968 if (getParser().MacroMap.lookup(Name)) {
2969 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2972 const char *BodyStart = StartToken.getLoc().getPointer();
2973 const char *BodyEnd = EndToken.getLoc().getPointer();
2974 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2975 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2979 /// ParseDirectiveEndMacro
2982 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2983 SMLoc DirectiveLoc) {
2984 if (getLexer().isNot(AsmToken::EndOfStatement))
2985 return TokError("unexpected token in '" + Directive + "' directive");
2987 // If we are inside a macro instantiation, terminate the current
2989 if (!getParser().ActiveMacros.empty()) {
2990 getParser().HandleMacroExit();
2994 // Otherwise, this .endmacro is a stray entry in the file; well formed
2995 // .endmacro directives are handled during the macro definition parsing.
2996 return TokError("unexpected '" + Directive + "' in file, "
2997 "no current macro definition");
3000 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3001 getParser().CheckForValidSection();
3003 const MCExpr *Value;
3005 if (getParser().ParseExpression(Value))
3008 if (getLexer().isNot(AsmToken::EndOfStatement))
3009 return TokError("unexpected token in directive");
3011 if (DirName[1] == 's')
3012 getStreamer().EmitSLEB128Value(Value);
3014 getStreamer().EmitULEB128Value(Value);
3020 /// \brief Create an MCAsmParser instance.
3021 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3022 MCContext &C, MCStreamer &Out,
3023 const MCAsmInfo &MAI) {
3024 return new AsmParser(SM, C, Out, MAI);