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");
339 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
341 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
342 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
345 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
347 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
348 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
349 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
350 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
351 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
352 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
353 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
354 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
355 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
356 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
357 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
358 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
359 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
360 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
361 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
362 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
363 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
364 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
365 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
366 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
368 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
369 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
370 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
371 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
373 bool ParseDirectiveLEB128(StringRef, SMLoc);
380 extern MCAsmParserExtension *createDarwinAsmParser();
381 extern MCAsmParserExtension *createELFAsmParser();
382 extern MCAsmParserExtension *createCOFFAsmParser();
386 enum { DEFAULT_ADDRSPACE = 0 };
388 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
389 MCStreamer &_Out, const MCAsmInfo &_MAI)
390 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
391 GenericParser(new GenericAsmParser), PlatformParser(0),
392 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
393 AssemblerDialect(~0U) {
394 // Save the old handler.
395 SavedDiagHandler = SrcMgr.getDiagHandler();
396 SavedDiagContext = SrcMgr.getDiagContext();
397 // Set our own handler which calls the saved handler.
398 SrcMgr.setDiagHandler(DiagHandler, this);
399 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
401 // Initialize the generic parser.
402 GenericParser->Initialize(*this);
404 // Initialize the platform / file format parser.
406 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
408 if (_MAI.hasMicrosoftFastStdCallMangling()) {
409 PlatformParser = createCOFFAsmParser();
410 PlatformParser->Initialize(*this);
411 } else if (_MAI.hasSubsectionsViaSymbols()) {
412 PlatformParser = createDarwinAsmParser();
413 PlatformParser->Initialize(*this);
415 PlatformParser = createELFAsmParser();
416 PlatformParser->Initialize(*this);
420 AsmParser::~AsmParser() {
421 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
423 // Destroy any macros.
424 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
425 ie = MacroMap.end(); it != ie; ++it)
426 delete it->getValue();
428 delete PlatformParser;
429 delete GenericParser;
432 void AsmParser::PrintMacroInstantiations() {
433 // Print the active macro instantiation stack.
434 for (std::vector<MacroInstantiation*>::const_reverse_iterator
435 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
436 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
437 "while in macro instantiation");
440 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
441 if (FatalAssemblerWarnings)
442 return Error(L, Msg, Ranges);
443 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
444 PrintMacroInstantiations();
448 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
450 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
451 PrintMacroInstantiations();
455 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
456 std::string IncludedFile;
457 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
463 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
468 /// Process the specified .incbin file by seaching for it in the include paths
469 /// then just emiting the byte contents of the file to the streamer. This
470 /// returns true on failure.
471 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
472 std::string IncludedFile;
473 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
477 // Pick up the bytes from the file and emit them.
478 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
483 void AsmParser::JumpToLoc(SMLoc Loc) {
484 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
485 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
488 const AsmToken &AsmParser::Lex() {
489 const AsmToken *tok = &Lexer.Lex();
491 if (tok->is(AsmToken::Eof)) {
492 // If this is the end of an included file, pop the parent file off the
494 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
495 if (ParentIncludeLoc != SMLoc()) {
496 JumpToLoc(ParentIncludeLoc);
501 if (tok->is(AsmToken::Error))
502 Error(Lexer.getErrLoc(), Lexer.getErr());
507 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
508 // Create the initial section, if requested.
509 if (!NoInitialTextSection)
516 AsmCond StartingCondState = TheCondState;
518 // If we are generating dwarf for assembly source files save the initial text
519 // section and generate a .file directive.
520 if (getContext().getGenDwarfForAssembly()) {
521 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
522 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
523 getStreamer().EmitLabel(SectionStartSym);
524 getContext().setGenDwarfSectionStartSym(SectionStartSym);
525 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
526 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
529 // While we have input, parse each statement.
530 while (Lexer.isNot(AsmToken::Eof)) {
531 if (!ParseStatement()) continue;
533 // We had an error, validate that one was emitted and recover by skipping to
535 assert(HadError && "Parse statement returned an error, but none emitted!");
536 EatToEndOfStatement();
539 if (TheCondState.TheCond != StartingCondState.TheCond ||
540 TheCondState.Ignore != StartingCondState.Ignore)
541 return TokError("unmatched .ifs or .elses");
543 // Check to see there are no empty DwarfFile slots.
544 const std::vector<MCDwarfFile *> &MCDwarfFiles =
545 getContext().getMCDwarfFiles();
546 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
547 if (!MCDwarfFiles[i])
548 TokError("unassigned file number: " + Twine(i) + " for .file directives");
551 // Check to see that all assembler local symbols were actually defined.
552 // Targets that don't do subsections via symbols may not want this, though,
553 // so conservatively exclude them. Only do this if we're finalizing, though,
554 // as otherwise we won't necessarilly have seen everything yet.
555 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
556 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
557 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
560 MCSymbol *Sym = i->getValue();
561 // Variable symbols may not be marked as defined, so check those
562 // explicitly. If we know it's a variable, we have a definition for
563 // the purposes of this check.
564 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
565 // FIXME: We would really like to refer back to where the symbol was
566 // first referenced for a source location. We need to add something
567 // to track that. Currently, we just point to the end of the file.
568 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
569 "assembler local symbol '" + Sym->getName() +
575 // Finalize the output stream if there are no errors and if the client wants
577 if (!HadError && !NoFinalize)
583 void AsmParser::CheckForValidSection() {
584 if (!getStreamer().getCurrentSection()) {
585 TokError("expected section directive before assembly directive");
586 Out.SwitchSection(Ctx.getMachOSection(
588 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
589 0, SectionKind::getText()));
593 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
594 void AsmParser::EatToEndOfStatement() {
595 while (Lexer.isNot(AsmToken::EndOfStatement) &&
596 Lexer.isNot(AsmToken::Eof))
600 if (Lexer.is(AsmToken::EndOfStatement))
604 StringRef AsmParser::ParseStringToEndOfStatement() {
605 const char *Start = getTok().getLoc().getPointer();
607 while (Lexer.isNot(AsmToken::EndOfStatement) &&
608 Lexer.isNot(AsmToken::Eof))
611 const char *End = getTok().getLoc().getPointer();
612 return StringRef(Start, End - Start);
615 StringRef AsmParser::ParseStringToComma() {
616 const char *Start = getTok().getLoc().getPointer();
618 while (Lexer.isNot(AsmToken::EndOfStatement) &&
619 Lexer.isNot(AsmToken::Comma) &&
620 Lexer.isNot(AsmToken::Eof))
623 const char *End = getTok().getLoc().getPointer();
624 return StringRef(Start, End - Start);
627 /// ParseParenExpr - Parse a paren expression and return it.
628 /// NOTE: This assumes the leading '(' has already been consumed.
630 /// parenexpr ::= expr)
632 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
633 if (ParseExpression(Res)) return true;
634 if (Lexer.isNot(AsmToken::RParen))
635 return TokError("expected ')' in parentheses expression");
636 EndLoc = Lexer.getLoc();
641 /// ParseBracketExpr - Parse a bracket expression and return it.
642 /// NOTE: This assumes the leading '[' has already been consumed.
644 /// bracketexpr ::= expr]
646 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
647 if (ParseExpression(Res)) return true;
648 if (Lexer.isNot(AsmToken::RBrac))
649 return TokError("expected ']' in brackets expression");
650 EndLoc = Lexer.getLoc();
655 /// ParsePrimaryExpr - Parse a primary expression and return it.
656 /// primaryexpr ::= (parenexpr
657 /// primaryexpr ::= symbol
658 /// primaryexpr ::= number
659 /// primaryexpr ::= '.'
660 /// primaryexpr ::= ~,+,- primaryexpr
661 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
662 switch (Lexer.getKind()) {
664 return TokError("unknown token in expression");
665 // If we have an error assume that we've already handled it.
666 case AsmToken::Error:
668 case AsmToken::Exclaim:
669 Lex(); // Eat the operator.
670 if (ParsePrimaryExpr(Res, EndLoc))
672 Res = MCUnaryExpr::CreateLNot(Res, getContext());
674 case AsmToken::Dollar:
675 case AsmToken::String:
676 case AsmToken::Identifier: {
677 EndLoc = Lexer.getLoc();
679 StringRef Identifier;
680 if (ParseIdentifier(Identifier))
683 // This is a symbol reference.
684 std::pair<StringRef, StringRef> Split = Identifier.split('@');
685 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
687 // Lookup the symbol variant if used.
688 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
689 if (Split.first.size() != Identifier.size()) {
690 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
691 if (Variant == MCSymbolRefExpr::VK_Invalid) {
692 Variant = MCSymbolRefExpr::VK_None;
693 return TokError("invalid variant '" + Split.second + "'");
697 // If this is an absolute variable reference, substitute it now to preserve
698 // semantics in the face of reassignment.
699 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
701 return Error(EndLoc, "unexpected modifier on variable reference");
703 Res = Sym->getVariableValue();
707 // Otherwise create a symbol ref.
708 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
711 case AsmToken::Integer: {
712 SMLoc Loc = getTok().getLoc();
713 int64_t IntVal = getTok().getIntVal();
714 Res = MCConstantExpr::Create(IntVal, getContext());
715 EndLoc = Lexer.getLoc();
717 // Look for 'b' or 'f' following an Integer as a directional label
718 if (Lexer.getKind() == AsmToken::Identifier) {
719 StringRef IDVal = getTok().getString();
720 if (IDVal == "f" || IDVal == "b"){
721 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
722 IDVal == "f" ? 1 : 0);
723 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
725 if(IDVal == "b" && Sym->isUndefined())
726 return Error(Loc, "invalid reference to undefined symbol");
727 EndLoc = Lexer.getLoc();
728 Lex(); // Eat identifier.
733 case AsmToken::Real: {
734 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
735 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
736 Res = MCConstantExpr::Create(IntVal, getContext());
740 case AsmToken::Dot: {
741 // This is a '.' reference, which references the current PC. Emit a
742 // temporary label to the streamer and refer to it.
743 MCSymbol *Sym = Ctx.CreateTempSymbol();
745 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
746 EndLoc = Lexer.getLoc();
747 Lex(); // Eat identifier.
750 case AsmToken::LParen:
751 Lex(); // Eat the '('.
752 return ParseParenExpr(Res, EndLoc);
753 case AsmToken::LBrac:
754 if (!PlatformParser->HasBracketExpressions())
755 return TokError("brackets expression not supported on this target");
756 Lex(); // Eat the '['.
757 return ParseBracketExpr(Res, EndLoc);
758 case AsmToken::Minus:
759 Lex(); // Eat the operator.
760 if (ParsePrimaryExpr(Res, EndLoc))
762 Res = MCUnaryExpr::CreateMinus(Res, getContext());
765 Lex(); // Eat the operator.
766 if (ParsePrimaryExpr(Res, EndLoc))
768 Res = MCUnaryExpr::CreatePlus(Res, getContext());
770 case AsmToken::Tilde:
771 Lex(); // Eat the operator.
772 if (ParsePrimaryExpr(Res, EndLoc))
774 Res = MCUnaryExpr::CreateNot(Res, getContext());
779 bool AsmParser::ParseExpression(const MCExpr *&Res) {
781 return ParseExpression(Res, EndLoc);
785 AsmParser::ApplyModifierToExpr(const MCExpr *E,
786 MCSymbolRefExpr::VariantKind Variant) {
787 // Recurse over the given expression, rebuilding it to apply the given variant
788 // if there is exactly one symbol.
789 switch (E->getKind()) {
791 case MCExpr::Constant:
794 case MCExpr::SymbolRef: {
795 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
797 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
798 TokError("invalid variant on expression '" +
799 getTok().getIdentifier() + "' (already modified)");
803 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
806 case MCExpr::Unary: {
807 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
808 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
811 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
814 case MCExpr::Binary: {
815 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
816 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
817 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
822 if (!LHS) LHS = BE->getLHS();
823 if (!RHS) RHS = BE->getRHS();
825 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
829 llvm_unreachable("Invalid expression kind!");
832 /// ParseExpression - Parse an expression and return it.
834 /// expr ::= expr &&,|| expr -> lowest.
835 /// expr ::= expr |,^,&,! expr
836 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
837 /// expr ::= expr <<,>> expr
838 /// expr ::= expr +,- expr
839 /// expr ::= expr *,/,% expr -> highest.
840 /// expr ::= primaryexpr
842 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
843 // Parse the expression.
845 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
848 // As a special case, we support 'a op b @ modifier' by rewriting the
849 // expression to include the modifier. This is inefficient, but in general we
850 // expect users to use 'a@modifier op b'.
851 if (Lexer.getKind() == AsmToken::At) {
854 if (Lexer.isNot(AsmToken::Identifier))
855 return TokError("unexpected symbol modifier following '@'");
857 MCSymbolRefExpr::VariantKind Variant =
858 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
859 if (Variant == MCSymbolRefExpr::VK_Invalid)
860 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
862 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
864 return TokError("invalid modifier '" + getTok().getIdentifier() +
865 "' (no symbols present)");
872 // Try to constant fold it up front, if possible.
874 if (Res->EvaluateAsAbsolute(Value))
875 Res = MCConstantExpr::Create(Value, getContext());
880 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
882 return ParseParenExpr(Res, EndLoc) ||
883 ParseBinOpRHS(1, Res, EndLoc);
886 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
889 SMLoc StartLoc = Lexer.getLoc();
890 if (ParseExpression(Expr))
893 if (!Expr->EvaluateAsAbsolute(Res))
894 return Error(StartLoc, "expected absolute expression");
899 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
900 MCBinaryExpr::Opcode &Kind) {
903 return 0; // not a binop.
905 // Lowest Precedence: &&, ||
906 case AsmToken::AmpAmp:
907 Kind = MCBinaryExpr::LAnd;
909 case AsmToken::PipePipe:
910 Kind = MCBinaryExpr::LOr;
914 // Low Precedence: |, &, ^
916 // FIXME: gas seems to support '!' as an infix operator?
918 Kind = MCBinaryExpr::Or;
920 case AsmToken::Caret:
921 Kind = MCBinaryExpr::Xor;
924 Kind = MCBinaryExpr::And;
927 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
928 case AsmToken::EqualEqual:
929 Kind = MCBinaryExpr::EQ;
931 case AsmToken::ExclaimEqual:
932 case AsmToken::LessGreater:
933 Kind = MCBinaryExpr::NE;
936 Kind = MCBinaryExpr::LT;
938 case AsmToken::LessEqual:
939 Kind = MCBinaryExpr::LTE;
941 case AsmToken::Greater:
942 Kind = MCBinaryExpr::GT;
944 case AsmToken::GreaterEqual:
945 Kind = MCBinaryExpr::GTE;
948 // Intermediate Precedence: <<, >>
949 case AsmToken::LessLess:
950 Kind = MCBinaryExpr::Shl;
952 case AsmToken::GreaterGreater:
953 Kind = MCBinaryExpr::Shr;
956 // High Intermediate Precedence: +, -
958 Kind = MCBinaryExpr::Add;
960 case AsmToken::Minus:
961 Kind = MCBinaryExpr::Sub;
964 // Highest Precedence: *, /, %
966 Kind = MCBinaryExpr::Mul;
968 case AsmToken::Slash:
969 Kind = MCBinaryExpr::Div;
971 case AsmToken::Percent:
972 Kind = MCBinaryExpr::Mod;
978 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
979 /// Res contains the LHS of the expression on input.
980 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
983 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
984 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
986 // If the next token is lower precedence than we are allowed to eat, return
987 // successfully with what we ate already.
988 if (TokPrec < Precedence)
993 // Eat the next primary expression.
995 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
997 // If BinOp binds less tightly with RHS than the operator after RHS, let
998 // the pending operator take RHS as its LHS.
999 MCBinaryExpr::Opcode Dummy;
1000 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1001 if (TokPrec < NextTokPrec) {
1002 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1005 // Merge LHS and RHS according to operator.
1006 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1014 /// ::= EndOfStatement
1015 /// ::= Label* Directive ...Operands... EndOfStatement
1016 /// ::= Label* Identifier OperandList* EndOfStatement
1017 bool AsmParser::ParseStatement() {
1018 if (Lexer.is(AsmToken::EndOfStatement)) {
1024 // Statements always start with an identifier or are a full line comment.
1025 AsmToken ID = getTok();
1026 SMLoc IDLoc = ID.getLoc();
1028 int64_t LocalLabelVal = -1;
1029 // A full line comment is a '#' as the first token.
1030 if (Lexer.is(AsmToken::Hash))
1031 return ParseCppHashLineFilenameComment(IDLoc);
1033 // Allow an integer followed by a ':' as a directional local label.
1034 if (Lexer.is(AsmToken::Integer)) {
1035 LocalLabelVal = getTok().getIntVal();
1036 if (LocalLabelVal < 0) {
1037 if (!TheCondState.Ignore)
1038 return TokError("unexpected token at start of statement");
1042 IDVal = getTok().getString();
1043 Lex(); // Consume the integer token to be used as an identifier token.
1044 if (Lexer.getKind() != AsmToken::Colon) {
1045 if (!TheCondState.Ignore)
1046 return TokError("unexpected token at start of statement");
1050 } else if (Lexer.is(AsmToken::Dot)) {
1051 // Treat '.' as a valid identifier in this context.
1055 } else if (ParseIdentifier(IDVal)) {
1056 if (!TheCondState.Ignore)
1057 return TokError("unexpected token at start of statement");
1062 // Handle conditional assembly here before checking for skipping. We
1063 // have to do this so that .endif isn't skipped in a ".if 0" block for
1066 return ParseDirectiveIf(IDLoc);
1067 if (IDVal == ".ifb")
1068 return ParseDirectiveIfb(IDLoc, true);
1069 if (IDVal == ".ifnb")
1070 return ParseDirectiveIfb(IDLoc, false);
1071 if (IDVal == ".ifc")
1072 return ParseDirectiveIfc(IDLoc, true);
1073 if (IDVal == ".ifnc")
1074 return ParseDirectiveIfc(IDLoc, false);
1075 if (IDVal == ".ifdef")
1076 return ParseDirectiveIfdef(IDLoc, true);
1077 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1078 return ParseDirectiveIfdef(IDLoc, false);
1079 if (IDVal == ".elseif")
1080 return ParseDirectiveElseIf(IDLoc);
1081 if (IDVal == ".else")
1082 return ParseDirectiveElse(IDLoc);
1083 if (IDVal == ".endif")
1084 return ParseDirectiveEndIf(IDLoc);
1086 // If we are in a ".if 0" block, ignore this statement.
1087 if (TheCondState.Ignore) {
1088 EatToEndOfStatement();
1092 // FIXME: Recurse on local labels?
1094 // See what kind of statement we have.
1095 switch (Lexer.getKind()) {
1096 case AsmToken::Colon: {
1097 CheckForValidSection();
1099 // identifier ':' -> Label.
1102 // Diagnose attempt to use '.' as a label.
1104 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1106 // Diagnose attempt to use a variable as a label.
1108 // FIXME: Diagnostics. Note the location of the definition as a label.
1109 // FIXME: This doesn't diagnose assignment to a symbol which has been
1110 // implicitly marked as external.
1112 if (LocalLabelVal == -1)
1113 Sym = getContext().GetOrCreateSymbol(IDVal);
1115 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1116 if (!Sym->isUndefined() || Sym->isVariable())
1117 return Error(IDLoc, "invalid symbol redefinition");
1122 // If we are generating dwarf for assembly source files then gather the
1123 // info to make a dwarf label entry for this label if needed.
1124 if (getContext().getGenDwarfForAssembly())
1125 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1128 // Consume any end of statement token, if present, to avoid spurious
1129 // AddBlankLine calls().
1130 if (Lexer.is(AsmToken::EndOfStatement)) {
1132 if (Lexer.is(AsmToken::Eof))
1136 return ParseStatement();
1139 case AsmToken::Equal:
1140 // identifier '=' ... -> assignment statement
1143 return ParseAssignment(IDVal, true);
1145 default: // Normal instruction or directive.
1149 // If macros are enabled, check to see if this is a macro instantiation.
1151 if (const Macro *M = MacroMap.lookup(IDVal))
1152 return HandleMacroEntry(IDVal, IDLoc, M);
1154 // Otherwise, we have a normal instruction or directive.
1155 if (IDVal[0] == '.' && IDVal != ".") {
1156 // Assembler features
1157 if (IDVal == ".set" || IDVal == ".equ")
1158 return ParseDirectiveSet(IDVal, true);
1159 if (IDVal == ".equiv")
1160 return ParseDirectiveSet(IDVal, false);
1164 if (IDVal == ".ascii")
1165 return ParseDirectiveAscii(IDVal, false);
1166 if (IDVal == ".asciz" || IDVal == ".string")
1167 return ParseDirectiveAscii(IDVal, true);
1169 if (IDVal == ".byte")
1170 return ParseDirectiveValue(1);
1171 if (IDVal == ".short")
1172 return ParseDirectiveValue(2);
1173 if (IDVal == ".value")
1174 return ParseDirectiveValue(2);
1175 if (IDVal == ".2byte")
1176 return ParseDirectiveValue(2);
1177 if (IDVal == ".long")
1178 return ParseDirectiveValue(4);
1179 if (IDVal == ".int")
1180 return ParseDirectiveValue(4);
1181 if (IDVal == ".4byte")
1182 return ParseDirectiveValue(4);
1183 if (IDVal == ".quad")
1184 return ParseDirectiveValue(8);
1185 if (IDVal == ".8byte")
1186 return ParseDirectiveValue(8);
1187 if (IDVal == ".single" || IDVal == ".float")
1188 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1189 if (IDVal == ".double")
1190 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1192 if (IDVal == ".align") {
1193 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1194 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1196 if (IDVal == ".align32") {
1197 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1198 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1200 if (IDVal == ".balign")
1201 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1202 if (IDVal == ".balignw")
1203 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1204 if (IDVal == ".balignl")
1205 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1206 if (IDVal == ".p2align")
1207 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1208 if (IDVal == ".p2alignw")
1209 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1210 if (IDVal == ".p2alignl")
1211 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1213 if (IDVal == ".org")
1214 return ParseDirectiveOrg();
1216 if (IDVal == ".fill")
1217 return ParseDirectiveFill();
1218 if (IDVal == ".space" || IDVal == ".skip")
1219 return ParseDirectiveSpace();
1220 if (IDVal == ".zero")
1221 return ParseDirectiveZero();
1223 // Symbol attribute directives
1225 if (IDVal == ".extern") {
1226 EatToEndOfStatement(); // .extern is the default, ignore it.
1229 if (IDVal == ".globl" || IDVal == ".global")
1230 return ParseDirectiveSymbolAttribute(MCSA_Global);
1231 if (IDVal == ".indirect_symbol")
1232 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1233 if (IDVal == ".lazy_reference")
1234 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1235 if (IDVal == ".no_dead_strip")
1236 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1237 if (IDVal == ".symbol_resolver")
1238 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1239 if (IDVal == ".private_extern")
1240 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1241 if (IDVal == ".reference")
1242 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1243 if (IDVal == ".weak_definition")
1244 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1245 if (IDVal == ".weak_reference")
1246 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1247 if (IDVal == ".weak_def_can_be_hidden")
1248 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1250 if (IDVal == ".comm" || IDVal == ".common")
1251 return ParseDirectiveComm(/*IsLocal=*/false);
1252 if (IDVal == ".lcomm")
1253 return ParseDirectiveComm(/*IsLocal=*/true);
1255 if (IDVal == ".abort")
1256 return ParseDirectiveAbort();
1257 if (IDVal == ".include")
1258 return ParseDirectiveInclude();
1259 if (IDVal == ".incbin")
1260 return ParseDirectiveIncbin();
1262 if (IDVal == ".code16" || IDVal == ".code16gcc")
1263 return TokError(Twine(IDVal) + " not supported yet");
1265 // Look up the handler in the handler table.
1266 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1267 DirectiveMap.lookup(IDVal);
1269 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1271 // Target hook for parsing target specific directives.
1272 if (!getTargetParser().ParseDirective(ID))
1275 return Error(IDLoc, "unknown directive");
1278 CheckForValidSection();
1280 // Canonicalize the opcode to lower case.
1281 SmallString<128> Opcode;
1282 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1283 Opcode.push_back(tolower(IDVal[i]));
1285 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1286 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1289 // Dump the parsed representation, if requested.
1290 if (getShowParsedOperands()) {
1291 SmallString<256> Str;
1292 raw_svector_ostream OS(Str);
1293 OS << "parsed instruction: [";
1294 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1297 ParsedOperands[i]->print(OS);
1301 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1304 // If we are generating dwarf for assembly source files and the current
1305 // section is the initial text section then generate a .loc directive for
1307 if (!HadError && getContext().getGenDwarfForAssembly() &&
1308 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1309 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1310 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1311 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1312 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1316 // If parsing succeeded, match the instruction.
1318 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1321 // Free any parsed operands.
1322 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1323 delete ParsedOperands[i];
1325 // Don't skip the rest of the line, the instruction parser is responsible for
1330 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1331 /// since they may not be able to be tokenized to get to the end of line token.
1332 void AsmParser::EatToEndOfLine() {
1333 if (!Lexer.is(AsmToken::EndOfStatement))
1334 Lexer.LexUntilEndOfLine();
1339 /// ParseCppHashLineFilenameComment as this:
1340 /// ::= # number "filename"
1341 /// or just as a full line comment if it doesn't have a number and a string.
1342 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1343 Lex(); // Eat the hash token.
1345 if (getLexer().isNot(AsmToken::Integer)) {
1346 // Consume the line since in cases it is not a well-formed line directive,
1347 // as if were simply a full line comment.
1352 int64_t LineNumber = getTok().getIntVal();
1355 if (getLexer().isNot(AsmToken::String)) {
1360 StringRef Filename = getTok().getString();
1361 // Get rid of the enclosing quotes.
1362 Filename = Filename.substr(1, Filename.size()-2);
1364 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1366 CppHashFilename = Filename;
1367 CppHashLineNumber = LineNumber;
1369 // Ignore any trailing characters, they're just comment.
1374 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1375 /// for the Filename and LineNo if any in the diagnostic.
1376 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1377 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1378 raw_ostream &OS = errs();
1380 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1381 const SMLoc &DiagLoc = Diag.getLoc();
1382 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1383 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1385 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1386 // before printing the message.
1387 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1388 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1389 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1390 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1393 // If we have not parsed a cpp hash line filename comment or the source
1394 // manager changed or buffer changed (like in a nested include) then just
1395 // print the normal diagnostic using its Filename and LineNo.
1396 if (!Parser->CppHashLineNumber ||
1397 &DiagSrcMgr != &Parser->SrcMgr ||
1398 DiagBuf != CppHashBuf) {
1399 if (Parser->SavedDiagHandler)
1400 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1406 // Use the CppHashFilename and calculate a line number based on the
1407 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1409 const std::string Filename = Parser->CppHashFilename;
1411 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1412 int CppHashLocLineNo =
1413 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1414 int LineNo = Parser->CppHashLineNumber - 1 +
1415 (DiagLocLineNo - CppHashLocLineNo);
1417 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1418 Filename, LineNo, Diag.getColumnNo(),
1419 Diag.getKind(), Diag.getMessage(),
1420 Diag.getLineContents(), Diag.getRanges());
1422 if (Parser->SavedDiagHandler)
1423 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1425 NewDiag.print(0, OS);
1428 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1429 const std::vector<StringRef> &Parameters,
1430 const std::vector<std::vector<AsmToken> > &A,
1432 raw_svector_ostream OS(Buf);
1433 unsigned NParameters = Parameters.size();
1434 if (NParameters != 0 && NParameters != A.size())
1435 return Error(L, "Wrong number of arguments");
1437 while (!Body.empty()) {
1438 // Scan for the next substitution.
1439 std::size_t End = Body.size(), Pos = 0;
1440 for (; Pos != End; ++Pos) {
1441 // Check for a substitution or escape.
1443 // This macro has no parameters, look for $0, $1, etc.
1444 if (Body[Pos] != '$' || Pos + 1 == End)
1447 char Next = Body[Pos + 1];
1448 if (Next == '$' || Next == 'n' || isdigit(Next))
1451 // This macro has parameters, look for \foo, \bar, etc.
1452 if (Body[Pos] == '\\' && Pos + 1 != End)
1458 OS << Body.slice(0, Pos);
1460 // Check if we reached the end.
1465 switch (Body[Pos+1]) {
1471 // $n => number of arguments
1476 // $[0-9] => argument
1478 // Missing arguments are ignored.
1479 unsigned Index = Body[Pos+1] - '0';
1480 if (Index >= A.size())
1483 // Otherwise substitute with the token values, with spaces eliminated.
1484 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1485 ie = A[Index].end(); it != ie; ++it)
1486 OS << it->getString();
1492 unsigned I = Pos + 1;
1493 while (isalnum(Body[I]) && I + 1 != End)
1496 const char *Begin = Body.data() + Pos +1;
1497 StringRef Argument(Begin, I - (Pos +1));
1499 for (; Index < NParameters; ++Index)
1500 if (Parameters[Index] == Argument)
1503 // FIXME: We should error at the macro definition.
1504 if (Index == NParameters)
1505 return Error(L, "Parameter not found");
1507 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1508 ie = A[Index].end(); it != ie; ++it)
1509 OS << it->getString();
1511 Pos += 1 + Argument.size();
1513 // Update the scan point.
1514 Body = Body.substr(Pos);
1517 // We include the .endmacro in the buffer as our queue to exit the macro
1519 OS << ".endmacro\n";
1523 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1525 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1529 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1531 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1532 // this, although we should protect against infinite loops.
1533 if (ActiveMacros.size() == 20)
1534 return TokError("macros cannot be nested more than 20 levels deep");
1536 // Parse the macro instantiation arguments.
1537 std::vector<std::vector<AsmToken> > MacroArguments;
1538 MacroArguments.push_back(std::vector<AsmToken>());
1539 unsigned ParenLevel = 0;
1541 if (Lexer.is(AsmToken::Eof))
1542 return TokError("unexpected token in macro instantiation");
1543 if (Lexer.is(AsmToken::EndOfStatement))
1546 // If we aren't inside parentheses and this is a comma, start a new token
1548 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1549 MacroArguments.push_back(std::vector<AsmToken>());
1551 // Adjust the current parentheses level.
1552 if (Lexer.is(AsmToken::LParen))
1554 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1557 // Append the token to the current argument list.
1558 MacroArguments.back().push_back(getTok());
1562 // If the last argument didn't end up with any tokens, it's not a real
1563 // argument and we should remove it from the list. This happens with either
1564 // a tailing comma or an empty argument list.
1565 if (MacroArguments.back().empty())
1566 MacroArguments.pop_back();
1568 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1569 // to hold the macro body with substitutions.
1570 SmallString<256> Buf;
1571 StringRef Body = M->Body;
1573 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1576 MemoryBuffer *Instantiation =
1577 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1579 // Create the macro instantiation object and add to the current macro
1580 // instantiation stack.
1581 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1584 ActiveMacros.push_back(MI);
1586 // Jump to the macro instantiation and prime the lexer.
1587 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1588 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1594 void AsmParser::HandleMacroExit() {
1595 // Jump to the EndOfStatement we should return to, and consume it.
1596 JumpToLoc(ActiveMacros.back()->ExitLoc);
1599 // Pop the instantiation entry.
1600 delete ActiveMacros.back();
1601 ActiveMacros.pop_back();
1604 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1605 switch (Value->getKind()) {
1606 case MCExpr::Binary: {
1607 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1608 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1611 case MCExpr::Target:
1612 case MCExpr::Constant:
1614 case MCExpr::SymbolRef: {
1615 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1617 return IsUsedIn(Sym, S.getVariableValue());
1621 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1624 llvm_unreachable("Unknown expr kind!");
1627 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1628 // FIXME: Use better location, we should use proper tokens.
1629 SMLoc EqualLoc = Lexer.getLoc();
1631 const MCExpr *Value;
1632 if (ParseExpression(Value))
1635 // Note: we don't count b as used in "a = b". This is to allow
1639 if (Lexer.isNot(AsmToken::EndOfStatement))
1640 return TokError("unexpected token in assignment");
1642 // Error on assignment to '.'.
1644 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1645 "(use '.space' or '.org').)"));
1648 // Eat the end of statement marker.
1651 // Validate that the LHS is allowed to be a variable (either it has not been
1652 // used as a symbol, or it is an absolute symbol).
1653 MCSymbol *Sym = getContext().LookupSymbol(Name);
1655 // Diagnose assignment to a label.
1657 // FIXME: Diagnostics. Note the location of the definition as a label.
1658 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1659 if (IsUsedIn(Sym, Value))
1660 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1661 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1662 ; // Allow redefinitions of undefined symbols only used in directives.
1663 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1664 ; // Allow redefinitions of variables that haven't yet been used.
1665 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1666 return Error(EqualLoc, "redefinition of '" + Name + "'");
1667 else if (!Sym->isVariable())
1668 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1669 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1670 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1673 // Don't count these checks as uses.
1674 Sym->setUsed(false);
1676 Sym = getContext().GetOrCreateSymbol(Name);
1678 // FIXME: Handle '.'.
1680 // Do the assignment.
1681 Out.EmitAssignment(Sym, Value);
1686 /// ParseIdentifier:
1689 bool AsmParser::ParseIdentifier(StringRef &Res) {
1690 // The assembler has relaxed rules for accepting identifiers, in particular we
1691 // allow things like '.globl $foo', which would normally be separate
1692 // tokens. At this level, we have already lexed so we cannot (currently)
1693 // handle this as a context dependent token, instead we detect adjacent tokens
1694 // and return the combined identifier.
1695 if (Lexer.is(AsmToken::Dollar)) {
1696 SMLoc DollarLoc = getLexer().getLoc();
1698 // Consume the dollar sign, and check for a following identifier.
1700 if (Lexer.isNot(AsmToken::Identifier))
1703 // We have a '$' followed by an identifier, make sure they are adjacent.
1704 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1707 // Construct the joined identifier and consume the token.
1708 Res = StringRef(DollarLoc.getPointer(),
1709 getTok().getIdentifier().size() + 1);
1714 if (Lexer.isNot(AsmToken::Identifier) &&
1715 Lexer.isNot(AsmToken::String))
1718 Res = getTok().getIdentifier();
1720 Lex(); // Consume the identifier token.
1725 /// ParseDirectiveSet:
1726 /// ::= .equ identifier ',' expression
1727 /// ::= .equiv identifier ',' expression
1728 /// ::= .set identifier ',' expression
1729 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1732 if (ParseIdentifier(Name))
1733 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1735 if (getLexer().isNot(AsmToken::Comma))
1736 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1739 return ParseAssignment(Name, allow_redef);
1742 bool AsmParser::ParseEscapedString(std::string &Data) {
1743 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1746 StringRef Str = getTok().getStringContents();
1747 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1748 if (Str[i] != '\\') {
1753 // Recognize escaped characters. Note that this escape semantics currently
1754 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1757 return TokError("unexpected backslash at end of string");
1759 // Recognize octal sequences.
1760 if ((unsigned) (Str[i] - '0') <= 7) {
1761 // Consume up to three octal characters.
1762 unsigned Value = Str[i] - '0';
1764 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1766 Value = Value * 8 + (Str[i] - '0');
1768 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1770 Value = Value * 8 + (Str[i] - '0');
1775 return TokError("invalid octal escape sequence (out of range)");
1777 Data += (unsigned char) Value;
1781 // Otherwise recognize individual escapes.
1784 // Just reject invalid escape sequences for now.
1785 return TokError("invalid escape sequence (unrecognized character)");
1787 case 'b': Data += '\b'; break;
1788 case 'f': Data += '\f'; break;
1789 case 'n': Data += '\n'; break;
1790 case 'r': Data += '\r'; break;
1791 case 't': Data += '\t'; break;
1792 case '"': Data += '"'; break;
1793 case '\\': Data += '\\'; break;
1800 /// ParseDirectiveAscii:
1801 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1802 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1803 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1804 CheckForValidSection();
1807 if (getLexer().isNot(AsmToken::String))
1808 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1811 if (ParseEscapedString(Data))
1814 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1816 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1820 if (getLexer().is(AsmToken::EndOfStatement))
1823 if (getLexer().isNot(AsmToken::Comma))
1824 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1833 /// ParseDirectiveValue
1834 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1835 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1836 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1837 CheckForValidSection();
1840 const MCExpr *Value;
1841 SMLoc ExprLoc = getLexer().getLoc();
1842 if (ParseExpression(Value))
1845 // Special case constant expressions to match code generator.
1846 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1847 assert(Size <= 8 && "Invalid size");
1848 uint64_t IntValue = MCE->getValue();
1849 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1850 return Error(ExprLoc, "literal value out of range for directive");
1851 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1853 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1855 if (getLexer().is(AsmToken::EndOfStatement))
1858 // FIXME: Improve diagnostic.
1859 if (getLexer().isNot(AsmToken::Comma))
1860 return TokError("unexpected token in directive");
1869 /// ParseDirectiveRealValue
1870 /// ::= (.single | .double) [ expression (, expression)* ]
1871 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1872 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1873 CheckForValidSection();
1876 // We don't truly support arithmetic on floating point expressions, so we
1877 // have to manually parse unary prefixes.
1879 if (getLexer().is(AsmToken::Minus)) {
1882 } else if (getLexer().is(AsmToken::Plus))
1885 if (getLexer().isNot(AsmToken::Integer) &&
1886 getLexer().isNot(AsmToken::Real) &&
1887 getLexer().isNot(AsmToken::Identifier))
1888 return TokError("unexpected token in directive");
1890 // Convert to an APFloat.
1891 APFloat Value(Semantics);
1892 StringRef IDVal = getTok().getString();
1893 if (getLexer().is(AsmToken::Identifier)) {
1894 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1895 Value = APFloat::getInf(Semantics);
1896 else if (!IDVal.compare_lower("nan"))
1897 Value = APFloat::getNaN(Semantics, false, ~0);
1899 return TokError("invalid floating point literal");
1900 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1901 APFloat::opInvalidOp)
1902 return TokError("invalid floating point literal");
1906 // Consume the numeric token.
1909 // Emit the value as an integer.
1910 APInt AsInt = Value.bitcastToAPInt();
1911 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1912 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1914 if (getLexer().is(AsmToken::EndOfStatement))
1917 if (getLexer().isNot(AsmToken::Comma))
1918 return TokError("unexpected token in directive");
1927 /// ParseDirectiveSpace
1928 /// ::= .space expression [ , expression ]
1929 bool AsmParser::ParseDirectiveSpace() {
1930 CheckForValidSection();
1933 if (ParseAbsoluteExpression(NumBytes))
1936 int64_t FillExpr = 0;
1937 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1938 if (getLexer().isNot(AsmToken::Comma))
1939 return TokError("unexpected token in '.space' directive");
1942 if (ParseAbsoluteExpression(FillExpr))
1945 if (getLexer().isNot(AsmToken::EndOfStatement))
1946 return TokError("unexpected token in '.space' directive");
1952 return TokError("invalid number of bytes in '.space' directive");
1954 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1955 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1960 /// ParseDirectiveZero
1961 /// ::= .zero expression
1962 bool AsmParser::ParseDirectiveZero() {
1963 CheckForValidSection();
1966 if (ParseAbsoluteExpression(NumBytes))
1970 if (getLexer().is(AsmToken::Comma)) {
1972 if (ParseAbsoluteExpression(Val))
1976 if (getLexer().isNot(AsmToken::EndOfStatement))
1977 return TokError("unexpected token in '.zero' directive");
1981 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1986 /// ParseDirectiveFill
1987 /// ::= .fill expression , expression , expression
1988 bool AsmParser::ParseDirectiveFill() {
1989 CheckForValidSection();
1992 if (ParseAbsoluteExpression(NumValues))
1995 if (getLexer().isNot(AsmToken::Comma))
1996 return TokError("unexpected token in '.fill' directive");
2000 if (ParseAbsoluteExpression(FillSize))
2003 if (getLexer().isNot(AsmToken::Comma))
2004 return TokError("unexpected token in '.fill' directive");
2008 if (ParseAbsoluteExpression(FillExpr))
2011 if (getLexer().isNot(AsmToken::EndOfStatement))
2012 return TokError("unexpected token in '.fill' directive");
2016 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2017 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2019 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2020 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2025 /// ParseDirectiveOrg
2026 /// ::= .org expression [ , expression ]
2027 bool AsmParser::ParseDirectiveOrg() {
2028 CheckForValidSection();
2030 const MCExpr *Offset;
2031 SMLoc Loc = getTok().getLoc();
2032 if (ParseExpression(Offset))
2035 // Parse optional fill expression.
2036 int64_t FillExpr = 0;
2037 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2038 if (getLexer().isNot(AsmToken::Comma))
2039 return TokError("unexpected token in '.org' directive");
2042 if (ParseAbsoluteExpression(FillExpr))
2045 if (getLexer().isNot(AsmToken::EndOfStatement))
2046 return TokError("unexpected token in '.org' directive");
2051 // Only limited forms of relocatable expressions are accepted here, it
2052 // has to be relative to the current section. The streamer will return
2053 // 'true' if the expression wasn't evaluatable.
2054 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2055 return Error(Loc, "expected assembly-time absolute expression");
2060 /// ParseDirectiveAlign
2061 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2062 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2063 CheckForValidSection();
2065 SMLoc AlignmentLoc = getLexer().getLoc();
2067 if (ParseAbsoluteExpression(Alignment))
2071 bool HasFillExpr = false;
2072 int64_t FillExpr = 0;
2073 int64_t MaxBytesToFill = 0;
2074 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2075 if (getLexer().isNot(AsmToken::Comma))
2076 return TokError("unexpected token in directive");
2079 // The fill expression can be omitted while specifying a maximum number of
2080 // alignment bytes, e.g:
2082 if (getLexer().isNot(AsmToken::Comma)) {
2084 if (ParseAbsoluteExpression(FillExpr))
2088 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2089 if (getLexer().isNot(AsmToken::Comma))
2090 return TokError("unexpected token in directive");
2093 MaxBytesLoc = getLexer().getLoc();
2094 if (ParseAbsoluteExpression(MaxBytesToFill))
2097 if (getLexer().isNot(AsmToken::EndOfStatement))
2098 return TokError("unexpected token in directive");
2107 // Compute alignment in bytes.
2109 // FIXME: Diagnose overflow.
2110 if (Alignment >= 32) {
2111 Error(AlignmentLoc, "invalid alignment value");
2115 Alignment = 1ULL << Alignment;
2118 // Diagnose non-sensical max bytes to align.
2119 if (MaxBytesLoc.isValid()) {
2120 if (MaxBytesToFill < 1) {
2121 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2122 "many bytes, ignoring maximum bytes expression");
2126 if (MaxBytesToFill >= Alignment) {
2127 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2133 // Check whether we should use optimal code alignment for this .align
2135 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2136 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2137 ValueSize == 1 && UseCodeAlign) {
2138 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2140 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2141 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2148 /// ParseDirectiveSymbolAttribute
2149 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2150 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2151 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2154 SMLoc Loc = getTok().getLoc();
2156 if (ParseIdentifier(Name))
2157 return Error(Loc, "expected identifier in directive");
2159 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2161 // Assembler local symbols don't make any sense here. Complain loudly.
2162 if (Sym->isTemporary())
2163 return Error(Loc, "non-local symbol required in directive");
2165 getStreamer().EmitSymbolAttribute(Sym, Attr);
2167 if (getLexer().is(AsmToken::EndOfStatement))
2170 if (getLexer().isNot(AsmToken::Comma))
2171 return TokError("unexpected token in directive");
2180 /// ParseDirectiveComm
2181 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2182 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2183 CheckForValidSection();
2185 SMLoc IDLoc = getLexer().getLoc();
2187 if (ParseIdentifier(Name))
2188 return TokError("expected identifier in directive");
2190 // Handle the identifier as the key symbol.
2191 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2193 if (getLexer().isNot(AsmToken::Comma))
2194 return TokError("unexpected token in directive");
2198 SMLoc SizeLoc = getLexer().getLoc();
2199 if (ParseAbsoluteExpression(Size))
2202 int64_t Pow2Alignment = 0;
2203 SMLoc Pow2AlignmentLoc;
2204 if (getLexer().is(AsmToken::Comma)) {
2206 Pow2AlignmentLoc = getLexer().getLoc();
2207 if (ParseAbsoluteExpression(Pow2Alignment))
2210 // If this target takes alignments in bytes (not log) validate and convert.
2211 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2212 if (!isPowerOf2_64(Pow2Alignment))
2213 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2214 Pow2Alignment = Log2_64(Pow2Alignment);
2218 if (getLexer().isNot(AsmToken::EndOfStatement))
2219 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2223 // NOTE: a size of zero for a .comm should create a undefined symbol
2224 // but a size of .lcomm creates a bss symbol of size zero.
2226 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2227 "be less than zero");
2229 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2230 // may internally end up wanting an alignment in bytes.
2231 // FIXME: Diagnose overflow.
2232 if (Pow2Alignment < 0)
2233 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2234 "alignment, can't be less than zero");
2236 if (!Sym->isUndefined())
2237 return Error(IDLoc, "invalid symbol redefinition");
2239 // '.lcomm' is equivalent to '.zerofill'.
2240 // Create the Symbol as a common or local common with Size and Pow2Alignment
2242 getStreamer().EmitZerofill(Ctx.getMachOSection(
2243 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2244 0, SectionKind::getBSS()),
2245 Sym, Size, 1 << Pow2Alignment);
2249 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2253 /// ParseDirectiveAbort
2254 /// ::= .abort [... message ...]
2255 bool AsmParser::ParseDirectiveAbort() {
2256 // FIXME: Use loc from directive.
2257 SMLoc Loc = getLexer().getLoc();
2259 StringRef Str = ParseStringToEndOfStatement();
2260 if (getLexer().isNot(AsmToken::EndOfStatement))
2261 return TokError("unexpected token in '.abort' directive");
2266 Error(Loc, ".abort detected. Assembly stopping.");
2268 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2269 // FIXME: Actually abort assembly here.
2274 /// ParseDirectiveInclude
2275 /// ::= .include "filename"
2276 bool AsmParser::ParseDirectiveInclude() {
2277 if (getLexer().isNot(AsmToken::String))
2278 return TokError("expected string in '.include' directive");
2280 std::string Filename = getTok().getString();
2281 SMLoc IncludeLoc = getLexer().getLoc();
2284 if (getLexer().isNot(AsmToken::EndOfStatement))
2285 return TokError("unexpected token in '.include' directive");
2287 // Strip the quotes.
2288 Filename = Filename.substr(1, Filename.size()-2);
2290 // Attempt to switch the lexer to the included file before consuming the end
2291 // of statement to avoid losing it when we switch.
2292 if (EnterIncludeFile(Filename)) {
2293 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2300 /// ParseDirectiveIncbin
2301 /// ::= .incbin "filename"
2302 bool AsmParser::ParseDirectiveIncbin() {
2303 if (getLexer().isNot(AsmToken::String))
2304 return TokError("expected string in '.incbin' directive");
2306 std::string Filename = getTok().getString();
2307 SMLoc IncbinLoc = getLexer().getLoc();
2310 if (getLexer().isNot(AsmToken::EndOfStatement))
2311 return TokError("unexpected token in '.incbin' directive");
2313 // Strip the quotes.
2314 Filename = Filename.substr(1, Filename.size()-2);
2316 // Attempt to process the included file.
2317 if (ProcessIncbinFile(Filename)) {
2318 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2325 /// ParseDirectiveIf
2326 /// ::= .if expression
2327 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2328 TheCondStack.push_back(TheCondState);
2329 TheCondState.TheCond = AsmCond::IfCond;
2330 if(TheCondState.Ignore) {
2331 EatToEndOfStatement();
2335 if (ParseAbsoluteExpression(ExprValue))
2338 if (getLexer().isNot(AsmToken::EndOfStatement))
2339 return TokError("unexpected token in '.if' directive");
2343 TheCondState.CondMet = ExprValue;
2344 TheCondState.Ignore = !TheCondState.CondMet;
2350 /// ParseDirectiveIfb
2352 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2353 TheCondStack.push_back(TheCondState);
2354 TheCondState.TheCond = AsmCond::IfCond;
2356 if(TheCondState.Ignore) {
2357 EatToEndOfStatement();
2359 StringRef Str = ParseStringToEndOfStatement();
2361 if (getLexer().isNot(AsmToken::EndOfStatement))
2362 return TokError("unexpected token in '.ifb' directive");
2366 TheCondState.CondMet = ExpectBlank == Str.empty();
2367 TheCondState.Ignore = !TheCondState.CondMet;
2373 /// ParseDirectiveIfc
2374 /// ::= .ifc string1, string2
2375 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2376 TheCondStack.push_back(TheCondState);
2377 TheCondState.TheCond = AsmCond::IfCond;
2379 if(TheCondState.Ignore) {
2380 EatToEndOfStatement();
2382 StringRef Str1 = ParseStringToComma();
2384 if (getLexer().isNot(AsmToken::Comma))
2385 return TokError("unexpected token in '.ifc' directive");
2389 StringRef Str2 = ParseStringToEndOfStatement();
2391 if (getLexer().isNot(AsmToken::EndOfStatement))
2392 return TokError("unexpected token in '.ifc' directive");
2396 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2397 TheCondState.Ignore = !TheCondState.CondMet;
2403 /// ParseDirectiveIfdef
2404 /// ::= .ifdef symbol
2405 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2407 TheCondStack.push_back(TheCondState);
2408 TheCondState.TheCond = AsmCond::IfCond;
2410 if (TheCondState.Ignore) {
2411 EatToEndOfStatement();
2413 if (ParseIdentifier(Name))
2414 return TokError("expected identifier after '.ifdef'");
2418 MCSymbol *Sym = getContext().LookupSymbol(Name);
2421 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2423 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2424 TheCondState.Ignore = !TheCondState.CondMet;
2430 /// ParseDirectiveElseIf
2431 /// ::= .elseif expression
2432 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2433 if (TheCondState.TheCond != AsmCond::IfCond &&
2434 TheCondState.TheCond != AsmCond::ElseIfCond)
2435 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2437 TheCondState.TheCond = AsmCond::ElseIfCond;
2439 bool LastIgnoreState = false;
2440 if (!TheCondStack.empty())
2441 LastIgnoreState = TheCondStack.back().Ignore;
2442 if (LastIgnoreState || TheCondState.CondMet) {
2443 TheCondState.Ignore = true;
2444 EatToEndOfStatement();
2448 if (ParseAbsoluteExpression(ExprValue))
2451 if (getLexer().isNot(AsmToken::EndOfStatement))
2452 return TokError("unexpected token in '.elseif' directive");
2455 TheCondState.CondMet = ExprValue;
2456 TheCondState.Ignore = !TheCondState.CondMet;
2462 /// ParseDirectiveElse
2464 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2465 if (getLexer().isNot(AsmToken::EndOfStatement))
2466 return TokError("unexpected token in '.else' directive");
2470 if (TheCondState.TheCond != AsmCond::IfCond &&
2471 TheCondState.TheCond != AsmCond::ElseIfCond)
2472 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2474 TheCondState.TheCond = AsmCond::ElseCond;
2475 bool LastIgnoreState = false;
2476 if (!TheCondStack.empty())
2477 LastIgnoreState = TheCondStack.back().Ignore;
2478 if (LastIgnoreState || TheCondState.CondMet)
2479 TheCondState.Ignore = true;
2481 TheCondState.Ignore = false;
2486 /// ParseDirectiveEndIf
2488 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2489 if (getLexer().isNot(AsmToken::EndOfStatement))
2490 return TokError("unexpected token in '.endif' directive");
2494 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2495 TheCondStack.empty())
2496 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2498 if (!TheCondStack.empty()) {
2499 TheCondState = TheCondStack.back();
2500 TheCondStack.pop_back();
2506 /// ParseDirectiveFile
2507 /// ::= .file [number] filename
2508 /// ::= .file number directory filename
2509 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2510 // FIXME: I'm not sure what this is.
2511 int64_t FileNumber = -1;
2512 SMLoc FileNumberLoc = getLexer().getLoc();
2513 if (getLexer().is(AsmToken::Integer)) {
2514 FileNumber = getTok().getIntVal();
2518 return TokError("file number less than one");
2521 if (getLexer().isNot(AsmToken::String))
2522 return TokError("unexpected token in '.file' directive");
2524 // Usually the directory and filename together, otherwise just the directory.
2525 StringRef Path = getTok().getString();
2526 Path = Path.substr(1, Path.size()-2);
2529 StringRef Directory;
2531 if (getLexer().is(AsmToken::String)) {
2532 if (FileNumber == -1)
2533 return TokError("explicit path specified, but no file number");
2534 Filename = getTok().getString();
2535 Filename = Filename.substr(1, Filename.size()-2);
2542 if (getLexer().isNot(AsmToken::EndOfStatement))
2543 return TokError("unexpected token in '.file' directive");
2545 if (FileNumber == -1)
2546 getStreamer().EmitFileDirective(Filename);
2548 if (getContext().getGenDwarfForAssembly() == true)
2549 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2550 "used to generate dwarf debug info for assembly code");
2552 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2553 Error(FileNumberLoc, "file number already allocated");
2559 /// ParseDirectiveLine
2560 /// ::= .line [number]
2561 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2562 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2563 if (getLexer().isNot(AsmToken::Integer))
2564 return TokError("unexpected token in '.line' directive");
2566 int64_t LineNumber = getTok().getIntVal();
2570 // FIXME: Do something with the .line.
2573 if (getLexer().isNot(AsmToken::EndOfStatement))
2574 return TokError("unexpected token in '.line' directive");
2580 /// ParseDirectiveLoc
2581 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2582 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2583 /// The first number is a file number, must have been previously assigned with
2584 /// a .file directive, the second number is the line number and optionally the
2585 /// third number is a column position (zero if not specified). The remaining
2586 /// optional items are .loc sub-directives.
2587 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2589 if (getLexer().isNot(AsmToken::Integer))
2590 return TokError("unexpected token in '.loc' directive");
2591 int64_t FileNumber = getTok().getIntVal();
2593 return TokError("file number less than one in '.loc' directive");
2594 if (!getContext().isValidDwarfFileNumber(FileNumber))
2595 return TokError("unassigned file number in '.loc' directive");
2598 int64_t LineNumber = 0;
2599 if (getLexer().is(AsmToken::Integer)) {
2600 LineNumber = getTok().getIntVal();
2602 return TokError("line number less than one in '.loc' directive");
2606 int64_t ColumnPos = 0;
2607 if (getLexer().is(AsmToken::Integer)) {
2608 ColumnPos = getTok().getIntVal();
2610 return TokError("column position less than zero in '.loc' directive");
2614 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2616 int64_t Discriminator = 0;
2617 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2619 if (getLexer().is(AsmToken::EndOfStatement))
2623 SMLoc Loc = getTok().getLoc();
2624 if (getParser().ParseIdentifier(Name))
2625 return TokError("unexpected token in '.loc' directive");
2627 if (Name == "basic_block")
2628 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2629 else if (Name == "prologue_end")
2630 Flags |= DWARF2_FLAG_PROLOGUE_END;
2631 else if (Name == "epilogue_begin")
2632 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2633 else if (Name == "is_stmt") {
2634 SMLoc Loc = getTok().getLoc();
2635 const MCExpr *Value;
2636 if (getParser().ParseExpression(Value))
2638 // The expression must be the constant 0 or 1.
2639 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2640 int Value = MCE->getValue();
2642 Flags &= ~DWARF2_FLAG_IS_STMT;
2643 else if (Value == 1)
2644 Flags |= DWARF2_FLAG_IS_STMT;
2646 return Error(Loc, "is_stmt value not 0 or 1");
2649 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2652 else if (Name == "isa") {
2653 SMLoc Loc = getTok().getLoc();
2654 const MCExpr *Value;
2655 if (getParser().ParseExpression(Value))
2657 // The expression must be a constant greater or equal to 0.
2658 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2659 int Value = MCE->getValue();
2661 return Error(Loc, "isa number less than zero");
2665 return Error(Loc, "isa number not a constant value");
2668 else if (Name == "discriminator") {
2669 if (getParser().ParseAbsoluteExpression(Discriminator))
2673 return Error(Loc, "unknown sub-directive in '.loc' directive");
2676 if (getLexer().is(AsmToken::EndOfStatement))
2681 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2682 Isa, Discriminator, StringRef());
2687 /// ParseDirectiveStabs
2688 /// ::= .stabs string, number, number, number
2689 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2690 SMLoc DirectiveLoc) {
2691 return TokError("unsupported directive '" + Directive + "'");
2694 /// ParseDirectiveCFISections
2695 /// ::= .cfi_sections section [, section]
2696 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2697 SMLoc DirectiveLoc) {
2702 if (getParser().ParseIdentifier(Name))
2703 return TokError("Expected an identifier");
2705 if (Name == ".eh_frame")
2707 else if (Name == ".debug_frame")
2710 if (getLexer().is(AsmToken::Comma)) {
2713 if (getParser().ParseIdentifier(Name))
2714 return TokError("Expected an identifier");
2716 if (Name == ".eh_frame")
2718 else if (Name == ".debug_frame")
2722 getStreamer().EmitCFISections(EH, Debug);
2727 /// ParseDirectiveCFIStartProc
2728 /// ::= .cfi_startproc
2729 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2730 SMLoc DirectiveLoc) {
2731 getStreamer().EmitCFIStartProc();
2735 /// ParseDirectiveCFIEndProc
2736 /// ::= .cfi_endproc
2737 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2738 getStreamer().EmitCFIEndProc();
2742 /// ParseRegisterOrRegisterNumber - parse register name or number.
2743 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2744 SMLoc DirectiveLoc) {
2747 if (getLexer().isNot(AsmToken::Integer)) {
2748 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2751 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2753 return getParser().ParseAbsoluteExpression(Register);
2758 /// ParseDirectiveCFIDefCfa
2759 /// ::= .cfi_def_cfa register, offset
2760 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2761 SMLoc DirectiveLoc) {
2762 int64_t Register = 0;
2763 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2766 if (getLexer().isNot(AsmToken::Comma))
2767 return TokError("unexpected token in directive");
2771 if (getParser().ParseAbsoluteExpression(Offset))
2774 getStreamer().EmitCFIDefCfa(Register, Offset);
2778 /// ParseDirectiveCFIDefCfaOffset
2779 /// ::= .cfi_def_cfa_offset offset
2780 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2781 SMLoc DirectiveLoc) {
2783 if (getParser().ParseAbsoluteExpression(Offset))
2786 getStreamer().EmitCFIDefCfaOffset(Offset);
2790 /// ParseDirectiveCFIAdjustCfaOffset
2791 /// ::= .cfi_adjust_cfa_offset adjustment
2792 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2793 SMLoc DirectiveLoc) {
2794 int64_t Adjustment = 0;
2795 if (getParser().ParseAbsoluteExpression(Adjustment))
2798 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2802 /// ParseDirectiveCFIDefCfaRegister
2803 /// ::= .cfi_def_cfa_register register
2804 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2805 SMLoc DirectiveLoc) {
2806 int64_t Register = 0;
2807 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2810 getStreamer().EmitCFIDefCfaRegister(Register);
2814 /// ParseDirectiveCFIOffset
2815 /// ::= .cfi_offset register, offset
2816 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2817 int64_t Register = 0;
2820 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2823 if (getLexer().isNot(AsmToken::Comma))
2824 return TokError("unexpected token in directive");
2827 if (getParser().ParseAbsoluteExpression(Offset))
2830 getStreamer().EmitCFIOffset(Register, Offset);
2834 /// ParseDirectiveCFIRelOffset
2835 /// ::= .cfi_rel_offset register, offset
2836 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2837 SMLoc DirectiveLoc) {
2838 int64_t Register = 0;
2840 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2843 if (getLexer().isNot(AsmToken::Comma))
2844 return TokError("unexpected token in directive");
2848 if (getParser().ParseAbsoluteExpression(Offset))
2851 getStreamer().EmitCFIRelOffset(Register, Offset);
2855 static bool isValidEncoding(int64_t Encoding) {
2856 if (Encoding & ~0xff)
2859 if (Encoding == dwarf::DW_EH_PE_omit)
2862 const unsigned Format = Encoding & 0xf;
2863 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2864 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2865 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2866 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2869 const unsigned Application = Encoding & 0x70;
2870 if (Application != dwarf::DW_EH_PE_absptr &&
2871 Application != dwarf::DW_EH_PE_pcrel)
2877 /// ParseDirectiveCFIPersonalityOrLsda
2878 /// ::= .cfi_personality encoding, [symbol_name]
2879 /// ::= .cfi_lsda encoding, [symbol_name]
2880 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2881 SMLoc DirectiveLoc) {
2882 int64_t Encoding = 0;
2883 if (getParser().ParseAbsoluteExpression(Encoding))
2885 if (Encoding == dwarf::DW_EH_PE_omit)
2888 if (!isValidEncoding(Encoding))
2889 return TokError("unsupported encoding.");
2891 if (getLexer().isNot(AsmToken::Comma))
2892 return TokError("unexpected token in directive");
2896 if (getParser().ParseIdentifier(Name))
2897 return TokError("expected identifier in directive");
2899 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2901 if (IDVal == ".cfi_personality")
2902 getStreamer().EmitCFIPersonality(Sym, Encoding);
2904 assert(IDVal == ".cfi_lsda");
2905 getStreamer().EmitCFILsda(Sym, Encoding);
2910 /// ParseDirectiveCFIRememberState
2911 /// ::= .cfi_remember_state
2912 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2913 SMLoc DirectiveLoc) {
2914 getStreamer().EmitCFIRememberState();
2918 /// ParseDirectiveCFIRestoreState
2919 /// ::= .cfi_remember_state
2920 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2921 SMLoc DirectiveLoc) {
2922 getStreamer().EmitCFIRestoreState();
2926 /// ParseDirectiveCFISameValue
2927 /// ::= .cfi_same_value register
2928 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2929 SMLoc DirectiveLoc) {
2930 int64_t Register = 0;
2932 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2935 getStreamer().EmitCFISameValue(Register);
2940 /// ParseDirectiveCFIRestore
2941 /// ::= .cfi_restore register
2942 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2943 SMLoc DirectiveLoc) {
2944 int64_t Register = 0;
2945 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2948 getStreamer().EmitCFIRestore(Register);
2953 /// ParseDirectiveCFIEscape
2954 /// ::= .cfi_escape expression[,...]
2955 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2956 SMLoc DirectiveLoc) {
2959 if (getParser().ParseAbsoluteExpression(CurrValue))
2962 Values.push_back((uint8_t)CurrValue);
2964 while (getLexer().is(AsmToken::Comma)) {
2967 if (getParser().ParseAbsoluteExpression(CurrValue))
2970 Values.push_back((uint8_t)CurrValue);
2973 getStreamer().EmitCFIEscape(Values);
2977 /// ParseDirectiveCFISignalFrame
2978 /// ::= .cfi_signal_frame
2979 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2980 SMLoc DirectiveLoc) {
2981 if (getLexer().isNot(AsmToken::EndOfStatement))
2982 return Error(getLexer().getLoc(),
2983 "unexpected token in '" + Directive + "' directive");
2985 getStreamer().EmitCFISignalFrame();
2990 /// ParseDirectiveMacrosOnOff
2993 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2994 SMLoc DirectiveLoc) {
2995 if (getLexer().isNot(AsmToken::EndOfStatement))
2996 return Error(getLexer().getLoc(),
2997 "unexpected token in '" + Directive + "' directive");
2999 getParser().MacrosEnabled = Directive == ".macros_on";
3004 /// ParseDirectiveMacro
3005 /// ::= .macro name [parameters]
3006 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3007 SMLoc DirectiveLoc) {
3009 if (getParser().ParseIdentifier(Name))
3010 return TokError("expected identifier in directive");
3012 std::vector<StringRef> Parameters;
3013 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3015 StringRef Parameter;
3016 if (getParser().ParseIdentifier(Parameter))
3017 return TokError("expected identifier in directive");
3018 Parameters.push_back(Parameter);
3020 if (getLexer().isNot(AsmToken::Comma))
3026 if (getLexer().isNot(AsmToken::EndOfStatement))
3027 return TokError("unexpected token in '.macro' directive");
3029 // Eat the end of statement.
3032 AsmToken EndToken, StartToken = getTok();
3034 // Lex the macro definition.
3036 // Check whether we have reached the end of the file.
3037 if (getLexer().is(AsmToken::Eof))
3038 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3040 // Otherwise, check whether we have reach the .endmacro.
3041 if (getLexer().is(AsmToken::Identifier) &&
3042 (getTok().getIdentifier() == ".endm" ||
3043 getTok().getIdentifier() == ".endmacro")) {
3044 EndToken = getTok();
3046 if (getLexer().isNot(AsmToken::EndOfStatement))
3047 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3052 // Otherwise, scan til the end of the statement.
3053 getParser().EatToEndOfStatement();
3056 if (getParser().MacroMap.lookup(Name)) {
3057 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3060 const char *BodyStart = StartToken.getLoc().getPointer();
3061 const char *BodyEnd = EndToken.getLoc().getPointer();
3062 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3063 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3067 /// ParseDirectiveEndMacro
3070 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3071 SMLoc DirectiveLoc) {
3072 if (getLexer().isNot(AsmToken::EndOfStatement))
3073 return TokError("unexpected token in '" + Directive + "' directive");
3075 // If we are inside a macro instantiation, terminate the current
3077 if (!getParser().ActiveMacros.empty()) {
3078 getParser().HandleMacroExit();
3082 // Otherwise, this .endmacro is a stray entry in the file; well formed
3083 // .endmacro directives are handled during the macro definition parsing.
3084 return TokError("unexpected '" + Directive + "' in file, "
3085 "no current macro definition");
3088 /// ParseDirectivePurgeMacro
3090 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3091 SMLoc DirectiveLoc) {
3093 if (getParser().ParseIdentifier(Name))
3094 return TokError("expected identifier in '.purgem' directive");
3096 if (getLexer().isNot(AsmToken::EndOfStatement))
3097 return TokError("unexpected token in '.purgem' directive");
3099 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3100 if (I == getParser().MacroMap.end())
3101 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3103 // Undefine the macro.
3104 delete I->getValue();
3105 getParser().MacroMap.erase(I);
3109 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3110 getParser().CheckForValidSection();
3112 const MCExpr *Value;
3114 if (getParser().ParseExpression(Value))
3117 if (getLexer().isNot(AsmToken::EndOfStatement))
3118 return TokError("unexpected token in directive");
3120 if (DirName[1] == 's')
3121 getStreamer().EmitSLEB128Value(Value);
3123 getStreamer().EmitULEB128Value(Value);
3129 /// \brief Create an MCAsmParser instance.
3130 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3131 MCContext &C, MCStreamer &Out,
3132 const MCAsmInfo &MAI) {
3133 return new AsmParser(SM, C, Out, MAI);