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/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCTargetAsmParser.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/raw_ostream.h"
42 FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
47 /// \brief Helper class for tracking macro definitions.
51 std::vector<StringRef> Parameters;
54 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
58 /// \brief Helper class for storing information about an active macro
60 struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
70 /// The location where parsing should resume upon instantiation completion.
74 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
78 /// \brief The concrete assembly parser instance.
79 class AsmParser : public MCAsmParser {
80 friend class GenericAsmParser;
82 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
90 SourceMgr::DiagHandlerTy SavedDiagHandler;
91 void *SavedDiagContext;
92 MCAsmParserExtension *GenericParser;
93 MCAsmParserExtension *PlatformParser;
95 /// This is the current buffer index we're lexing from as managed by the
100 std::vector<AsmCond> TheCondStack;
102 /// DirectiveMap - This is a table handlers for directives. Each handler is
103 /// invoked after the directive identifier is read and is responsible for
104 /// parsing and validating the rest of the directive. The handler is passed
105 /// in the directive name and the location of the directive keyword.
106 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
108 /// MacroMap - Map of currently defined macros.
109 StringMap<Macro*> MacroMap;
111 /// ActiveMacros - Stack of active macro instantiations.
112 std::vector<MacroInstantiation*> ActiveMacros;
114 /// Boolean tracking whether macro substitution is enabled.
115 unsigned MacrosEnabled : 1;
117 /// Flag tracking whether any errors have been encountered.
118 unsigned HadError : 1;
120 /// The values from the last parsed cpp hash file line comment if any.
121 StringRef CppHashFilename;
122 int64_t CppHashLineNumber;
125 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
126 unsigned AssemblerDialect;
129 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
130 const MCAsmInfo &MAI);
133 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
135 void AddDirectiveHandler(MCAsmParserExtension *Object,
137 DirectiveHandler Handler) {
138 DirectiveMap[Directive] = std::make_pair(Object, Handler);
142 /// @name MCAsmParser Interface
145 virtual SourceMgr &getSourceManager() { return SrcMgr; }
146 virtual MCAsmLexer &getLexer() { return Lexer; }
147 virtual MCContext &getContext() { return Ctx; }
148 virtual MCStreamer &getStreamer() { return Out; }
149 virtual unsigned getAssemblerDialect() {
150 if (AssemblerDialect == ~0U)
151 return MAI.getAssemblerDialect();
153 return AssemblerDialect;
155 virtual void setAssemblerDialect(unsigned i) {
156 AssemblerDialect = i;
159 virtual bool Warning(SMLoc L, const Twine &Msg,
160 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
161 virtual bool Error(SMLoc L, const Twine &Msg,
162 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
164 const AsmToken &Lex();
166 bool ParseExpression(const MCExpr *&Res);
167 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
168 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
169 virtual bool ParseAbsoluteExpression(int64_t &Res);
174 void CheckForValidSection();
176 bool ParseStatement();
177 void EatToEndOfLine();
178 bool ParseCppHashLineFilenameComment(const SMLoc &L);
180 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
181 bool expandMacro(SmallString<256> &Buf, StringRef Body,
182 const std::vector<StringRef> &Parameters,
183 const std::vector<std::vector<AsmToken> > &A,
185 void HandleMacroExit();
187 void PrintMacroInstantiations();
188 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
189 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
190 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
192 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
194 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
195 bool EnterIncludeFile(const std::string &Filename);
196 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
197 /// This returns true on failure.
198 bool ProcessIncbinFile(const std::string &Filename);
200 /// \brief Reset the current lexer position to that given by \arg Loc. The
201 /// current token is not set; clients should ensure Lex() is called
203 void JumpToLoc(SMLoc Loc);
205 void EatToEndOfStatement();
207 /// \brief Parse up to the end of statement and a return the contents from the
208 /// current token until the end of the statement; the current token on exit
209 /// will be either the EndOfStatement or EOF.
210 StringRef ParseStringToEndOfStatement();
212 /// \brief Parse until the end of a statement or a comma is encountered,
213 /// return the contents from the current token up to the end or comma.
214 StringRef ParseStringToComma();
216 bool ParseAssignment(StringRef Name, bool allow_redef);
218 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
219 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
220 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
221 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
223 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
224 /// and set \arg Res to the identifier contents.
225 bool ParseIdentifier(StringRef &Res);
227 // Directive Parsing.
229 // ".ascii", ".asciiz", ".string"
230 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
231 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
232 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
233 bool ParseDirectiveFill(); // ".fill"
234 bool ParseDirectiveSpace(); // ".space"
235 bool ParseDirectiveZero(); // ".zero"
236 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
237 bool ParseDirectiveOrg(); // ".org"
238 // ".align{,32}", ".p2align{,w,l}"
239 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
241 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
242 /// accepts a single symbol (which should be a label or an external).
243 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
245 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
247 bool ParseDirectiveAbort(); // ".abort"
248 bool ParseDirectiveInclude(); // ".include"
249 bool ParseDirectiveIncbin(); // ".incbin"
251 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
252 // ".ifb" or ".ifnb", depending on ExpectBlank.
253 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
254 // ".ifc" or ".ifnc", depending on ExpectEqual.
255 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
256 // ".ifdef" or ".ifndef", depending on expect_defined
257 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
258 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
259 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
260 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
262 /// ParseEscapedString - Parse the current token as a string which may include
263 /// escaped characters and return the string contents.
264 bool ParseEscapedString(std::string &Data);
266 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
267 MCSymbolRefExpr::VariantKind Variant);
270 /// \brief Generic implementations of directive handling, etc. which is shared
271 /// (or the default, at least) for all assembler parser.
272 class GenericAsmParser : public MCAsmParserExtension {
273 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
274 void AddDirectiveHandler(StringRef Directive) {
275 getParser().AddDirectiveHandler(this, Directive,
276 HandleDirective<GenericAsmParser, Handler>);
279 GenericAsmParser() {}
281 AsmParser &getParser() {
282 return (AsmParser&) this->MCAsmParserExtension::getParser();
285 virtual void Initialize(MCAsmParser &Parser) {
286 // Call the base implementation.
287 this->MCAsmParserExtension::Initialize(Parser);
289 // Debugging directives.
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
291 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
293 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
296 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
298 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
300 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
302 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
305 ".cfi_def_cfa_offset");
306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
307 ".cfi_adjust_cfa_offset");
308 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
309 ".cfi_def_cfa_register");
310 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
312 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
315 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
317 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
319 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
321 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
323 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
325 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
327 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
329 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
332 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
334 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
336 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
337 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
338 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
340 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
341 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
344 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
346 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
347 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
348 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
349 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
350 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
351 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
352 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
353 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
354 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
355 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
356 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
357 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
358 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
359 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
360 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
361 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
362 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
363 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
364 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
365 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
367 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
368 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
369 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
371 bool ParseDirectiveLEB128(StringRef, SMLoc);
378 extern MCAsmParserExtension *createDarwinAsmParser();
379 extern MCAsmParserExtension *createELFAsmParser();
380 extern MCAsmParserExtension *createCOFFAsmParser();
384 enum { DEFAULT_ADDRSPACE = 0 };
386 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
387 MCStreamer &_Out, const MCAsmInfo &_MAI)
388 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
389 GenericParser(new GenericAsmParser), PlatformParser(0),
390 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
391 AssemblerDialect(~0U) {
392 // Save the old handler.
393 SavedDiagHandler = SrcMgr.getDiagHandler();
394 SavedDiagContext = SrcMgr.getDiagContext();
395 // Set our own handler which calls the saved handler.
396 SrcMgr.setDiagHandler(DiagHandler, this);
397 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
399 // Initialize the generic parser.
400 GenericParser->Initialize(*this);
402 // Initialize the platform / file format parser.
404 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
406 if (_MAI.hasMicrosoftFastStdCallMangling()) {
407 PlatformParser = createCOFFAsmParser();
408 PlatformParser->Initialize(*this);
409 } else if (_MAI.hasSubsectionsViaSymbols()) {
410 PlatformParser = createDarwinAsmParser();
411 PlatformParser->Initialize(*this);
413 PlatformParser = createELFAsmParser();
414 PlatformParser->Initialize(*this);
418 AsmParser::~AsmParser() {
419 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
421 // Destroy any macros.
422 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
423 ie = MacroMap.end(); it != ie; ++it)
424 delete it->getValue();
426 delete PlatformParser;
427 delete GenericParser;
430 void AsmParser::PrintMacroInstantiations() {
431 // Print the active macro instantiation stack.
432 for (std::vector<MacroInstantiation*>::const_reverse_iterator
433 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
434 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
435 "while in macro instantiation");
438 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
439 if (FatalAssemblerWarnings)
440 return Error(L, Msg, Ranges);
441 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
442 PrintMacroInstantiations();
446 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
448 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
449 PrintMacroInstantiations();
453 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
454 std::string IncludedFile;
455 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
461 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
466 /// Process the specified .incbin file by seaching for it in the include paths
467 /// then just emiting the byte contents of the file to the streamer. This
468 /// returns true on failure.
469 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
470 std::string IncludedFile;
471 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
475 // Pick up the bytes from the file and emit them.
476 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
481 void AsmParser::JumpToLoc(SMLoc Loc) {
482 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
483 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
486 const AsmToken &AsmParser::Lex() {
487 const AsmToken *tok = &Lexer.Lex();
489 if (tok->is(AsmToken::Eof)) {
490 // If this is the end of an included file, pop the parent file off the
492 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
493 if (ParentIncludeLoc != SMLoc()) {
494 JumpToLoc(ParentIncludeLoc);
499 if (tok->is(AsmToken::Error))
500 Error(Lexer.getErrLoc(), Lexer.getErr());
505 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
506 // Create the initial section, if requested.
507 if (!NoInitialTextSection)
514 AsmCond StartingCondState = TheCondState;
516 // If we are generating dwarf for assembly source files save the initial text
517 // section and generate a .file directive.
518 if (getContext().getGenDwarfForAssembly()) {
519 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
520 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
521 getStreamer().EmitLabel(SectionStartSym);
522 getContext().setGenDwarfSectionStartSym(SectionStartSym);
523 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
524 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
527 // While we have input, parse each statement.
528 while (Lexer.isNot(AsmToken::Eof)) {
529 if (!ParseStatement()) continue;
531 // We had an error, validate that one was emitted and recover by skipping to
533 assert(HadError && "Parse statement returned an error, but none emitted!");
534 EatToEndOfStatement();
537 if (TheCondState.TheCond != StartingCondState.TheCond ||
538 TheCondState.Ignore != StartingCondState.Ignore)
539 return TokError("unmatched .ifs or .elses");
541 // Check to see there are no empty DwarfFile slots.
542 const std::vector<MCDwarfFile *> &MCDwarfFiles =
543 getContext().getMCDwarfFiles();
544 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
545 if (!MCDwarfFiles[i])
546 TokError("unassigned file number: " + Twine(i) + " for .file directives");
549 // Check to see that all assembler local symbols were actually defined.
550 // Targets that don't do subsections via symbols may not want this, though,
551 // so conservatively exclude them. Only do this if we're finalizing, though,
552 // as otherwise we won't necessarilly have seen everything yet.
553 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
554 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
555 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
558 MCSymbol *Sym = i->getValue();
559 // Variable symbols may not be marked as defined, so check those
560 // explicitly. If we know it's a variable, we have a definition for
561 // the purposes of this check.
562 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
563 // FIXME: We would really like to refer back to where the symbol was
564 // first referenced for a source location. We need to add something
565 // to track that. Currently, we just point to the end of the file.
566 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
567 "assembler local symbol '" + Sym->getName() +
573 // Finalize the output stream if there are no errors and if the client wants
575 if (!HadError && !NoFinalize)
581 void AsmParser::CheckForValidSection() {
582 if (!getStreamer().getCurrentSection()) {
583 TokError("expected section directive before assembly directive");
584 Out.SwitchSection(Ctx.getMachOSection(
586 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
587 0, SectionKind::getText()));
591 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
592 void AsmParser::EatToEndOfStatement() {
593 while (Lexer.isNot(AsmToken::EndOfStatement) &&
594 Lexer.isNot(AsmToken::Eof))
598 if (Lexer.is(AsmToken::EndOfStatement))
602 StringRef AsmParser::ParseStringToEndOfStatement() {
603 const char *Start = getTok().getLoc().getPointer();
605 while (Lexer.isNot(AsmToken::EndOfStatement) &&
606 Lexer.isNot(AsmToken::Eof))
609 const char *End = getTok().getLoc().getPointer();
610 return StringRef(Start, End - Start);
613 StringRef AsmParser::ParseStringToComma() {
614 const char *Start = getTok().getLoc().getPointer();
616 while (Lexer.isNot(AsmToken::EndOfStatement) &&
617 Lexer.isNot(AsmToken::Comma) &&
618 Lexer.isNot(AsmToken::Eof))
621 const char *End = getTok().getLoc().getPointer();
622 return StringRef(Start, End - Start);
625 /// ParseParenExpr - Parse a paren expression and return it.
626 /// NOTE: This assumes the leading '(' has already been consumed.
628 /// parenexpr ::= expr)
630 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
631 if (ParseExpression(Res)) return true;
632 if (Lexer.isNot(AsmToken::RParen))
633 return TokError("expected ')' in parentheses expression");
634 EndLoc = Lexer.getLoc();
639 /// ParseBracketExpr - Parse a bracket expression and return it.
640 /// NOTE: This assumes the leading '[' has already been consumed.
642 /// bracketexpr ::= expr]
644 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
645 if (ParseExpression(Res)) return true;
646 if (Lexer.isNot(AsmToken::RBrac))
647 return TokError("expected ']' in brackets expression");
648 EndLoc = Lexer.getLoc();
653 /// ParsePrimaryExpr - Parse a primary expression and return it.
654 /// primaryexpr ::= (parenexpr
655 /// primaryexpr ::= symbol
656 /// primaryexpr ::= number
657 /// primaryexpr ::= '.'
658 /// primaryexpr ::= ~,+,- primaryexpr
659 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
660 switch (Lexer.getKind()) {
662 return TokError("unknown token in expression");
663 // If we have an error assume that we've already handled it.
664 case AsmToken::Error:
666 case AsmToken::Exclaim:
667 Lex(); // Eat the operator.
668 if (ParsePrimaryExpr(Res, EndLoc))
670 Res = MCUnaryExpr::CreateLNot(Res, getContext());
672 case AsmToken::Dollar:
673 case AsmToken::String:
674 case AsmToken::Identifier: {
675 EndLoc = Lexer.getLoc();
677 StringRef Identifier;
678 if (ParseIdentifier(Identifier))
681 // This is a symbol reference.
682 std::pair<StringRef, StringRef> Split = Identifier.split('@');
683 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
685 // Lookup the symbol variant if used.
686 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
687 if (Split.first.size() != Identifier.size()) {
688 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
689 if (Variant == MCSymbolRefExpr::VK_Invalid) {
690 Variant = MCSymbolRefExpr::VK_None;
691 return TokError("invalid variant '" + Split.second + "'");
695 // If this is an absolute variable reference, substitute it now to preserve
696 // semantics in the face of reassignment.
697 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
699 return Error(EndLoc, "unexpected modifier on variable reference");
701 Res = Sym->getVariableValue();
705 // Otherwise create a symbol ref.
706 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
709 case AsmToken::Integer: {
710 SMLoc Loc = getTok().getLoc();
711 int64_t IntVal = getTok().getIntVal();
712 Res = MCConstantExpr::Create(IntVal, getContext());
713 EndLoc = Lexer.getLoc();
715 // Look for 'b' or 'f' following an Integer as a directional label
716 if (Lexer.getKind() == AsmToken::Identifier) {
717 StringRef IDVal = getTok().getString();
718 if (IDVal == "f" || IDVal == "b"){
719 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
720 IDVal == "f" ? 1 : 0);
721 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
723 if(IDVal == "b" && Sym->isUndefined())
724 return Error(Loc, "invalid reference to undefined symbol");
725 EndLoc = Lexer.getLoc();
726 Lex(); // Eat identifier.
731 case AsmToken::Real: {
732 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
733 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
734 Res = MCConstantExpr::Create(IntVal, getContext());
738 case AsmToken::Dot: {
739 // This is a '.' reference, which references the current PC. Emit a
740 // temporary label to the streamer and refer to it.
741 MCSymbol *Sym = Ctx.CreateTempSymbol();
743 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
744 EndLoc = Lexer.getLoc();
745 Lex(); // Eat identifier.
748 case AsmToken::LParen:
749 Lex(); // Eat the '('.
750 return ParseParenExpr(Res, EndLoc);
751 case AsmToken::LBrac:
752 if (!PlatformParser->HasBracketExpressions())
753 return TokError("brackets expression not supported on this target");
754 Lex(); // Eat the '['.
755 return ParseBracketExpr(Res, EndLoc);
756 case AsmToken::Minus:
757 Lex(); // Eat the operator.
758 if (ParsePrimaryExpr(Res, EndLoc))
760 Res = MCUnaryExpr::CreateMinus(Res, getContext());
763 Lex(); // Eat the operator.
764 if (ParsePrimaryExpr(Res, EndLoc))
766 Res = MCUnaryExpr::CreatePlus(Res, getContext());
768 case AsmToken::Tilde:
769 Lex(); // Eat the operator.
770 if (ParsePrimaryExpr(Res, EndLoc))
772 Res = MCUnaryExpr::CreateNot(Res, getContext());
777 bool AsmParser::ParseExpression(const MCExpr *&Res) {
779 return ParseExpression(Res, EndLoc);
783 AsmParser::ApplyModifierToExpr(const MCExpr *E,
784 MCSymbolRefExpr::VariantKind Variant) {
785 // Recurse over the given expression, rebuilding it to apply the given variant
786 // if there is exactly one symbol.
787 switch (E->getKind()) {
789 case MCExpr::Constant:
792 case MCExpr::SymbolRef: {
793 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
795 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
796 TokError("invalid variant on expression '" +
797 getTok().getIdentifier() + "' (already modified)");
801 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
804 case MCExpr::Unary: {
805 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
806 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
809 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
812 case MCExpr::Binary: {
813 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
814 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
815 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
820 if (!LHS) LHS = BE->getLHS();
821 if (!RHS) RHS = BE->getRHS();
823 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
827 llvm_unreachable("Invalid expression kind!");
830 /// ParseExpression - Parse an expression and return it.
832 /// expr ::= expr &&,|| expr -> lowest.
833 /// expr ::= expr |,^,&,! expr
834 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
835 /// expr ::= expr <<,>> expr
836 /// expr ::= expr +,- expr
837 /// expr ::= expr *,/,% expr -> highest.
838 /// expr ::= primaryexpr
840 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
841 // Parse the expression.
843 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
846 // As a special case, we support 'a op b @ modifier' by rewriting the
847 // expression to include the modifier. This is inefficient, but in general we
848 // expect users to use 'a@modifier op b'.
849 if (Lexer.getKind() == AsmToken::At) {
852 if (Lexer.isNot(AsmToken::Identifier))
853 return TokError("unexpected symbol modifier following '@'");
855 MCSymbolRefExpr::VariantKind Variant =
856 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
857 if (Variant == MCSymbolRefExpr::VK_Invalid)
858 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
860 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
862 return TokError("invalid modifier '" + getTok().getIdentifier() +
863 "' (no symbols present)");
870 // Try to constant fold it up front, if possible.
872 if (Res->EvaluateAsAbsolute(Value))
873 Res = MCConstantExpr::Create(Value, getContext());
878 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
880 return ParseParenExpr(Res, EndLoc) ||
881 ParseBinOpRHS(1, Res, EndLoc);
884 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
887 SMLoc StartLoc = Lexer.getLoc();
888 if (ParseExpression(Expr))
891 if (!Expr->EvaluateAsAbsolute(Res))
892 return Error(StartLoc, "expected absolute expression");
897 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
898 MCBinaryExpr::Opcode &Kind) {
901 return 0; // not a binop.
903 // Lowest Precedence: &&, ||
904 case AsmToken::AmpAmp:
905 Kind = MCBinaryExpr::LAnd;
907 case AsmToken::PipePipe:
908 Kind = MCBinaryExpr::LOr;
912 // Low Precedence: |, &, ^
914 // FIXME: gas seems to support '!' as an infix operator?
916 Kind = MCBinaryExpr::Or;
918 case AsmToken::Caret:
919 Kind = MCBinaryExpr::Xor;
922 Kind = MCBinaryExpr::And;
925 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
926 case AsmToken::EqualEqual:
927 Kind = MCBinaryExpr::EQ;
929 case AsmToken::ExclaimEqual:
930 case AsmToken::LessGreater:
931 Kind = MCBinaryExpr::NE;
934 Kind = MCBinaryExpr::LT;
936 case AsmToken::LessEqual:
937 Kind = MCBinaryExpr::LTE;
939 case AsmToken::Greater:
940 Kind = MCBinaryExpr::GT;
942 case AsmToken::GreaterEqual:
943 Kind = MCBinaryExpr::GTE;
946 // Intermediate Precedence: <<, >>
947 case AsmToken::LessLess:
948 Kind = MCBinaryExpr::Shl;
950 case AsmToken::GreaterGreater:
951 Kind = MCBinaryExpr::Shr;
954 // High Intermediate Precedence: +, -
956 Kind = MCBinaryExpr::Add;
958 case AsmToken::Minus:
959 Kind = MCBinaryExpr::Sub;
962 // Highest Precedence: *, /, %
964 Kind = MCBinaryExpr::Mul;
966 case AsmToken::Slash:
967 Kind = MCBinaryExpr::Div;
969 case AsmToken::Percent:
970 Kind = MCBinaryExpr::Mod;
976 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
977 /// Res contains the LHS of the expression on input.
978 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
981 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
982 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
984 // If the next token is lower precedence than we are allowed to eat, return
985 // successfully with what we ate already.
986 if (TokPrec < Precedence)
991 // Eat the next primary expression.
993 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
995 // If BinOp binds less tightly with RHS than the operator after RHS, let
996 // the pending operator take RHS as its LHS.
997 MCBinaryExpr::Opcode Dummy;
998 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
999 if (TokPrec < NextTokPrec) {
1000 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1003 // Merge LHS and RHS according to operator.
1004 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1012 /// ::= EndOfStatement
1013 /// ::= Label* Directive ...Operands... EndOfStatement
1014 /// ::= Label* Identifier OperandList* EndOfStatement
1015 bool AsmParser::ParseStatement() {
1016 if (Lexer.is(AsmToken::EndOfStatement)) {
1022 // Statements always start with an identifier or are a full line comment.
1023 AsmToken ID = getTok();
1024 SMLoc IDLoc = ID.getLoc();
1026 int64_t LocalLabelVal = -1;
1027 // A full line comment is a '#' as the first token.
1028 if (Lexer.is(AsmToken::Hash))
1029 return ParseCppHashLineFilenameComment(IDLoc);
1031 // Allow an integer followed by a ':' as a directional local label.
1032 if (Lexer.is(AsmToken::Integer)) {
1033 LocalLabelVal = getTok().getIntVal();
1034 if (LocalLabelVal < 0) {
1035 if (!TheCondState.Ignore)
1036 return TokError("unexpected token at start of statement");
1040 IDVal = getTok().getString();
1041 Lex(); // Consume the integer token to be used as an identifier token.
1042 if (Lexer.getKind() != AsmToken::Colon) {
1043 if (!TheCondState.Ignore)
1044 return TokError("unexpected token at start of statement");
1048 } else if (Lexer.is(AsmToken::Dot)) {
1049 // Treat '.' as a valid identifier in this context.
1053 } else if (ParseIdentifier(IDVal)) {
1054 if (!TheCondState.Ignore)
1055 return TokError("unexpected token at start of statement");
1060 // Handle conditional assembly here before checking for skipping. We
1061 // have to do this so that .endif isn't skipped in a ".if 0" block for
1064 return ParseDirectiveIf(IDLoc);
1065 if (IDVal == ".ifb")
1066 return ParseDirectiveIfb(IDLoc, true);
1067 if (IDVal == ".ifnb")
1068 return ParseDirectiveIfb(IDLoc, false);
1069 if (IDVal == ".ifc")
1070 return ParseDirectiveIfc(IDLoc, true);
1071 if (IDVal == ".ifnc")
1072 return ParseDirectiveIfc(IDLoc, false);
1073 if (IDVal == ".ifdef")
1074 return ParseDirectiveIfdef(IDLoc, true);
1075 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1076 return ParseDirectiveIfdef(IDLoc, false);
1077 if (IDVal == ".elseif")
1078 return ParseDirectiveElseIf(IDLoc);
1079 if (IDVal == ".else")
1080 return ParseDirectiveElse(IDLoc);
1081 if (IDVal == ".endif")
1082 return ParseDirectiveEndIf(IDLoc);
1084 // If we are in a ".if 0" block, ignore this statement.
1085 if (TheCondState.Ignore) {
1086 EatToEndOfStatement();
1090 // FIXME: Recurse on local labels?
1092 // See what kind of statement we have.
1093 switch (Lexer.getKind()) {
1094 case AsmToken::Colon: {
1095 CheckForValidSection();
1097 // identifier ':' -> Label.
1100 // Diagnose attempt to use '.' as a label.
1102 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1104 // Diagnose attempt to use a variable as a label.
1106 // FIXME: Diagnostics. Note the location of the definition as a label.
1107 // FIXME: This doesn't diagnose assignment to a symbol which has been
1108 // implicitly marked as external.
1110 if (LocalLabelVal == -1)
1111 Sym = getContext().GetOrCreateSymbol(IDVal);
1113 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1114 if (!Sym->isUndefined() || Sym->isVariable())
1115 return Error(IDLoc, "invalid symbol redefinition");
1120 // If we are generating dwarf for assembly source files then gather the
1121 // info to make a dwarf label entry for this label if needed.
1122 if (getContext().getGenDwarfForAssembly())
1123 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1126 // Consume any end of statement token, if present, to avoid spurious
1127 // AddBlankLine calls().
1128 if (Lexer.is(AsmToken::EndOfStatement)) {
1130 if (Lexer.is(AsmToken::Eof))
1134 return ParseStatement();
1137 case AsmToken::Equal:
1138 // identifier '=' ... -> assignment statement
1141 return ParseAssignment(IDVal, true);
1143 default: // Normal instruction or directive.
1147 // If macros are enabled, check to see if this is a macro instantiation.
1149 if (const Macro *M = MacroMap.lookup(IDVal))
1150 return HandleMacroEntry(IDVal, IDLoc, M);
1152 // Otherwise, we have a normal instruction or directive.
1153 if (IDVal[0] == '.' && IDVal != ".") {
1154 // Assembler features
1155 if (IDVal == ".set" || IDVal == ".equ")
1156 return ParseDirectiveSet(IDVal, true);
1157 if (IDVal == ".equiv")
1158 return ParseDirectiveSet(IDVal, false);
1162 if (IDVal == ".ascii")
1163 return ParseDirectiveAscii(IDVal, false);
1164 if (IDVal == ".asciz" || IDVal == ".string")
1165 return ParseDirectiveAscii(IDVal, true);
1167 if (IDVal == ".byte")
1168 return ParseDirectiveValue(1);
1169 if (IDVal == ".short")
1170 return ParseDirectiveValue(2);
1171 if (IDVal == ".value")
1172 return ParseDirectiveValue(2);
1173 if (IDVal == ".2byte")
1174 return ParseDirectiveValue(2);
1175 if (IDVal == ".long")
1176 return ParseDirectiveValue(4);
1177 if (IDVal == ".int")
1178 return ParseDirectiveValue(4);
1179 if (IDVal == ".4byte")
1180 return ParseDirectiveValue(4);
1181 if (IDVal == ".quad")
1182 return ParseDirectiveValue(8);
1183 if (IDVal == ".8byte")
1184 return ParseDirectiveValue(8);
1185 if (IDVal == ".single" || IDVal == ".float")
1186 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1187 if (IDVal == ".double")
1188 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1190 if (IDVal == ".align") {
1191 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1192 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1194 if (IDVal == ".align32") {
1195 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1196 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1198 if (IDVal == ".balign")
1199 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1200 if (IDVal == ".balignw")
1201 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1202 if (IDVal == ".balignl")
1203 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1204 if (IDVal == ".p2align")
1205 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1206 if (IDVal == ".p2alignw")
1207 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1208 if (IDVal == ".p2alignl")
1209 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1211 if (IDVal == ".org")
1212 return ParseDirectiveOrg();
1214 if (IDVal == ".fill")
1215 return ParseDirectiveFill();
1216 if (IDVal == ".space" || IDVal == ".skip")
1217 return ParseDirectiveSpace();
1218 if (IDVal == ".zero")
1219 return ParseDirectiveZero();
1221 // Symbol attribute directives
1223 if (IDVal == ".extern") {
1224 EatToEndOfStatement(); // .extern is the default, ignore it.
1227 if (IDVal == ".globl" || IDVal == ".global")
1228 return ParseDirectiveSymbolAttribute(MCSA_Global);
1229 if (IDVal == ".indirect_symbol")
1230 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1231 if (IDVal == ".lazy_reference")
1232 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1233 if (IDVal == ".no_dead_strip")
1234 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1235 if (IDVal == ".symbol_resolver")
1236 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1237 if (IDVal == ".private_extern")
1238 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1239 if (IDVal == ".reference")
1240 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1241 if (IDVal == ".weak_definition")
1242 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1243 if (IDVal == ".weak_reference")
1244 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1245 if (IDVal == ".weak_def_can_be_hidden")
1246 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1248 if (IDVal == ".comm" || IDVal == ".common")
1249 return ParseDirectiveComm(/*IsLocal=*/false);
1250 if (IDVal == ".lcomm")
1251 return ParseDirectiveComm(/*IsLocal=*/true);
1253 if (IDVal == ".abort")
1254 return ParseDirectiveAbort();
1255 if (IDVal == ".include")
1256 return ParseDirectiveInclude();
1257 if (IDVal == ".incbin")
1258 return ParseDirectiveIncbin();
1260 if (IDVal == ".code16")
1261 return TokError(Twine(IDVal) + " not supported yet");
1263 // Look up the handler in the handler table.
1264 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1265 DirectiveMap.lookup(IDVal);
1267 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1269 // Target hook for parsing target specific directives.
1270 if (!getTargetParser().ParseDirective(ID))
1273 return Error(IDLoc, "unknown directive");
1276 CheckForValidSection();
1278 // Canonicalize the opcode to lower case.
1279 SmallString<128> Opcode;
1280 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1281 Opcode.push_back(tolower(IDVal[i]));
1283 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1284 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1287 // Dump the parsed representation, if requested.
1288 if (getShowParsedOperands()) {
1289 SmallString<256> Str;
1290 raw_svector_ostream OS(Str);
1291 OS << "parsed instruction: [";
1292 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1295 ParsedOperands[i]->print(OS);
1299 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1302 // If we are generating dwarf for assembly source files and the current
1303 // section is the initial text section then generate a .loc directive for
1305 if (!HadError && getContext().getGenDwarfForAssembly() &&
1306 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1307 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1308 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1309 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1310 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1314 // If parsing succeeded, match the instruction.
1316 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1319 // Free any parsed operands.
1320 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1321 delete ParsedOperands[i];
1323 // Don't skip the rest of the line, the instruction parser is responsible for
1328 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1329 /// since they may not be able to be tokenized to get to the end of line token.
1330 void AsmParser::EatToEndOfLine() {
1331 if (!Lexer.is(AsmToken::EndOfStatement))
1332 Lexer.LexUntilEndOfLine();
1337 /// ParseCppHashLineFilenameComment as this:
1338 /// ::= # number "filename"
1339 /// or just as a full line comment if it doesn't have a number and a string.
1340 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1341 Lex(); // Eat the hash token.
1343 if (getLexer().isNot(AsmToken::Integer)) {
1344 // Consume the line since in cases it is not a well-formed line directive,
1345 // as if were simply a full line comment.
1350 int64_t LineNumber = getTok().getIntVal();
1353 if (getLexer().isNot(AsmToken::String)) {
1358 StringRef Filename = getTok().getString();
1359 // Get rid of the enclosing quotes.
1360 Filename = Filename.substr(1, Filename.size()-2);
1362 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1364 CppHashFilename = Filename;
1365 CppHashLineNumber = LineNumber;
1367 // Ignore any trailing characters, they're just comment.
1372 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1373 /// for the Filename and LineNo if any in the diagnostic.
1374 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1375 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1376 raw_ostream &OS = errs();
1378 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1379 const SMLoc &DiagLoc = Diag.getLoc();
1380 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1381 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1383 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1384 // before printing the message.
1385 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1386 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1387 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1388 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1391 // If we have not parsed a cpp hash line filename comment or the source
1392 // manager changed or buffer changed (like in a nested include) then just
1393 // print the normal diagnostic using its Filename and LineNo.
1394 if (!Parser->CppHashLineNumber ||
1395 &DiagSrcMgr != &Parser->SrcMgr ||
1396 DiagBuf != CppHashBuf) {
1397 if (Parser->SavedDiagHandler)
1398 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1404 // Use the CppHashFilename and calculate a line number based on the
1405 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1407 const std::string Filename = Parser->CppHashFilename;
1409 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1410 int CppHashLocLineNo =
1411 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1412 int LineNo = Parser->CppHashLineNumber - 1 +
1413 (DiagLocLineNo - CppHashLocLineNo);
1415 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1416 Filename, LineNo, Diag.getColumnNo(),
1417 Diag.getKind(), Diag.getMessage(),
1418 Diag.getLineContents(), Diag.getRanges());
1420 if (Parser->SavedDiagHandler)
1421 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1423 NewDiag.print(0, OS);
1426 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1427 const std::vector<StringRef> &Parameters,
1428 const std::vector<std::vector<AsmToken> > &A,
1430 raw_svector_ostream OS(Buf);
1431 unsigned NParameters = Parameters.size();
1432 if (NParameters != 0 && NParameters != A.size())
1433 return Error(L, "Wrong number of arguments");
1435 while (!Body.empty()) {
1436 // Scan for the next substitution.
1437 std::size_t End = Body.size(), Pos = 0;
1438 for (; Pos != End; ++Pos) {
1439 // Check for a substitution or escape.
1441 // This macro has no parameters, look for $0, $1, etc.
1442 if (Body[Pos] != '$' || Pos + 1 == End)
1445 char Next = Body[Pos + 1];
1446 if (Next == '$' || Next == 'n' || isdigit(Next))
1449 // This macro has parameters, look for \foo, \bar, etc.
1450 if (Body[Pos] == '\\' && Pos + 1 != End)
1456 OS << Body.slice(0, Pos);
1458 // Check if we reached the end.
1463 switch (Body[Pos+1]) {
1469 // $n => number of arguments
1474 // $[0-9] => argument
1476 // Missing arguments are ignored.
1477 unsigned Index = Body[Pos+1] - '0';
1478 if (Index >= A.size())
1481 // Otherwise substitute with the token values, with spaces eliminated.
1482 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1483 ie = A[Index].end(); it != ie; ++it)
1484 OS << it->getString();
1490 unsigned I = Pos + 1;
1491 while (isalnum(Body[I]) && I + 1 != End)
1494 const char *Begin = Body.data() + Pos +1;
1495 StringRef Argument(Begin, I - (Pos +1));
1497 for (; Index < NParameters; ++Index)
1498 if (Parameters[Index] == Argument)
1501 // FIXME: We should error at the macro definition.
1502 if (Index == NParameters)
1503 return Error(L, "Parameter not found");
1505 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1506 ie = A[Index].end(); it != ie; ++it)
1507 OS << it->getString();
1509 Pos += 1 + Argument.size();
1511 // Update the scan point.
1512 Body = Body.substr(Pos);
1515 // We include the .endmacro in the buffer as our queue to exit the macro
1517 OS << ".endmacro\n";
1521 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1523 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1527 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1529 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1530 // this, although we should protect against infinite loops.
1531 if (ActiveMacros.size() == 20)
1532 return TokError("macros cannot be nested more than 20 levels deep");
1534 // Parse the macro instantiation arguments.
1535 std::vector<std::vector<AsmToken> > MacroArguments;
1536 MacroArguments.push_back(std::vector<AsmToken>());
1537 unsigned ParenLevel = 0;
1539 if (Lexer.is(AsmToken::Eof))
1540 return TokError("unexpected token in macro instantiation");
1541 if (Lexer.is(AsmToken::EndOfStatement))
1544 // If we aren't inside parentheses and this is a comma, start a new token
1546 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1547 MacroArguments.push_back(std::vector<AsmToken>());
1549 // Adjust the current parentheses level.
1550 if (Lexer.is(AsmToken::LParen))
1552 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1555 // Append the token to the current argument list.
1556 MacroArguments.back().push_back(getTok());
1560 // If the last argument didn't end up with any tokens, it's not a real
1561 // argument and we should remove it from the list. This happens with either
1562 // a tailing comma or an empty argument list.
1563 if (MacroArguments.back().empty())
1564 MacroArguments.pop_back();
1566 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1567 // to hold the macro body with substitutions.
1568 SmallString<256> Buf;
1569 StringRef Body = M->Body;
1571 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1574 MemoryBuffer *Instantiation =
1575 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1577 // Create the macro instantiation object and add to the current macro
1578 // instantiation stack.
1579 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1582 ActiveMacros.push_back(MI);
1584 // Jump to the macro instantiation and prime the lexer.
1585 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1586 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1592 void AsmParser::HandleMacroExit() {
1593 // Jump to the EndOfStatement we should return to, and consume it.
1594 JumpToLoc(ActiveMacros.back()->ExitLoc);
1597 // Pop the instantiation entry.
1598 delete ActiveMacros.back();
1599 ActiveMacros.pop_back();
1602 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1603 switch (Value->getKind()) {
1604 case MCExpr::Binary: {
1605 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1606 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1609 case MCExpr::Target:
1610 case MCExpr::Constant:
1612 case MCExpr::SymbolRef: {
1613 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1615 return IsUsedIn(Sym, S.getVariableValue());
1619 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1622 llvm_unreachable("Unknown expr kind!");
1625 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1626 // FIXME: Use better location, we should use proper tokens.
1627 SMLoc EqualLoc = Lexer.getLoc();
1629 const MCExpr *Value;
1630 if (ParseExpression(Value))
1633 // Note: we don't count b as used in "a = b". This is to allow
1637 if (Lexer.isNot(AsmToken::EndOfStatement))
1638 return TokError("unexpected token in assignment");
1640 // Error on assignment to '.'.
1642 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1643 "(use '.space' or '.org').)"));
1646 // Eat the end of statement marker.
1649 // Validate that the LHS is allowed to be a variable (either it has not been
1650 // used as a symbol, or it is an absolute symbol).
1651 MCSymbol *Sym = getContext().LookupSymbol(Name);
1653 // Diagnose assignment to a label.
1655 // FIXME: Diagnostics. Note the location of the definition as a label.
1656 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1657 if (IsUsedIn(Sym, Value))
1658 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1659 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1660 ; // Allow redefinitions of undefined symbols only used in directives.
1661 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1662 ; // Allow redefinitions of variables that haven't yet been used.
1663 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1664 return Error(EqualLoc, "redefinition of '" + Name + "'");
1665 else if (!Sym->isVariable())
1666 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1667 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1668 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1671 // Don't count these checks as uses.
1672 Sym->setUsed(false);
1674 Sym = getContext().GetOrCreateSymbol(Name);
1676 // FIXME: Handle '.'.
1678 // Do the assignment.
1679 Out.EmitAssignment(Sym, Value);
1684 /// ParseIdentifier:
1687 bool AsmParser::ParseIdentifier(StringRef &Res) {
1688 // The assembler has relaxed rules for accepting identifiers, in particular we
1689 // allow things like '.globl $foo', which would normally be separate
1690 // tokens. At this level, we have already lexed so we cannot (currently)
1691 // handle this as a context dependent token, instead we detect adjacent tokens
1692 // and return the combined identifier.
1693 if (Lexer.is(AsmToken::Dollar)) {
1694 SMLoc DollarLoc = getLexer().getLoc();
1696 // Consume the dollar sign, and check for a following identifier.
1698 if (Lexer.isNot(AsmToken::Identifier))
1701 // We have a '$' followed by an identifier, make sure they are adjacent.
1702 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1705 // Construct the joined identifier and consume the token.
1706 Res = StringRef(DollarLoc.getPointer(),
1707 getTok().getIdentifier().size() + 1);
1712 if (Lexer.isNot(AsmToken::Identifier) &&
1713 Lexer.isNot(AsmToken::String))
1716 Res = getTok().getIdentifier();
1718 Lex(); // Consume the identifier token.
1723 /// ParseDirectiveSet:
1724 /// ::= .equ identifier ',' expression
1725 /// ::= .equiv identifier ',' expression
1726 /// ::= .set identifier ',' expression
1727 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1730 if (ParseIdentifier(Name))
1731 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1733 if (getLexer().isNot(AsmToken::Comma))
1734 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1737 return ParseAssignment(Name, allow_redef);
1740 bool AsmParser::ParseEscapedString(std::string &Data) {
1741 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1744 StringRef Str = getTok().getStringContents();
1745 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1746 if (Str[i] != '\\') {
1751 // Recognize escaped characters. Note that this escape semantics currently
1752 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1755 return TokError("unexpected backslash at end of string");
1757 // Recognize octal sequences.
1758 if ((unsigned) (Str[i] - '0') <= 7) {
1759 // Consume up to three octal characters.
1760 unsigned Value = Str[i] - '0';
1762 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1764 Value = Value * 8 + (Str[i] - '0');
1766 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1768 Value = Value * 8 + (Str[i] - '0');
1773 return TokError("invalid octal escape sequence (out of range)");
1775 Data += (unsigned char) Value;
1779 // Otherwise recognize individual escapes.
1782 // Just reject invalid escape sequences for now.
1783 return TokError("invalid escape sequence (unrecognized character)");
1785 case 'b': Data += '\b'; break;
1786 case 'f': Data += '\f'; break;
1787 case 'n': Data += '\n'; break;
1788 case 'r': Data += '\r'; break;
1789 case 't': Data += '\t'; break;
1790 case '"': Data += '"'; break;
1791 case '\\': Data += '\\'; break;
1798 /// ParseDirectiveAscii:
1799 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1800 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1801 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1802 CheckForValidSection();
1805 if (getLexer().isNot(AsmToken::String))
1806 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1809 if (ParseEscapedString(Data))
1812 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1814 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1818 if (getLexer().is(AsmToken::EndOfStatement))
1821 if (getLexer().isNot(AsmToken::Comma))
1822 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1831 /// ParseDirectiveValue
1832 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1833 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1834 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1835 CheckForValidSection();
1838 const MCExpr *Value;
1839 SMLoc ExprLoc = getLexer().getLoc();
1840 if (ParseExpression(Value))
1843 // Special case constant expressions to match code generator.
1844 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1845 assert(Size <= 8 && "Invalid size");
1846 uint64_t IntValue = MCE->getValue();
1847 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1848 return Error(ExprLoc, "literal value out of range for directive");
1849 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1851 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1853 if (getLexer().is(AsmToken::EndOfStatement))
1856 // FIXME: Improve diagnostic.
1857 if (getLexer().isNot(AsmToken::Comma))
1858 return TokError("unexpected token in directive");
1867 /// ParseDirectiveRealValue
1868 /// ::= (.single | .double) [ expression (, expression)* ]
1869 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1870 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1871 CheckForValidSection();
1874 // We don't truly support arithmetic on floating point expressions, so we
1875 // have to manually parse unary prefixes.
1877 if (getLexer().is(AsmToken::Minus)) {
1880 } else if (getLexer().is(AsmToken::Plus))
1883 if (getLexer().isNot(AsmToken::Integer) &&
1884 getLexer().isNot(AsmToken::Real) &&
1885 getLexer().isNot(AsmToken::Identifier))
1886 return TokError("unexpected token in directive");
1888 // Convert to an APFloat.
1889 APFloat Value(Semantics);
1890 StringRef IDVal = getTok().getString();
1891 if (getLexer().is(AsmToken::Identifier)) {
1892 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1893 Value = APFloat::getInf(Semantics);
1894 else if (!IDVal.compare_lower("nan"))
1895 Value = APFloat::getNaN(Semantics, false, ~0);
1897 return TokError("invalid floating point literal");
1898 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1899 APFloat::opInvalidOp)
1900 return TokError("invalid floating point literal");
1904 // Consume the numeric token.
1907 // Emit the value as an integer.
1908 APInt AsInt = Value.bitcastToAPInt();
1909 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1910 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1912 if (getLexer().is(AsmToken::EndOfStatement))
1915 if (getLexer().isNot(AsmToken::Comma))
1916 return TokError("unexpected token in directive");
1925 /// ParseDirectiveSpace
1926 /// ::= .space expression [ , expression ]
1927 bool AsmParser::ParseDirectiveSpace() {
1928 CheckForValidSection();
1931 if (ParseAbsoluteExpression(NumBytes))
1934 int64_t FillExpr = 0;
1935 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1936 if (getLexer().isNot(AsmToken::Comma))
1937 return TokError("unexpected token in '.space' directive");
1940 if (ParseAbsoluteExpression(FillExpr))
1943 if (getLexer().isNot(AsmToken::EndOfStatement))
1944 return TokError("unexpected token in '.space' directive");
1950 return TokError("invalid number of bytes in '.space' directive");
1952 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1953 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1958 /// ParseDirectiveZero
1959 /// ::= .zero expression
1960 bool AsmParser::ParseDirectiveZero() {
1961 CheckForValidSection();
1964 if (ParseAbsoluteExpression(NumBytes))
1968 if (getLexer().is(AsmToken::Comma)) {
1970 if (ParseAbsoluteExpression(Val))
1974 if (getLexer().isNot(AsmToken::EndOfStatement))
1975 return TokError("unexpected token in '.zero' directive");
1979 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1984 /// ParseDirectiveFill
1985 /// ::= .fill expression , expression , expression
1986 bool AsmParser::ParseDirectiveFill() {
1987 CheckForValidSection();
1990 if (ParseAbsoluteExpression(NumValues))
1993 if (getLexer().isNot(AsmToken::Comma))
1994 return TokError("unexpected token in '.fill' directive");
1998 if (ParseAbsoluteExpression(FillSize))
2001 if (getLexer().isNot(AsmToken::Comma))
2002 return TokError("unexpected token in '.fill' directive");
2006 if (ParseAbsoluteExpression(FillExpr))
2009 if (getLexer().isNot(AsmToken::EndOfStatement))
2010 return TokError("unexpected token in '.fill' directive");
2014 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2015 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2017 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2018 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2023 /// ParseDirectiveOrg
2024 /// ::= .org expression [ , expression ]
2025 bool AsmParser::ParseDirectiveOrg() {
2026 CheckForValidSection();
2028 const MCExpr *Offset;
2029 SMLoc Loc = getTok().getLoc();
2030 if (ParseExpression(Offset))
2033 // Parse optional fill expression.
2034 int64_t FillExpr = 0;
2035 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2036 if (getLexer().isNot(AsmToken::Comma))
2037 return TokError("unexpected token in '.org' directive");
2040 if (ParseAbsoluteExpression(FillExpr))
2043 if (getLexer().isNot(AsmToken::EndOfStatement))
2044 return TokError("unexpected token in '.org' directive");
2049 // Only limited forms of relocatable expressions are accepted here, it
2050 // has to be relative to the current section. The streamer will return
2051 // 'true' if the expression wasn't evaluatable.
2052 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2053 return Error(Loc, "expected assembly-time absolute expression");
2058 /// ParseDirectiveAlign
2059 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2060 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2061 CheckForValidSection();
2063 SMLoc AlignmentLoc = getLexer().getLoc();
2065 if (ParseAbsoluteExpression(Alignment))
2069 bool HasFillExpr = false;
2070 int64_t FillExpr = 0;
2071 int64_t MaxBytesToFill = 0;
2072 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2073 if (getLexer().isNot(AsmToken::Comma))
2074 return TokError("unexpected token in directive");
2077 // The fill expression can be omitted while specifying a maximum number of
2078 // alignment bytes, e.g:
2080 if (getLexer().isNot(AsmToken::Comma)) {
2082 if (ParseAbsoluteExpression(FillExpr))
2086 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2087 if (getLexer().isNot(AsmToken::Comma))
2088 return TokError("unexpected token in directive");
2091 MaxBytesLoc = getLexer().getLoc();
2092 if (ParseAbsoluteExpression(MaxBytesToFill))
2095 if (getLexer().isNot(AsmToken::EndOfStatement))
2096 return TokError("unexpected token in directive");
2105 // Compute alignment in bytes.
2107 // FIXME: Diagnose overflow.
2108 if (Alignment >= 32) {
2109 Error(AlignmentLoc, "invalid alignment value");
2113 Alignment = 1ULL << Alignment;
2116 // Diagnose non-sensical max bytes to align.
2117 if (MaxBytesLoc.isValid()) {
2118 if (MaxBytesToFill < 1) {
2119 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2120 "many bytes, ignoring maximum bytes expression");
2124 if (MaxBytesToFill >= Alignment) {
2125 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2131 // Check whether we should use optimal code alignment for this .align
2133 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2134 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2135 ValueSize == 1 && UseCodeAlign) {
2136 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2138 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2139 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2146 /// ParseDirectiveSymbolAttribute
2147 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2148 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2149 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2152 SMLoc Loc = getTok().getLoc();
2154 if (ParseIdentifier(Name))
2155 return Error(Loc, "expected identifier in directive");
2157 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2159 // Assembler local symbols don't make any sense here. Complain loudly.
2160 if (Sym->isTemporary())
2161 return Error(Loc, "non-local symbol required in directive");
2163 getStreamer().EmitSymbolAttribute(Sym, Attr);
2165 if (getLexer().is(AsmToken::EndOfStatement))
2168 if (getLexer().isNot(AsmToken::Comma))
2169 return TokError("unexpected token in directive");
2178 /// ParseDirectiveComm
2179 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2180 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2181 CheckForValidSection();
2183 SMLoc IDLoc = getLexer().getLoc();
2185 if (ParseIdentifier(Name))
2186 return TokError("expected identifier in directive");
2188 // Handle the identifier as the key symbol.
2189 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2191 if (getLexer().isNot(AsmToken::Comma))
2192 return TokError("unexpected token in directive");
2196 SMLoc SizeLoc = getLexer().getLoc();
2197 if (ParseAbsoluteExpression(Size))
2200 int64_t Pow2Alignment = 0;
2201 SMLoc Pow2AlignmentLoc;
2202 if (getLexer().is(AsmToken::Comma)) {
2204 Pow2AlignmentLoc = getLexer().getLoc();
2205 if (ParseAbsoluteExpression(Pow2Alignment))
2208 // If this target takes alignments in bytes (not log) validate and convert.
2209 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2210 if (!isPowerOf2_64(Pow2Alignment))
2211 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2212 Pow2Alignment = Log2_64(Pow2Alignment);
2216 if (getLexer().isNot(AsmToken::EndOfStatement))
2217 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2221 // NOTE: a size of zero for a .comm should create a undefined symbol
2222 // but a size of .lcomm creates a bss symbol of size zero.
2224 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2225 "be less than zero");
2227 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2228 // may internally end up wanting an alignment in bytes.
2229 // FIXME: Diagnose overflow.
2230 if (Pow2Alignment < 0)
2231 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2232 "alignment, can't be less than zero");
2234 if (!Sym->isUndefined())
2235 return Error(IDLoc, "invalid symbol redefinition");
2237 // '.lcomm' is equivalent to '.zerofill'.
2238 // Create the Symbol as a common or local common with Size and Pow2Alignment
2240 getStreamer().EmitZerofill(Ctx.getMachOSection(
2241 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2242 0, SectionKind::getBSS()),
2243 Sym, Size, 1 << Pow2Alignment);
2247 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2251 /// ParseDirectiveAbort
2252 /// ::= .abort [... message ...]
2253 bool AsmParser::ParseDirectiveAbort() {
2254 // FIXME: Use loc from directive.
2255 SMLoc Loc = getLexer().getLoc();
2257 StringRef Str = ParseStringToEndOfStatement();
2258 if (getLexer().isNot(AsmToken::EndOfStatement))
2259 return TokError("unexpected token in '.abort' directive");
2264 Error(Loc, ".abort detected. Assembly stopping.");
2266 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2267 // FIXME: Actually abort assembly here.
2272 /// ParseDirectiveInclude
2273 /// ::= .include "filename"
2274 bool AsmParser::ParseDirectiveInclude() {
2275 if (getLexer().isNot(AsmToken::String))
2276 return TokError("expected string in '.include' directive");
2278 std::string Filename = getTok().getString();
2279 SMLoc IncludeLoc = getLexer().getLoc();
2282 if (getLexer().isNot(AsmToken::EndOfStatement))
2283 return TokError("unexpected token in '.include' directive");
2285 // Strip the quotes.
2286 Filename = Filename.substr(1, Filename.size()-2);
2288 // Attempt to switch the lexer to the included file before consuming the end
2289 // of statement to avoid losing it when we switch.
2290 if (EnterIncludeFile(Filename)) {
2291 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2298 /// ParseDirectiveIncbin
2299 /// ::= .incbin "filename"
2300 bool AsmParser::ParseDirectiveIncbin() {
2301 if (getLexer().isNot(AsmToken::String))
2302 return TokError("expected string in '.incbin' directive");
2304 std::string Filename = getTok().getString();
2305 SMLoc IncbinLoc = getLexer().getLoc();
2308 if (getLexer().isNot(AsmToken::EndOfStatement))
2309 return TokError("unexpected token in '.incbin' directive");
2311 // Strip the quotes.
2312 Filename = Filename.substr(1, Filename.size()-2);
2314 // Attempt to process the included file.
2315 if (ProcessIncbinFile(Filename)) {
2316 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2323 /// ParseDirectiveIf
2324 /// ::= .if expression
2325 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2326 TheCondStack.push_back(TheCondState);
2327 TheCondState.TheCond = AsmCond::IfCond;
2328 if(TheCondState.Ignore) {
2329 EatToEndOfStatement();
2333 if (ParseAbsoluteExpression(ExprValue))
2336 if (getLexer().isNot(AsmToken::EndOfStatement))
2337 return TokError("unexpected token in '.if' directive");
2341 TheCondState.CondMet = ExprValue;
2342 TheCondState.Ignore = !TheCondState.CondMet;
2348 /// ParseDirectiveIfb
2350 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2351 TheCondStack.push_back(TheCondState);
2352 TheCondState.TheCond = AsmCond::IfCond;
2354 if(TheCondState.Ignore) {
2355 EatToEndOfStatement();
2357 StringRef Str = ParseStringToEndOfStatement();
2359 if (getLexer().isNot(AsmToken::EndOfStatement))
2360 return TokError("unexpected token in '.ifb' directive");
2364 TheCondState.CondMet = ExpectBlank == Str.empty();
2365 TheCondState.Ignore = !TheCondState.CondMet;
2371 /// ParseDirectiveIfc
2372 /// ::= .ifc string1, string2
2373 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2374 TheCondStack.push_back(TheCondState);
2375 TheCondState.TheCond = AsmCond::IfCond;
2377 if(TheCondState.Ignore) {
2378 EatToEndOfStatement();
2380 StringRef Str1 = ParseStringToComma();
2382 if (getLexer().isNot(AsmToken::Comma))
2383 return TokError("unexpected token in '.ifc' directive");
2387 StringRef Str2 = ParseStringToEndOfStatement();
2389 if (getLexer().isNot(AsmToken::EndOfStatement))
2390 return TokError("unexpected token in '.ifc' directive");
2394 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2395 TheCondState.Ignore = !TheCondState.CondMet;
2401 /// ParseDirectiveIfdef
2402 /// ::= .ifdef symbol
2403 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2405 TheCondStack.push_back(TheCondState);
2406 TheCondState.TheCond = AsmCond::IfCond;
2408 if (TheCondState.Ignore) {
2409 EatToEndOfStatement();
2411 if (ParseIdentifier(Name))
2412 return TokError("expected identifier after '.ifdef'");
2416 MCSymbol *Sym = getContext().LookupSymbol(Name);
2419 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2421 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2422 TheCondState.Ignore = !TheCondState.CondMet;
2428 /// ParseDirectiveElseIf
2429 /// ::= .elseif expression
2430 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2431 if (TheCondState.TheCond != AsmCond::IfCond &&
2432 TheCondState.TheCond != AsmCond::ElseIfCond)
2433 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2435 TheCondState.TheCond = AsmCond::ElseIfCond;
2437 bool LastIgnoreState = false;
2438 if (!TheCondStack.empty())
2439 LastIgnoreState = TheCondStack.back().Ignore;
2440 if (LastIgnoreState || TheCondState.CondMet) {
2441 TheCondState.Ignore = true;
2442 EatToEndOfStatement();
2446 if (ParseAbsoluteExpression(ExprValue))
2449 if (getLexer().isNot(AsmToken::EndOfStatement))
2450 return TokError("unexpected token in '.elseif' directive");
2453 TheCondState.CondMet = ExprValue;
2454 TheCondState.Ignore = !TheCondState.CondMet;
2460 /// ParseDirectiveElse
2462 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2463 if (getLexer().isNot(AsmToken::EndOfStatement))
2464 return TokError("unexpected token in '.else' directive");
2468 if (TheCondState.TheCond != AsmCond::IfCond &&
2469 TheCondState.TheCond != AsmCond::ElseIfCond)
2470 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2472 TheCondState.TheCond = AsmCond::ElseCond;
2473 bool LastIgnoreState = false;
2474 if (!TheCondStack.empty())
2475 LastIgnoreState = TheCondStack.back().Ignore;
2476 if (LastIgnoreState || TheCondState.CondMet)
2477 TheCondState.Ignore = true;
2479 TheCondState.Ignore = false;
2484 /// ParseDirectiveEndIf
2486 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2487 if (getLexer().isNot(AsmToken::EndOfStatement))
2488 return TokError("unexpected token in '.endif' directive");
2492 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2493 TheCondStack.empty())
2494 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2496 if (!TheCondStack.empty()) {
2497 TheCondState = TheCondStack.back();
2498 TheCondStack.pop_back();
2504 /// ParseDirectiveFile
2505 /// ::= .file [number] filename
2506 /// ::= .file number directory filename
2507 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2508 // FIXME: I'm not sure what this is.
2509 int64_t FileNumber = -1;
2510 SMLoc FileNumberLoc = getLexer().getLoc();
2511 if (getLexer().is(AsmToken::Integer)) {
2512 FileNumber = getTok().getIntVal();
2516 return TokError("file number less than one");
2519 if (getLexer().isNot(AsmToken::String))
2520 return TokError("unexpected token in '.file' directive");
2522 // Usually the directory and filename together, otherwise just the directory.
2523 StringRef Path = getTok().getString();
2524 Path = Path.substr(1, Path.size()-2);
2527 StringRef Directory;
2529 if (getLexer().is(AsmToken::String)) {
2530 if (FileNumber == -1)
2531 return TokError("explicit path specified, but no file number");
2532 Filename = getTok().getString();
2533 Filename = Filename.substr(1, Filename.size()-2);
2540 if (getLexer().isNot(AsmToken::EndOfStatement))
2541 return TokError("unexpected token in '.file' directive");
2543 if (FileNumber == -1)
2544 getStreamer().EmitFileDirective(Filename);
2546 if (getContext().getGenDwarfForAssembly() == true)
2547 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2548 "used to generate dwarf debug info for assembly code");
2550 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2551 Error(FileNumberLoc, "file number already allocated");
2557 /// ParseDirectiveLine
2558 /// ::= .line [number]
2559 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2560 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2561 if (getLexer().isNot(AsmToken::Integer))
2562 return TokError("unexpected token in '.line' directive");
2564 int64_t LineNumber = getTok().getIntVal();
2568 // FIXME: Do something with the .line.
2571 if (getLexer().isNot(AsmToken::EndOfStatement))
2572 return TokError("unexpected token in '.line' directive");
2578 /// ParseDirectiveLoc
2579 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2580 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2581 /// The first number is a file number, must have been previously assigned with
2582 /// a .file directive, the second number is the line number and optionally the
2583 /// third number is a column position (zero if not specified). The remaining
2584 /// optional items are .loc sub-directives.
2585 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2587 if (getLexer().isNot(AsmToken::Integer))
2588 return TokError("unexpected token in '.loc' directive");
2589 int64_t FileNumber = getTok().getIntVal();
2591 return TokError("file number less than one in '.loc' directive");
2592 if (!getContext().isValidDwarfFileNumber(FileNumber))
2593 return TokError("unassigned file number in '.loc' directive");
2596 int64_t LineNumber = 0;
2597 if (getLexer().is(AsmToken::Integer)) {
2598 LineNumber = getTok().getIntVal();
2600 return TokError("line number less than one in '.loc' directive");
2604 int64_t ColumnPos = 0;
2605 if (getLexer().is(AsmToken::Integer)) {
2606 ColumnPos = getTok().getIntVal();
2608 return TokError("column position less than zero in '.loc' directive");
2612 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2614 int64_t Discriminator = 0;
2615 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2617 if (getLexer().is(AsmToken::EndOfStatement))
2621 SMLoc Loc = getTok().getLoc();
2622 if (getParser().ParseIdentifier(Name))
2623 return TokError("unexpected token in '.loc' directive");
2625 if (Name == "basic_block")
2626 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2627 else if (Name == "prologue_end")
2628 Flags |= DWARF2_FLAG_PROLOGUE_END;
2629 else if (Name == "epilogue_begin")
2630 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2631 else if (Name == "is_stmt") {
2632 SMLoc Loc = getTok().getLoc();
2633 const MCExpr *Value;
2634 if (getParser().ParseExpression(Value))
2636 // The expression must be the constant 0 or 1.
2637 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2638 int Value = MCE->getValue();
2640 Flags &= ~DWARF2_FLAG_IS_STMT;
2641 else if (Value == 1)
2642 Flags |= DWARF2_FLAG_IS_STMT;
2644 return Error(Loc, "is_stmt value not 0 or 1");
2647 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2650 else if (Name == "isa") {
2651 SMLoc Loc = getTok().getLoc();
2652 const MCExpr *Value;
2653 if (getParser().ParseExpression(Value))
2655 // The expression must be a constant greater or equal to 0.
2656 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2657 int Value = MCE->getValue();
2659 return Error(Loc, "isa number less than zero");
2663 return Error(Loc, "isa number not a constant value");
2666 else if (Name == "discriminator") {
2667 if (getParser().ParseAbsoluteExpression(Discriminator))
2671 return Error(Loc, "unknown sub-directive in '.loc' directive");
2674 if (getLexer().is(AsmToken::EndOfStatement))
2679 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2680 Isa, Discriminator, StringRef());
2685 /// ParseDirectiveStabs
2686 /// ::= .stabs string, number, number, number
2687 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2688 SMLoc DirectiveLoc) {
2689 return TokError("unsupported directive '" + Directive + "'");
2692 /// ParseDirectiveCFISections
2693 /// ::= .cfi_sections section [, section]
2694 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2695 SMLoc DirectiveLoc) {
2700 if (getParser().ParseIdentifier(Name))
2701 return TokError("Expected an identifier");
2703 if (Name == ".eh_frame")
2705 else if (Name == ".debug_frame")
2708 if (getLexer().is(AsmToken::Comma)) {
2711 if (getParser().ParseIdentifier(Name))
2712 return TokError("Expected an identifier");
2714 if (Name == ".eh_frame")
2716 else if (Name == ".debug_frame")
2720 getStreamer().EmitCFISections(EH, Debug);
2725 /// ParseDirectiveCFIStartProc
2726 /// ::= .cfi_startproc
2727 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2728 SMLoc DirectiveLoc) {
2729 getStreamer().EmitCFIStartProc();
2733 /// ParseDirectiveCFIEndProc
2734 /// ::= .cfi_endproc
2735 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2736 getStreamer().EmitCFIEndProc();
2740 /// ParseRegisterOrRegisterNumber - parse register name or number.
2741 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2742 SMLoc DirectiveLoc) {
2745 if (getLexer().isNot(AsmToken::Integer)) {
2746 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2749 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2751 return getParser().ParseAbsoluteExpression(Register);
2756 /// ParseDirectiveCFIDefCfa
2757 /// ::= .cfi_def_cfa register, offset
2758 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2759 SMLoc DirectiveLoc) {
2760 int64_t Register = 0;
2761 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2764 if (getLexer().isNot(AsmToken::Comma))
2765 return TokError("unexpected token in directive");
2769 if (getParser().ParseAbsoluteExpression(Offset))
2772 getStreamer().EmitCFIDefCfa(Register, Offset);
2776 /// ParseDirectiveCFIDefCfaOffset
2777 /// ::= .cfi_def_cfa_offset offset
2778 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2779 SMLoc DirectiveLoc) {
2781 if (getParser().ParseAbsoluteExpression(Offset))
2784 getStreamer().EmitCFIDefCfaOffset(Offset);
2788 /// ParseDirectiveCFIAdjustCfaOffset
2789 /// ::= .cfi_adjust_cfa_offset adjustment
2790 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2791 SMLoc DirectiveLoc) {
2792 int64_t Adjustment = 0;
2793 if (getParser().ParseAbsoluteExpression(Adjustment))
2796 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2800 /// ParseDirectiveCFIDefCfaRegister
2801 /// ::= .cfi_def_cfa_register register
2802 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2803 SMLoc DirectiveLoc) {
2804 int64_t Register = 0;
2805 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2808 getStreamer().EmitCFIDefCfaRegister(Register);
2812 /// ParseDirectiveCFIOffset
2813 /// ::= .cfi_offset register, offset
2814 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2815 int64_t Register = 0;
2818 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2821 if (getLexer().isNot(AsmToken::Comma))
2822 return TokError("unexpected token in directive");
2825 if (getParser().ParseAbsoluteExpression(Offset))
2828 getStreamer().EmitCFIOffset(Register, Offset);
2832 /// ParseDirectiveCFIRelOffset
2833 /// ::= .cfi_rel_offset register, offset
2834 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2835 SMLoc DirectiveLoc) {
2836 int64_t Register = 0;
2838 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2841 if (getLexer().isNot(AsmToken::Comma))
2842 return TokError("unexpected token in directive");
2846 if (getParser().ParseAbsoluteExpression(Offset))
2849 getStreamer().EmitCFIRelOffset(Register, Offset);
2853 static bool isValidEncoding(int64_t Encoding) {
2854 if (Encoding & ~0xff)
2857 if (Encoding == dwarf::DW_EH_PE_omit)
2860 const unsigned Format = Encoding & 0xf;
2861 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2862 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2863 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2864 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2867 const unsigned Application = Encoding & 0x70;
2868 if (Application != dwarf::DW_EH_PE_absptr &&
2869 Application != dwarf::DW_EH_PE_pcrel)
2875 /// ParseDirectiveCFIPersonalityOrLsda
2876 /// ::= .cfi_personality encoding, [symbol_name]
2877 /// ::= .cfi_lsda encoding, [symbol_name]
2878 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2879 SMLoc DirectiveLoc) {
2880 int64_t Encoding = 0;
2881 if (getParser().ParseAbsoluteExpression(Encoding))
2883 if (Encoding == dwarf::DW_EH_PE_omit)
2886 if (!isValidEncoding(Encoding))
2887 return TokError("unsupported encoding.");
2889 if (getLexer().isNot(AsmToken::Comma))
2890 return TokError("unexpected token in directive");
2894 if (getParser().ParseIdentifier(Name))
2895 return TokError("expected identifier in directive");
2897 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2899 if (IDVal == ".cfi_personality")
2900 getStreamer().EmitCFIPersonality(Sym, Encoding);
2902 assert(IDVal == ".cfi_lsda");
2903 getStreamer().EmitCFILsda(Sym, Encoding);
2908 /// ParseDirectiveCFIRememberState
2909 /// ::= .cfi_remember_state
2910 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2911 SMLoc DirectiveLoc) {
2912 getStreamer().EmitCFIRememberState();
2916 /// ParseDirectiveCFIRestoreState
2917 /// ::= .cfi_remember_state
2918 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2919 SMLoc DirectiveLoc) {
2920 getStreamer().EmitCFIRestoreState();
2924 /// ParseDirectiveCFISameValue
2925 /// ::= .cfi_same_value register
2926 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2927 SMLoc DirectiveLoc) {
2928 int64_t Register = 0;
2930 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2933 getStreamer().EmitCFISameValue(Register);
2938 /// ParseDirectiveCFIRestore
2939 /// ::= .cfi_restore register
2940 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2941 SMLoc DirectiveLoc) {
2942 int64_t Register = 0;
2943 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2946 getStreamer().EmitCFIRestore(Register);
2951 /// ParseDirectiveCFIEscape
2952 /// ::= .cfi_escape expression[,...]
2953 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2954 SMLoc DirectiveLoc) {
2957 if (getParser().ParseAbsoluteExpression(CurrValue))
2960 Values.push_back((uint8_t)CurrValue);
2962 while (getLexer().is(AsmToken::Comma)) {
2965 if (getParser().ParseAbsoluteExpression(CurrValue))
2968 Values.push_back((uint8_t)CurrValue);
2971 getStreamer().EmitCFIEscape(Values);
2975 /// ParseDirectiveCFISignalFrame
2976 /// ::= .cfi_signal_frame
2977 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2978 SMLoc DirectiveLoc) {
2979 if (getLexer().isNot(AsmToken::EndOfStatement))
2980 return Error(getLexer().getLoc(),
2981 "unexpected token in '" + Directive + "' directive");
2983 getStreamer().EmitCFISignalFrame();
2988 /// ParseDirectiveMacrosOnOff
2991 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2992 SMLoc DirectiveLoc) {
2993 if (getLexer().isNot(AsmToken::EndOfStatement))
2994 return Error(getLexer().getLoc(),
2995 "unexpected token in '" + Directive + "' directive");
2997 getParser().MacrosEnabled = Directive == ".macros_on";
3002 /// ParseDirectiveMacro
3003 /// ::= .macro name [parameters]
3004 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3005 SMLoc DirectiveLoc) {
3007 if (getParser().ParseIdentifier(Name))
3008 return TokError("expected identifier in directive");
3010 std::vector<StringRef> Parameters;
3011 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3013 StringRef Parameter;
3014 if (getParser().ParseIdentifier(Parameter))
3015 return TokError("expected identifier in directive");
3016 Parameters.push_back(Parameter);
3018 if (getLexer().isNot(AsmToken::Comma))
3024 if (getLexer().isNot(AsmToken::EndOfStatement))
3025 return TokError("unexpected token in '.macro' directive");
3027 // Eat the end of statement.
3030 AsmToken EndToken, StartToken = getTok();
3032 // Lex the macro definition.
3034 // Check whether we have reached the end of the file.
3035 if (getLexer().is(AsmToken::Eof))
3036 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3038 // Otherwise, check whether we have reach the .endmacro.
3039 if (getLexer().is(AsmToken::Identifier) &&
3040 (getTok().getIdentifier() == ".endm" ||
3041 getTok().getIdentifier() == ".endmacro")) {
3042 EndToken = getTok();
3044 if (getLexer().isNot(AsmToken::EndOfStatement))
3045 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3050 // Otherwise, scan til the end of the statement.
3051 getParser().EatToEndOfStatement();
3054 if (getParser().MacroMap.lookup(Name)) {
3055 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3058 const char *BodyStart = StartToken.getLoc().getPointer();
3059 const char *BodyEnd = EndToken.getLoc().getPointer();
3060 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3061 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3065 /// ParseDirectiveEndMacro
3068 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3069 SMLoc DirectiveLoc) {
3070 if (getLexer().isNot(AsmToken::EndOfStatement))
3071 return TokError("unexpected token in '" + Directive + "' directive");
3073 // If we are inside a macro instantiation, terminate the current
3075 if (!getParser().ActiveMacros.empty()) {
3076 getParser().HandleMacroExit();
3080 // Otherwise, this .endmacro is a stray entry in the file; well formed
3081 // .endmacro directives are handled during the macro definition parsing.
3082 return TokError("unexpected '" + Directive + "' in file, "
3083 "no current macro definition");
3086 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3087 getParser().CheckForValidSection();
3089 const MCExpr *Value;
3091 if (getParser().ParseExpression(Value))
3094 if (getLexer().isNot(AsmToken::EndOfStatement))
3095 return TokError("unexpected token in directive");
3097 if (DirName[1] == 's')
3098 getStreamer().EmitSLEB128Value(Value);
3100 getStreamer().EmitULEB128Value(Value);
3106 /// \brief Create an MCAsmParser instance.
3107 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3108 MCContext &C, MCStreamer &Out,
3109 const MCAsmInfo &MAI) {
3110 return new AsmParser(SM, C, Out, MAI);