1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCParser/AsmCond.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCTargetAsmParser.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/raw_ostream.h"
42 FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
47 /// \brief Helper class for tracking macro definitions.
51 std::vector<StringRef> Parameters;
54 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
58 /// \brief Helper class for storing information about an active macro
60 struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
70 /// The location where parsing should resume upon instantiation completion.
74 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
78 /// \brief The concrete assembly parser instance.
79 class AsmParser : public MCAsmParser {
80 friend class GenericAsmParser;
82 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
90 SourceMgr::DiagHandlerTy SavedDiagHandler;
91 void *SavedDiagContext;
92 MCAsmParserExtension *GenericParser;
93 MCAsmParserExtension *PlatformParser;
95 /// This is the current buffer index we're lexing from as managed by the
100 std::vector<AsmCond> TheCondStack;
102 /// DirectiveMap - This is a table handlers for directives. Each handler is
103 /// invoked after the directive identifier is read and is responsible for
104 /// parsing and validating the rest of the directive. The handler is passed
105 /// in the directive name and the location of the directive keyword.
106 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
108 /// MacroMap - Map of currently defined macros.
109 StringMap<Macro*> MacroMap;
111 /// ActiveMacros - Stack of active macro instantiations.
112 std::vector<MacroInstantiation*> ActiveMacros;
114 /// Boolean tracking whether macro substitution is enabled.
115 unsigned MacrosEnabled : 1;
117 /// Flag tracking whether any errors have been encountered.
118 unsigned HadError : 1;
120 /// The values from the last parsed cpp hash file line comment if any.
121 StringRef CppHashFilename;
122 int64_t CppHashLineNumber;
126 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
127 const MCAsmInfo &MAI);
130 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
132 void AddDirectiveHandler(MCAsmParserExtension *Object,
134 DirectiveHandler Handler) {
135 DirectiveMap[Directive] = std::make_pair(Object, Handler);
139 /// @name MCAsmParser Interface
142 virtual SourceMgr &getSourceManager() { return SrcMgr; }
143 virtual MCAsmLexer &getLexer() { return Lexer; }
144 virtual MCContext &getContext() { return Ctx; }
145 virtual MCStreamer &getStreamer() { return Out; }
146 virtual unsigned getAssemblerDialect() { return MAI.getAssemblerDialect(); }
148 virtual bool Warning(SMLoc L, const Twine &Msg,
149 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
150 virtual bool Error(SMLoc L, const Twine &Msg,
151 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
153 const AsmToken &Lex();
155 bool ParseExpression(const MCExpr *&Res);
156 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
157 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
158 virtual bool ParseAbsoluteExpression(int64_t &Res);
163 void CheckForValidSection();
165 bool ParseStatement();
166 void EatToEndOfLine();
167 bool ParseCppHashLineFilenameComment(const SMLoc &L);
169 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
170 bool expandMacro(SmallString<256> &Buf, StringRef Body,
171 const std::vector<StringRef> &Parameters,
172 const std::vector<std::vector<AsmToken> > &A,
174 void HandleMacroExit();
176 void PrintMacroInstantiations();
177 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
178 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
179 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
181 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
183 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
184 bool EnterIncludeFile(const std::string &Filename);
185 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
186 /// This returns true on failure.
187 bool ProcessIncbinFile(const std::string &Filename);
189 /// \brief Reset the current lexer position to that given by \arg Loc. The
190 /// current token is not set; clients should ensure Lex() is called
192 void JumpToLoc(SMLoc Loc);
194 void EatToEndOfStatement();
196 /// \brief Parse up to the end of statement and a return the contents from the
197 /// current token until the end of the statement; the current token on exit
198 /// will be either the EndOfStatement or EOF.
199 StringRef ParseStringToEndOfStatement();
201 bool ParseAssignment(StringRef Name, bool allow_redef);
203 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
204 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
205 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
206 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
208 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
209 /// and set \arg Res to the identifier contents.
210 bool ParseIdentifier(StringRef &Res);
212 // Directive Parsing.
214 // ".ascii", ".asciiz", ".string"
215 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
216 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
217 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
218 bool ParseDirectiveFill(); // ".fill"
219 bool ParseDirectiveSpace(); // ".space"
220 bool ParseDirectiveZero(); // ".zero"
221 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
222 bool ParseDirectiveOrg(); // ".org"
223 // ".align{,32}", ".p2align{,w,l}"
224 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
226 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
227 /// accepts a single symbol (which should be a label or an external).
228 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
230 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
232 bool ParseDirectiveAbort(); // ".abort"
233 bool ParseDirectiveInclude(); // ".include"
234 bool ParseDirectiveIncbin(); // ".incbin"
236 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
237 // ".ifdef" or ".ifndef", depending on expect_defined
238 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
239 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
240 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
241 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
243 /// ParseEscapedString - Parse the current token as a string which may include
244 /// escaped characters and return the string contents.
245 bool ParseEscapedString(std::string &Data);
247 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
248 MCSymbolRefExpr::VariantKind Variant);
251 /// \brief Generic implementations of directive handling, etc. which is shared
252 /// (or the default, at least) for all assembler parser.
253 class GenericAsmParser : public MCAsmParserExtension {
254 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
255 void AddDirectiveHandler(StringRef Directive) {
256 getParser().AddDirectiveHandler(this, Directive,
257 HandleDirective<GenericAsmParser, Handler>);
260 GenericAsmParser() {}
262 AsmParser &getParser() {
263 return (AsmParser&) this->MCAsmParserExtension::getParser();
266 virtual void Initialize(MCAsmParser &Parser) {
267 // Call the base implementation.
268 this->MCAsmParserExtension::Initialize(Parser);
270 // Debugging directives.
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
277 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
279 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
281 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
283 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
285 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
286 ".cfi_def_cfa_offset");
287 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
288 ".cfi_adjust_cfa_offset");
289 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
290 ".cfi_def_cfa_register");
291 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
293 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
296 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
298 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
300 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
302 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
304 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
306 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
308 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
310 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
313 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
315 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
317 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
318 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
319 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
321 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
322 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
325 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
327 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
328 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
329 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
330 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
331 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
332 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
333 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
334 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
335 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
336 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
337 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
338 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
339 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
340 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
341 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
342 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
343 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
344 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
345 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
346 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
348 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
349 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
350 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
352 bool ParseDirectiveLEB128(StringRef, SMLoc);
359 extern MCAsmParserExtension *createDarwinAsmParser();
360 extern MCAsmParserExtension *createELFAsmParser();
361 extern MCAsmParserExtension *createCOFFAsmParser();
365 enum { DEFAULT_ADDRSPACE = 0 };
367 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
368 MCStreamer &_Out, const MCAsmInfo &_MAI)
369 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
370 GenericParser(new GenericAsmParser), PlatformParser(0),
371 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0) {
372 // Save the old handler.
373 SavedDiagHandler = SrcMgr.getDiagHandler();
374 SavedDiagContext = SrcMgr.getDiagContext();
375 // Set our own handler which calls the saved handler.
376 SrcMgr.setDiagHandler(DiagHandler, this);
377 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
379 // Initialize the generic parser.
380 GenericParser->Initialize(*this);
382 // Initialize the platform / file format parser.
384 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
386 if (_MAI.hasMicrosoftFastStdCallMangling()) {
387 PlatformParser = createCOFFAsmParser();
388 PlatformParser->Initialize(*this);
389 } else if (_MAI.hasSubsectionsViaSymbols()) {
390 PlatformParser = createDarwinAsmParser();
391 PlatformParser->Initialize(*this);
393 PlatformParser = createELFAsmParser();
394 PlatformParser->Initialize(*this);
398 AsmParser::~AsmParser() {
399 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
401 // Destroy any macros.
402 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
403 ie = MacroMap.end(); it != ie; ++it)
404 delete it->getValue();
406 delete PlatformParser;
407 delete GenericParser;
410 void AsmParser::PrintMacroInstantiations() {
411 // Print the active macro instantiation stack.
412 for (std::vector<MacroInstantiation*>::const_reverse_iterator
413 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
414 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
415 "while in macro instantiation");
418 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
419 if (FatalAssemblerWarnings)
420 return Error(L, Msg, Ranges);
421 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
422 PrintMacroInstantiations();
426 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
428 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
429 PrintMacroInstantiations();
433 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
434 std::string IncludedFile;
435 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
441 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
446 /// Process the specified .incbin file by seaching for it in the include paths
447 /// then just emiting the byte contents of the file to the streamer. This
448 /// returns true on failure.
449 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
450 std::string IncludedFile;
451 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
455 // Pick up the bytes from the file and emit them.
456 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
461 void AsmParser::JumpToLoc(SMLoc Loc) {
462 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
463 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
466 const AsmToken &AsmParser::Lex() {
467 const AsmToken *tok = &Lexer.Lex();
469 if (tok->is(AsmToken::Eof)) {
470 // If this is the end of an included file, pop the parent file off the
472 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
473 if (ParentIncludeLoc != SMLoc()) {
474 JumpToLoc(ParentIncludeLoc);
479 if (tok->is(AsmToken::Error))
480 Error(Lexer.getErrLoc(), Lexer.getErr());
485 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
486 // Create the initial section, if requested.
487 if (!NoInitialTextSection)
494 AsmCond StartingCondState = TheCondState;
496 // If we are generating dwarf for assembly source files save the initial text
497 // section and generate a .file directive.
498 if (getContext().getGenDwarfForAssembly()) {
499 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
500 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
501 getStreamer().EmitLabel(SectionStartSym);
502 getContext().setGenDwarfSectionStartSym(SectionStartSym);
503 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
504 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
507 // While we have input, parse each statement.
508 while (Lexer.isNot(AsmToken::Eof)) {
509 if (!ParseStatement()) continue;
511 // We had an error, validate that one was emitted and recover by skipping to
513 assert(HadError && "Parse statement returned an error, but none emitted!");
514 EatToEndOfStatement();
517 if (TheCondState.TheCond != StartingCondState.TheCond ||
518 TheCondState.Ignore != StartingCondState.Ignore)
519 return TokError("unmatched .ifs or .elses");
521 // Check to see there are no empty DwarfFile slots.
522 const std::vector<MCDwarfFile *> &MCDwarfFiles =
523 getContext().getMCDwarfFiles();
524 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
525 if (!MCDwarfFiles[i])
526 TokError("unassigned file number: " + Twine(i) + " for .file directives");
529 // Check to see that all assembler local symbols were actually defined.
530 // Targets that don't do subsections via symbols may not want this, though,
531 // so conservatively exclude them. Only do this if we're finalizing, though,
532 // as otherwise we won't necessarilly have seen everything yet.
533 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
534 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
535 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
538 MCSymbol *Sym = i->getValue();
539 // Variable symbols may not be marked as defined, so check those
540 // explicitly. If we know it's a variable, we have a definition for
541 // the purposes of this check.
542 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
543 // FIXME: We would really like to refer back to where the symbol was
544 // first referenced for a source location. We need to add something
545 // to track that. Currently, we just point to the end of the file.
546 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
547 "assembler local symbol '" + Sym->getName() +
553 // Finalize the output stream if there are no errors and if the client wants
555 if (!HadError && !NoFinalize)
561 void AsmParser::CheckForValidSection() {
562 if (!getStreamer().getCurrentSection()) {
563 TokError("expected section directive before assembly directive");
564 Out.SwitchSection(Ctx.getMachOSection(
566 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
567 0, SectionKind::getText()));
571 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
572 void AsmParser::EatToEndOfStatement() {
573 while (Lexer.isNot(AsmToken::EndOfStatement) &&
574 Lexer.isNot(AsmToken::Eof))
578 if (Lexer.is(AsmToken::EndOfStatement))
582 StringRef AsmParser::ParseStringToEndOfStatement() {
583 const char *Start = getTok().getLoc().getPointer();
585 while (Lexer.isNot(AsmToken::EndOfStatement) &&
586 Lexer.isNot(AsmToken::Eof))
589 const char *End = getTok().getLoc().getPointer();
590 return StringRef(Start, End - Start);
593 /// ParseParenExpr - Parse a paren expression and return it.
594 /// NOTE: This assumes the leading '(' has already been consumed.
596 /// parenexpr ::= expr)
598 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
599 if (ParseExpression(Res)) return true;
600 if (Lexer.isNot(AsmToken::RParen))
601 return TokError("expected ')' in parentheses expression");
602 EndLoc = Lexer.getLoc();
607 /// ParseBracketExpr - Parse a bracket expression and return it.
608 /// NOTE: This assumes the leading '[' has already been consumed.
610 /// bracketexpr ::= expr]
612 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
613 if (ParseExpression(Res)) return true;
614 if (Lexer.isNot(AsmToken::RBrac))
615 return TokError("expected ']' in brackets expression");
616 EndLoc = Lexer.getLoc();
621 /// ParsePrimaryExpr - Parse a primary expression and return it.
622 /// primaryexpr ::= (parenexpr
623 /// primaryexpr ::= symbol
624 /// primaryexpr ::= number
625 /// primaryexpr ::= '.'
626 /// primaryexpr ::= ~,+,- primaryexpr
627 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
628 switch (Lexer.getKind()) {
630 return TokError("unknown token in expression");
631 // If we have an error assume that we've already handled it.
632 case AsmToken::Error:
634 case AsmToken::Exclaim:
635 Lex(); // Eat the operator.
636 if (ParsePrimaryExpr(Res, EndLoc))
638 Res = MCUnaryExpr::CreateLNot(Res, getContext());
640 case AsmToken::Dollar:
641 case AsmToken::String:
642 case AsmToken::Identifier: {
643 EndLoc = Lexer.getLoc();
645 StringRef Identifier;
646 if (ParseIdentifier(Identifier))
649 // This is a symbol reference.
650 std::pair<StringRef, StringRef> Split = Identifier.split('@');
651 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
653 // Lookup the symbol variant if used.
654 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
655 if (Split.first.size() != Identifier.size()) {
656 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
657 if (Variant == MCSymbolRefExpr::VK_Invalid) {
658 Variant = MCSymbolRefExpr::VK_None;
659 return TokError("invalid variant '" + Split.second + "'");
663 // If this is an absolute variable reference, substitute it now to preserve
664 // semantics in the face of reassignment.
665 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
667 return Error(EndLoc, "unexpected modifier on variable reference");
669 Res = Sym->getVariableValue();
673 // Otherwise create a symbol ref.
674 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
677 case AsmToken::Integer: {
678 SMLoc Loc = getTok().getLoc();
679 int64_t IntVal = getTok().getIntVal();
680 Res = MCConstantExpr::Create(IntVal, getContext());
681 EndLoc = Lexer.getLoc();
683 // Look for 'b' or 'f' following an Integer as a directional label
684 if (Lexer.getKind() == AsmToken::Identifier) {
685 StringRef IDVal = getTok().getString();
686 if (IDVal == "f" || IDVal == "b"){
687 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
688 IDVal == "f" ? 1 : 0);
689 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
691 if(IDVal == "b" && Sym->isUndefined())
692 return Error(Loc, "invalid reference to undefined symbol");
693 EndLoc = Lexer.getLoc();
694 Lex(); // Eat identifier.
699 case AsmToken::Real: {
700 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
701 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
702 Res = MCConstantExpr::Create(IntVal, getContext());
706 case AsmToken::Dot: {
707 // This is a '.' reference, which references the current PC. Emit a
708 // temporary label to the streamer and refer to it.
709 MCSymbol *Sym = Ctx.CreateTempSymbol();
711 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
712 EndLoc = Lexer.getLoc();
713 Lex(); // Eat identifier.
716 case AsmToken::LParen:
717 Lex(); // Eat the '('.
718 return ParseParenExpr(Res, EndLoc);
719 case AsmToken::LBrac:
720 if (!PlatformParser->HasBracketExpressions())
721 return TokError("brackets expression not supported on this target");
722 Lex(); // Eat the '['.
723 return ParseBracketExpr(Res, EndLoc);
724 case AsmToken::Minus:
725 Lex(); // Eat the operator.
726 if (ParsePrimaryExpr(Res, EndLoc))
728 Res = MCUnaryExpr::CreateMinus(Res, getContext());
731 Lex(); // Eat the operator.
732 if (ParsePrimaryExpr(Res, EndLoc))
734 Res = MCUnaryExpr::CreatePlus(Res, getContext());
736 case AsmToken::Tilde:
737 Lex(); // Eat the operator.
738 if (ParsePrimaryExpr(Res, EndLoc))
740 Res = MCUnaryExpr::CreateNot(Res, getContext());
745 bool AsmParser::ParseExpression(const MCExpr *&Res) {
747 return ParseExpression(Res, EndLoc);
751 AsmParser::ApplyModifierToExpr(const MCExpr *E,
752 MCSymbolRefExpr::VariantKind Variant) {
753 // Recurse over the given expression, rebuilding it to apply the given variant
754 // if there is exactly one symbol.
755 switch (E->getKind()) {
757 case MCExpr::Constant:
760 case MCExpr::SymbolRef: {
761 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
763 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
764 TokError("invalid variant on expression '" +
765 getTok().getIdentifier() + "' (already modified)");
769 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
772 case MCExpr::Unary: {
773 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
774 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
777 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
780 case MCExpr::Binary: {
781 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
782 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
783 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
788 if (!LHS) LHS = BE->getLHS();
789 if (!RHS) RHS = BE->getRHS();
791 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
795 assert(0 && "Invalid expression kind!");
799 /// ParseExpression - Parse an expression and return it.
801 /// expr ::= expr &&,|| expr -> lowest.
802 /// expr ::= expr |,^,&,! expr
803 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
804 /// expr ::= expr <<,>> expr
805 /// expr ::= expr +,- expr
806 /// expr ::= expr *,/,% expr -> highest.
807 /// expr ::= primaryexpr
809 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
810 // Parse the expression.
812 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
815 // As a special case, we support 'a op b @ modifier' by rewriting the
816 // expression to include the modifier. This is inefficient, but in general we
817 // expect users to use 'a@modifier op b'.
818 if (Lexer.getKind() == AsmToken::At) {
821 if (Lexer.isNot(AsmToken::Identifier))
822 return TokError("unexpected symbol modifier following '@'");
824 MCSymbolRefExpr::VariantKind Variant =
825 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
826 if (Variant == MCSymbolRefExpr::VK_Invalid)
827 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
829 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
831 return TokError("invalid modifier '" + getTok().getIdentifier() +
832 "' (no symbols present)");
839 // Try to constant fold it up front, if possible.
841 if (Res->EvaluateAsAbsolute(Value))
842 Res = MCConstantExpr::Create(Value, getContext());
847 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
849 return ParseParenExpr(Res, EndLoc) ||
850 ParseBinOpRHS(1, Res, EndLoc);
853 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
856 SMLoc StartLoc = Lexer.getLoc();
857 if (ParseExpression(Expr))
860 if (!Expr->EvaluateAsAbsolute(Res))
861 return Error(StartLoc, "expected absolute expression");
866 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
867 MCBinaryExpr::Opcode &Kind) {
870 return 0; // not a binop.
872 // Lowest Precedence: &&, ||
873 case AsmToken::AmpAmp:
874 Kind = MCBinaryExpr::LAnd;
876 case AsmToken::PipePipe:
877 Kind = MCBinaryExpr::LOr;
881 // Low Precedence: |, &, ^
883 // FIXME: gas seems to support '!' as an infix operator?
885 Kind = MCBinaryExpr::Or;
887 case AsmToken::Caret:
888 Kind = MCBinaryExpr::Xor;
891 Kind = MCBinaryExpr::And;
894 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
895 case AsmToken::EqualEqual:
896 Kind = MCBinaryExpr::EQ;
898 case AsmToken::ExclaimEqual:
899 case AsmToken::LessGreater:
900 Kind = MCBinaryExpr::NE;
903 Kind = MCBinaryExpr::LT;
905 case AsmToken::LessEqual:
906 Kind = MCBinaryExpr::LTE;
908 case AsmToken::Greater:
909 Kind = MCBinaryExpr::GT;
911 case AsmToken::GreaterEqual:
912 Kind = MCBinaryExpr::GTE;
915 // Intermediate Precedence: <<, >>
916 case AsmToken::LessLess:
917 Kind = MCBinaryExpr::Shl;
919 case AsmToken::GreaterGreater:
920 Kind = MCBinaryExpr::Shr;
923 // High Intermediate Precedence: +, -
925 Kind = MCBinaryExpr::Add;
927 case AsmToken::Minus:
928 Kind = MCBinaryExpr::Sub;
931 // Highest Precedence: *, /, %
933 Kind = MCBinaryExpr::Mul;
935 case AsmToken::Slash:
936 Kind = MCBinaryExpr::Div;
938 case AsmToken::Percent:
939 Kind = MCBinaryExpr::Mod;
945 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
946 /// Res contains the LHS of the expression on input.
947 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
950 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
951 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
953 // If the next token is lower precedence than we are allowed to eat, return
954 // successfully with what we ate already.
955 if (TokPrec < Precedence)
960 // Eat the next primary expression.
962 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
964 // If BinOp binds less tightly with RHS than the operator after RHS, let
965 // the pending operator take RHS as its LHS.
966 MCBinaryExpr::Opcode Dummy;
967 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
968 if (TokPrec < NextTokPrec) {
969 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
972 // Merge LHS and RHS according to operator.
973 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
981 /// ::= EndOfStatement
982 /// ::= Label* Directive ...Operands... EndOfStatement
983 /// ::= Label* Identifier OperandList* EndOfStatement
984 bool AsmParser::ParseStatement() {
985 if (Lexer.is(AsmToken::EndOfStatement)) {
991 // Statements always start with an identifier or are a full line comment.
992 AsmToken ID = getTok();
993 SMLoc IDLoc = ID.getLoc();
995 int64_t LocalLabelVal = -1;
996 // A full line comment is a '#' as the first token.
997 if (Lexer.is(AsmToken::Hash))
998 return ParseCppHashLineFilenameComment(IDLoc);
1000 // Allow an integer followed by a ':' as a directional local label.
1001 if (Lexer.is(AsmToken::Integer)) {
1002 LocalLabelVal = getTok().getIntVal();
1003 if (LocalLabelVal < 0) {
1004 if (!TheCondState.Ignore)
1005 return TokError("unexpected token at start of statement");
1009 IDVal = getTok().getString();
1010 Lex(); // Consume the integer token to be used as an identifier token.
1011 if (Lexer.getKind() != AsmToken::Colon) {
1012 if (!TheCondState.Ignore)
1013 return TokError("unexpected token at start of statement");
1017 } else if (Lexer.is(AsmToken::Dot)) {
1018 // Treat '.' as a valid identifier in this context.
1022 } else if (ParseIdentifier(IDVal)) {
1023 if (!TheCondState.Ignore)
1024 return TokError("unexpected token at start of statement");
1029 // Handle conditional assembly here before checking for skipping. We
1030 // have to do this so that .endif isn't skipped in a ".if 0" block for
1033 return ParseDirectiveIf(IDLoc);
1034 if (IDVal == ".ifdef")
1035 return ParseDirectiveIfdef(IDLoc, true);
1036 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1037 return ParseDirectiveIfdef(IDLoc, false);
1038 if (IDVal == ".elseif")
1039 return ParseDirectiveElseIf(IDLoc);
1040 if (IDVal == ".else")
1041 return ParseDirectiveElse(IDLoc);
1042 if (IDVal == ".endif")
1043 return ParseDirectiveEndIf(IDLoc);
1045 // If we are in a ".if 0" block, ignore this statement.
1046 if (TheCondState.Ignore) {
1047 EatToEndOfStatement();
1051 // FIXME: Recurse on local labels?
1053 // See what kind of statement we have.
1054 switch (Lexer.getKind()) {
1055 case AsmToken::Colon: {
1056 CheckForValidSection();
1058 // identifier ':' -> Label.
1061 // Diagnose attempt to use '.' as a label.
1063 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1065 // Diagnose attempt to use a variable as a label.
1067 // FIXME: Diagnostics. Note the location of the definition as a label.
1068 // FIXME: This doesn't diagnose assignment to a symbol which has been
1069 // implicitly marked as external.
1071 if (LocalLabelVal == -1)
1072 Sym = getContext().GetOrCreateSymbol(IDVal);
1074 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1075 if (!Sym->isUndefined() || Sym->isVariable())
1076 return Error(IDLoc, "invalid symbol redefinition");
1081 // If we are generating dwarf for assembly source files then gather the
1082 // info to make a dwarf label entry for this label if needed.
1083 if (getContext().getGenDwarfForAssembly())
1084 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1087 // Consume any end of statement token, if present, to avoid spurious
1088 // AddBlankLine calls().
1089 if (Lexer.is(AsmToken::EndOfStatement)) {
1091 if (Lexer.is(AsmToken::Eof))
1095 return ParseStatement();
1098 case AsmToken::Equal:
1099 // identifier '=' ... -> assignment statement
1102 return ParseAssignment(IDVal, true);
1104 default: // Normal instruction or directive.
1108 // If macros are enabled, check to see if this is a macro instantiation.
1110 if (const Macro *M = MacroMap.lookup(IDVal))
1111 return HandleMacroEntry(IDVal, IDLoc, M);
1113 // Otherwise, we have a normal instruction or directive.
1114 if (IDVal[0] == '.' && IDVal != ".") {
1115 // Assembler features
1116 if (IDVal == ".set" || IDVal == ".equ")
1117 return ParseDirectiveSet(IDVal, true);
1118 if (IDVal == ".equiv")
1119 return ParseDirectiveSet(IDVal, false);
1123 if (IDVal == ".ascii")
1124 return ParseDirectiveAscii(IDVal, false);
1125 if (IDVal == ".asciz" || IDVal == ".string")
1126 return ParseDirectiveAscii(IDVal, true);
1128 if (IDVal == ".byte")
1129 return ParseDirectiveValue(1);
1130 if (IDVal == ".short")
1131 return ParseDirectiveValue(2);
1132 if (IDVal == ".value")
1133 return ParseDirectiveValue(2);
1134 if (IDVal == ".2byte")
1135 return ParseDirectiveValue(2);
1136 if (IDVal == ".long")
1137 return ParseDirectiveValue(4);
1138 if (IDVal == ".int")
1139 return ParseDirectiveValue(4);
1140 if (IDVal == ".4byte")
1141 return ParseDirectiveValue(4);
1142 if (IDVal == ".quad")
1143 return ParseDirectiveValue(8);
1144 if (IDVal == ".8byte")
1145 return ParseDirectiveValue(8);
1146 if (IDVal == ".single" || IDVal == ".float")
1147 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1148 if (IDVal == ".double")
1149 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1151 if (IDVal == ".align") {
1152 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1153 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1155 if (IDVal == ".align32") {
1156 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1157 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1159 if (IDVal == ".balign")
1160 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1161 if (IDVal == ".balignw")
1162 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1163 if (IDVal == ".balignl")
1164 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1165 if (IDVal == ".p2align")
1166 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1167 if (IDVal == ".p2alignw")
1168 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1169 if (IDVal == ".p2alignl")
1170 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1172 if (IDVal == ".org")
1173 return ParseDirectiveOrg();
1175 if (IDVal == ".fill")
1176 return ParseDirectiveFill();
1177 if (IDVal == ".space" || IDVal == ".skip")
1178 return ParseDirectiveSpace();
1179 if (IDVal == ".zero")
1180 return ParseDirectiveZero();
1182 // Symbol attribute directives
1184 if (IDVal == ".globl" || IDVal == ".global")
1185 return ParseDirectiveSymbolAttribute(MCSA_Global);
1186 if (IDVal == ".indirect_symbol")
1187 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1188 if (IDVal == ".lazy_reference")
1189 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1190 if (IDVal == ".no_dead_strip")
1191 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1192 if (IDVal == ".symbol_resolver")
1193 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1194 if (IDVal == ".private_extern")
1195 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1196 if (IDVal == ".reference")
1197 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1198 if (IDVal == ".weak_definition")
1199 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1200 if (IDVal == ".weak_reference")
1201 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1202 if (IDVal == ".weak_def_can_be_hidden")
1203 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1205 if (IDVal == ".comm" || IDVal == ".common")
1206 return ParseDirectiveComm(/*IsLocal=*/false);
1207 if (IDVal == ".lcomm")
1208 return ParseDirectiveComm(/*IsLocal=*/true);
1210 if (IDVal == ".abort")
1211 return ParseDirectiveAbort();
1212 if (IDVal == ".include")
1213 return ParseDirectiveInclude();
1214 if (IDVal == ".incbin")
1215 return ParseDirectiveIncbin();
1217 if (IDVal == ".code16")
1218 return TokError(Twine(IDVal) + " not supported yet");
1220 // Look up the handler in the handler table.
1221 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1222 DirectiveMap.lookup(IDVal);
1224 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1226 // Target hook for parsing target specific directives.
1227 if (!getTargetParser().ParseDirective(ID))
1230 bool retval = Warning(IDLoc, "ignoring directive for now");
1231 EatToEndOfStatement();
1235 CheckForValidSection();
1237 // Canonicalize the opcode to lower case.
1238 SmallString<128> Opcode;
1239 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1240 Opcode.push_back(tolower(IDVal[i]));
1242 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1243 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1246 // Dump the parsed representation, if requested.
1247 if (getShowParsedOperands()) {
1248 SmallString<256> Str;
1249 raw_svector_ostream OS(Str);
1250 OS << "parsed instruction: [";
1251 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1254 ParsedOperands[i]->print(OS);
1258 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1261 // If we are generating dwarf for assembly source files and the current
1262 // section is the initial text section then generate a .loc directive for
1264 if (!HadError && getContext().getGenDwarfForAssembly() &&
1265 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1266 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1267 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1268 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1269 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1273 // If parsing succeeded, match the instruction.
1275 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1278 // Free any parsed operands.
1279 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1280 delete ParsedOperands[i];
1282 // Don't skip the rest of the line, the instruction parser is responsible for
1287 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1288 /// since they may not be able to be tokenized to get to the end of line token.
1289 void AsmParser::EatToEndOfLine() {
1290 if (!Lexer.is(AsmToken::EndOfStatement))
1291 Lexer.LexUntilEndOfLine();
1296 /// ParseCppHashLineFilenameComment as this:
1297 /// ::= # number "filename"
1298 /// or just as a full line comment if it doesn't have a number and a string.
1299 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1300 Lex(); // Eat the hash token.
1302 if (getLexer().isNot(AsmToken::Integer)) {
1303 // Consume the line since in cases it is not a well-formed line directive,
1304 // as if were simply a full line comment.
1309 int64_t LineNumber = getTok().getIntVal();
1312 if (getLexer().isNot(AsmToken::String)) {
1317 StringRef Filename = getTok().getString();
1318 // Get rid of the enclosing quotes.
1319 Filename = Filename.substr(1, Filename.size()-2);
1321 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1323 CppHashFilename = Filename;
1324 CppHashLineNumber = LineNumber;
1326 // Ignore any trailing characters, they're just comment.
1331 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1332 /// for the Filename and LineNo if any in the diagnostic.
1333 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1334 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1335 raw_ostream &OS = errs();
1337 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1338 const SMLoc &DiagLoc = Diag.getLoc();
1339 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1340 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1342 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1343 // before printing the message.
1344 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1345 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1346 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1347 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1350 // If we have not parsed a cpp hash line filename comment or the source
1351 // manager changed or buffer changed (like in a nested include) then just
1352 // print the normal diagnostic using its Filename and LineNo.
1353 if (!Parser->CppHashLineNumber ||
1354 &DiagSrcMgr != &Parser->SrcMgr ||
1355 DiagBuf != CppHashBuf) {
1356 if (Parser->SavedDiagHandler)
1357 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1363 // Use the CppHashFilename and calculate a line number based on the
1364 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1366 const std::string Filename = Parser->CppHashFilename;
1368 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1369 int CppHashLocLineNo =
1370 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1371 int LineNo = Parser->CppHashLineNumber - 1 +
1372 (DiagLocLineNo - CppHashLocLineNo);
1374 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1375 Filename, LineNo, Diag.getColumnNo(),
1376 Diag.getKind(), Diag.getMessage(),
1377 Diag.getLineContents(), Diag.getRanges());
1379 if (Parser->SavedDiagHandler)
1380 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1382 NewDiag.print(0, OS);
1385 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1386 const std::vector<StringRef> &Parameters,
1387 const std::vector<std::vector<AsmToken> > &A,
1389 raw_svector_ostream OS(Buf);
1390 unsigned NParameters = Parameters.size();
1391 if (NParameters != 0 && NParameters != A.size())
1392 return Error(L, "Wrong number of arguments");
1394 while (!Body.empty()) {
1395 // Scan for the next substitution.
1396 std::size_t End = Body.size(), Pos = 0;
1397 for (; Pos != End; ++Pos) {
1398 // Check for a substitution or escape.
1400 // This macro has no parameters, look for $0, $1, etc.
1401 if (Body[Pos] != '$' || Pos + 1 == End)
1404 char Next = Body[Pos + 1];
1405 if (Next == '$' || Next == 'n' || isdigit(Next))
1408 // This macro has parameters, look for \foo, \bar, etc.
1409 if (Body[Pos] == '\\' && Pos + 1 != End)
1415 OS << Body.slice(0, Pos);
1417 // Check if we reached the end.
1422 switch (Body[Pos+1]) {
1428 // $n => number of arguments
1433 // $[0-9] => argument
1435 // Missing arguments are ignored.
1436 unsigned Index = Body[Pos+1] - '0';
1437 if (Index >= A.size())
1440 // Otherwise substitute with the token values, with spaces eliminated.
1441 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1442 ie = A[Index].end(); it != ie; ++it)
1443 OS << it->getString();
1449 unsigned I = Pos + 1;
1450 while (isalnum(Body[I]) && I + 1 != End)
1453 const char *Begin = Body.data() + Pos +1;
1454 StringRef Argument(Begin, I - (Pos +1));
1456 for (; Index < NParameters; ++Index)
1457 if (Parameters[Index] == Argument)
1460 // FIXME: We should error at the macro definition.
1461 if (Index == NParameters)
1462 return Error(L, "Parameter not found");
1464 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1465 ie = A[Index].end(); it != ie; ++it)
1466 OS << it->getString();
1468 Pos += 1 + Argument.size();
1470 // Update the scan point.
1471 Body = Body.substr(Pos);
1474 // We include the .endmacro in the buffer as our queue to exit the macro
1476 OS << ".endmacro\n";
1480 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1482 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1486 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1488 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1489 // this, although we should protect against infinite loops.
1490 if (ActiveMacros.size() == 20)
1491 return TokError("macros cannot be nested more than 20 levels deep");
1493 // Parse the macro instantiation arguments.
1494 std::vector<std::vector<AsmToken> > MacroArguments;
1495 MacroArguments.push_back(std::vector<AsmToken>());
1496 unsigned ParenLevel = 0;
1498 if (Lexer.is(AsmToken::Eof))
1499 return TokError("unexpected token in macro instantiation");
1500 if (Lexer.is(AsmToken::EndOfStatement))
1503 // If we aren't inside parentheses and this is a comma, start a new token
1505 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1506 MacroArguments.push_back(std::vector<AsmToken>());
1508 // Adjust the current parentheses level.
1509 if (Lexer.is(AsmToken::LParen))
1511 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1514 // Append the token to the current argument list.
1515 MacroArguments.back().push_back(getTok());
1520 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1521 // to hold the macro body with substitutions.
1522 SmallString<256> Buf;
1523 StringRef Body = M->Body;
1525 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1528 MemoryBuffer *Instantiation =
1529 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1531 // Create the macro instantiation object and add to the current macro
1532 // instantiation stack.
1533 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1536 ActiveMacros.push_back(MI);
1538 // Jump to the macro instantiation and prime the lexer.
1539 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1540 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1546 void AsmParser::HandleMacroExit() {
1547 // Jump to the EndOfStatement we should return to, and consume it.
1548 JumpToLoc(ActiveMacros.back()->ExitLoc);
1551 // Pop the instantiation entry.
1552 delete ActiveMacros.back();
1553 ActiveMacros.pop_back();
1556 static void MarkUsed(const MCExpr *Value) {
1557 switch (Value->getKind()) {
1558 case MCExpr::Binary:
1559 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1560 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1562 case MCExpr::Target:
1563 case MCExpr::Constant:
1565 case MCExpr::SymbolRef: {
1566 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1570 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1575 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1576 // FIXME: Use better location, we should use proper tokens.
1577 SMLoc EqualLoc = Lexer.getLoc();
1579 const MCExpr *Value;
1580 if (ParseExpression(Value))
1585 if (Lexer.isNot(AsmToken::EndOfStatement))
1586 return TokError("unexpected token in assignment");
1588 // Error on assignment to '.'.
1590 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1591 "(use '.space' or '.org').)"));
1594 // Eat the end of statement marker.
1597 // Validate that the LHS is allowed to be a variable (either it has not been
1598 // used as a symbol, or it is an absolute symbol).
1599 MCSymbol *Sym = getContext().LookupSymbol(Name);
1601 // Diagnose assignment to a label.
1603 // FIXME: Diagnostics. Note the location of the definition as a label.
1604 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1605 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1606 ; // Allow redefinitions of undefined symbols only used in directives.
1607 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1608 return Error(EqualLoc, "redefinition of '" + Name + "'");
1609 else if (!Sym->isVariable())
1610 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1611 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1612 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1615 // Don't count these checks as uses.
1616 Sym->setUsed(false);
1618 Sym = getContext().GetOrCreateSymbol(Name);
1620 // FIXME: Handle '.'.
1622 // Do the assignment.
1623 Out.EmitAssignment(Sym, Value);
1628 /// ParseIdentifier:
1631 bool AsmParser::ParseIdentifier(StringRef &Res) {
1632 // The assembler has relaxed rules for accepting identifiers, in particular we
1633 // allow things like '.globl $foo', which would normally be separate
1634 // tokens. At this level, we have already lexed so we cannot (currently)
1635 // handle this as a context dependent token, instead we detect adjacent tokens
1636 // and return the combined identifier.
1637 if (Lexer.is(AsmToken::Dollar)) {
1638 SMLoc DollarLoc = getLexer().getLoc();
1640 // Consume the dollar sign, and check for a following identifier.
1642 if (Lexer.isNot(AsmToken::Identifier))
1645 // We have a '$' followed by an identifier, make sure they are adjacent.
1646 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1649 // Construct the joined identifier and consume the token.
1650 Res = StringRef(DollarLoc.getPointer(),
1651 getTok().getIdentifier().size() + 1);
1656 if (Lexer.isNot(AsmToken::Identifier) &&
1657 Lexer.isNot(AsmToken::String))
1660 Res = getTok().getIdentifier();
1662 Lex(); // Consume the identifier token.
1667 /// ParseDirectiveSet:
1668 /// ::= .equ identifier ',' expression
1669 /// ::= .equiv identifier ',' expression
1670 /// ::= .set identifier ',' expression
1671 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1674 if (ParseIdentifier(Name))
1675 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1677 if (getLexer().isNot(AsmToken::Comma))
1678 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1681 return ParseAssignment(Name, allow_redef);
1684 bool AsmParser::ParseEscapedString(std::string &Data) {
1685 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1688 StringRef Str = getTok().getStringContents();
1689 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1690 if (Str[i] != '\\') {
1695 // Recognize escaped characters. Note that this escape semantics currently
1696 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1699 return TokError("unexpected backslash at end of string");
1701 // Recognize octal sequences.
1702 if ((unsigned) (Str[i] - '0') <= 7) {
1703 // Consume up to three octal characters.
1704 unsigned Value = Str[i] - '0';
1706 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1708 Value = Value * 8 + (Str[i] - '0');
1710 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1712 Value = Value * 8 + (Str[i] - '0');
1717 return TokError("invalid octal escape sequence (out of range)");
1719 Data += (unsigned char) Value;
1723 // Otherwise recognize individual escapes.
1726 // Just reject invalid escape sequences for now.
1727 return TokError("invalid escape sequence (unrecognized character)");
1729 case 'b': Data += '\b'; break;
1730 case 'f': Data += '\f'; break;
1731 case 'n': Data += '\n'; break;
1732 case 'r': Data += '\r'; break;
1733 case 't': Data += '\t'; break;
1734 case '"': Data += '"'; break;
1735 case '\\': Data += '\\'; break;
1742 /// ParseDirectiveAscii:
1743 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1744 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1745 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1746 CheckForValidSection();
1749 if (getLexer().isNot(AsmToken::String))
1750 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1753 if (ParseEscapedString(Data))
1756 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1758 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1762 if (getLexer().is(AsmToken::EndOfStatement))
1765 if (getLexer().isNot(AsmToken::Comma))
1766 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1775 /// ParseDirectiveValue
1776 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1777 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1778 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1779 CheckForValidSection();
1782 const MCExpr *Value;
1783 SMLoc ExprLoc = getLexer().getLoc();
1784 if (ParseExpression(Value))
1787 // Special case constant expressions to match code generator.
1788 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1789 assert(Size <= 8 && "Invalid size");
1790 uint64_t IntValue = MCE->getValue();
1791 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1792 return Error(ExprLoc, "literal value out of range for directive");
1793 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1795 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1797 if (getLexer().is(AsmToken::EndOfStatement))
1800 // FIXME: Improve diagnostic.
1801 if (getLexer().isNot(AsmToken::Comma))
1802 return TokError("unexpected token in directive");
1811 /// ParseDirectiveRealValue
1812 /// ::= (.single | .double) [ expression (, expression)* ]
1813 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1814 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1815 CheckForValidSection();
1818 // We don't truly support arithmetic on floating point expressions, so we
1819 // have to manually parse unary prefixes.
1821 if (getLexer().is(AsmToken::Minus)) {
1824 } else if (getLexer().is(AsmToken::Plus))
1827 if (getLexer().isNot(AsmToken::Integer) &&
1828 getLexer().isNot(AsmToken::Real) &&
1829 getLexer().isNot(AsmToken::Identifier))
1830 return TokError("unexpected token in directive");
1832 // Convert to an APFloat.
1833 APFloat Value(Semantics);
1834 StringRef IDVal = getTok().getString();
1835 if (getLexer().is(AsmToken::Identifier)) {
1836 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1837 Value = APFloat::getInf(Semantics);
1838 else if (!IDVal.compare_lower("nan"))
1839 Value = APFloat::getNaN(Semantics, false, ~0);
1841 return TokError("invalid floating point literal");
1842 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1843 APFloat::opInvalidOp)
1844 return TokError("invalid floating point literal");
1848 // Consume the numeric token.
1851 // Emit the value as an integer.
1852 APInt AsInt = Value.bitcastToAPInt();
1853 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1854 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1856 if (getLexer().is(AsmToken::EndOfStatement))
1859 if (getLexer().isNot(AsmToken::Comma))
1860 return TokError("unexpected token in directive");
1869 /// ParseDirectiveSpace
1870 /// ::= .space expression [ , expression ]
1871 bool AsmParser::ParseDirectiveSpace() {
1872 CheckForValidSection();
1875 if (ParseAbsoluteExpression(NumBytes))
1878 int64_t FillExpr = 0;
1879 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1880 if (getLexer().isNot(AsmToken::Comma))
1881 return TokError("unexpected token in '.space' directive");
1884 if (ParseAbsoluteExpression(FillExpr))
1887 if (getLexer().isNot(AsmToken::EndOfStatement))
1888 return TokError("unexpected token in '.space' directive");
1894 return TokError("invalid number of bytes in '.space' directive");
1896 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1897 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1902 /// ParseDirectiveZero
1903 /// ::= .zero expression
1904 bool AsmParser::ParseDirectiveZero() {
1905 CheckForValidSection();
1908 if (ParseAbsoluteExpression(NumBytes))
1912 if (getLexer().is(AsmToken::Comma)) {
1914 if (ParseAbsoluteExpression(Val))
1918 if (getLexer().isNot(AsmToken::EndOfStatement))
1919 return TokError("unexpected token in '.zero' directive");
1923 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1928 /// ParseDirectiveFill
1929 /// ::= .fill expression , expression , expression
1930 bool AsmParser::ParseDirectiveFill() {
1931 CheckForValidSection();
1934 if (ParseAbsoluteExpression(NumValues))
1937 if (getLexer().isNot(AsmToken::Comma))
1938 return TokError("unexpected token in '.fill' directive");
1942 if (ParseAbsoluteExpression(FillSize))
1945 if (getLexer().isNot(AsmToken::Comma))
1946 return TokError("unexpected token in '.fill' directive");
1950 if (ParseAbsoluteExpression(FillExpr))
1953 if (getLexer().isNot(AsmToken::EndOfStatement))
1954 return TokError("unexpected token in '.fill' directive");
1958 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1959 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1961 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1962 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1967 /// ParseDirectiveOrg
1968 /// ::= .org expression [ , expression ]
1969 bool AsmParser::ParseDirectiveOrg() {
1970 CheckForValidSection();
1972 const MCExpr *Offset;
1973 SMLoc Loc = getTok().getLoc();
1974 if (ParseExpression(Offset))
1977 // Parse optional fill expression.
1978 int64_t FillExpr = 0;
1979 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1980 if (getLexer().isNot(AsmToken::Comma))
1981 return TokError("unexpected token in '.org' directive");
1984 if (ParseAbsoluteExpression(FillExpr))
1987 if (getLexer().isNot(AsmToken::EndOfStatement))
1988 return TokError("unexpected token in '.org' directive");
1993 // Only limited forms of relocatable expressions are accepted here, it
1994 // has to be relative to the current section. The streamer will return
1995 // 'true' if the expression wasn't evaluatable.
1996 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
1997 return Error(Loc, "expected assembly-time absolute expression");
2002 /// ParseDirectiveAlign
2003 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2004 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2005 CheckForValidSection();
2007 SMLoc AlignmentLoc = getLexer().getLoc();
2009 if (ParseAbsoluteExpression(Alignment))
2013 bool HasFillExpr = false;
2014 int64_t FillExpr = 0;
2015 int64_t MaxBytesToFill = 0;
2016 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2017 if (getLexer().isNot(AsmToken::Comma))
2018 return TokError("unexpected token in directive");
2021 // The fill expression can be omitted while specifying a maximum number of
2022 // alignment bytes, e.g:
2024 if (getLexer().isNot(AsmToken::Comma)) {
2026 if (ParseAbsoluteExpression(FillExpr))
2030 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2031 if (getLexer().isNot(AsmToken::Comma))
2032 return TokError("unexpected token in directive");
2035 MaxBytesLoc = getLexer().getLoc();
2036 if (ParseAbsoluteExpression(MaxBytesToFill))
2039 if (getLexer().isNot(AsmToken::EndOfStatement))
2040 return TokError("unexpected token in directive");
2049 // Compute alignment in bytes.
2051 // FIXME: Diagnose overflow.
2052 if (Alignment >= 32) {
2053 Error(AlignmentLoc, "invalid alignment value");
2057 Alignment = 1ULL << Alignment;
2060 // Diagnose non-sensical max bytes to align.
2061 if (MaxBytesLoc.isValid()) {
2062 if (MaxBytesToFill < 1) {
2063 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2064 "many bytes, ignoring maximum bytes expression");
2068 if (MaxBytesToFill >= Alignment) {
2069 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2075 // Check whether we should use optimal code alignment for this .align
2077 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2078 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2079 ValueSize == 1 && UseCodeAlign) {
2080 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2082 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2083 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2090 /// ParseDirectiveSymbolAttribute
2091 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2092 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2093 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2096 SMLoc Loc = getTok().getLoc();
2098 if (ParseIdentifier(Name))
2099 return Error(Loc, "expected identifier in directive");
2101 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2103 // Assembler local symbols don't make any sense here. Complain loudly.
2104 if (Sym->isTemporary())
2105 return Error(Loc, "non-local symbol required in directive");
2107 getStreamer().EmitSymbolAttribute(Sym, Attr);
2109 if (getLexer().is(AsmToken::EndOfStatement))
2112 if (getLexer().isNot(AsmToken::Comma))
2113 return TokError("unexpected token in directive");
2122 /// ParseDirectiveComm
2123 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2124 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2125 CheckForValidSection();
2127 SMLoc IDLoc = getLexer().getLoc();
2129 if (ParseIdentifier(Name))
2130 return TokError("expected identifier in directive");
2132 // Handle the identifier as the key symbol.
2133 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2135 if (getLexer().isNot(AsmToken::Comma))
2136 return TokError("unexpected token in directive");
2140 SMLoc SizeLoc = getLexer().getLoc();
2141 if (ParseAbsoluteExpression(Size))
2144 int64_t Pow2Alignment = 0;
2145 SMLoc Pow2AlignmentLoc;
2146 if (getLexer().is(AsmToken::Comma)) {
2148 Pow2AlignmentLoc = getLexer().getLoc();
2149 if (ParseAbsoluteExpression(Pow2Alignment))
2152 // If this target takes alignments in bytes (not log) validate and convert.
2153 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2154 if (!isPowerOf2_64(Pow2Alignment))
2155 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2156 Pow2Alignment = Log2_64(Pow2Alignment);
2160 if (getLexer().isNot(AsmToken::EndOfStatement))
2161 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2165 // NOTE: a size of zero for a .comm should create a undefined symbol
2166 // but a size of .lcomm creates a bss symbol of size zero.
2168 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2169 "be less than zero");
2171 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2172 // may internally end up wanting an alignment in bytes.
2173 // FIXME: Diagnose overflow.
2174 if (Pow2Alignment < 0)
2175 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2176 "alignment, can't be less than zero");
2178 if (!Sym->isUndefined())
2179 return Error(IDLoc, "invalid symbol redefinition");
2181 // '.lcomm' is equivalent to '.zerofill'.
2182 // Create the Symbol as a common or local common with Size and Pow2Alignment
2184 getStreamer().EmitZerofill(Ctx.getMachOSection(
2185 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2186 0, SectionKind::getBSS()),
2187 Sym, Size, 1 << Pow2Alignment);
2191 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2195 /// ParseDirectiveAbort
2196 /// ::= .abort [... message ...]
2197 bool AsmParser::ParseDirectiveAbort() {
2198 // FIXME: Use loc from directive.
2199 SMLoc Loc = getLexer().getLoc();
2201 StringRef Str = ParseStringToEndOfStatement();
2202 if (getLexer().isNot(AsmToken::EndOfStatement))
2203 return TokError("unexpected token in '.abort' directive");
2208 Error(Loc, ".abort detected. Assembly stopping.");
2210 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2211 // FIXME: Actually abort assembly here.
2216 /// ParseDirectiveInclude
2217 /// ::= .include "filename"
2218 bool AsmParser::ParseDirectiveInclude() {
2219 if (getLexer().isNot(AsmToken::String))
2220 return TokError("expected string in '.include' directive");
2222 std::string Filename = getTok().getString();
2223 SMLoc IncludeLoc = getLexer().getLoc();
2226 if (getLexer().isNot(AsmToken::EndOfStatement))
2227 return TokError("unexpected token in '.include' directive");
2229 // Strip the quotes.
2230 Filename = Filename.substr(1, Filename.size()-2);
2232 // Attempt to switch the lexer to the included file before consuming the end
2233 // of statement to avoid losing it when we switch.
2234 if (EnterIncludeFile(Filename)) {
2235 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2242 /// ParseDirectiveIncbin
2243 /// ::= .incbin "filename"
2244 bool AsmParser::ParseDirectiveIncbin() {
2245 if (getLexer().isNot(AsmToken::String))
2246 return TokError("expected string in '.incbin' directive");
2248 std::string Filename = getTok().getString();
2249 SMLoc IncbinLoc = getLexer().getLoc();
2252 if (getLexer().isNot(AsmToken::EndOfStatement))
2253 return TokError("unexpected token in '.incbin' directive");
2255 // Strip the quotes.
2256 Filename = Filename.substr(1, Filename.size()-2);
2258 // Attempt to process the included file.
2259 if (ProcessIncbinFile(Filename)) {
2260 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2267 /// ParseDirectiveIf
2268 /// ::= .if expression
2269 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2270 TheCondStack.push_back(TheCondState);
2271 TheCondState.TheCond = AsmCond::IfCond;
2272 if(TheCondState.Ignore) {
2273 EatToEndOfStatement();
2277 if (ParseAbsoluteExpression(ExprValue))
2280 if (getLexer().isNot(AsmToken::EndOfStatement))
2281 return TokError("unexpected token in '.if' directive");
2285 TheCondState.CondMet = ExprValue;
2286 TheCondState.Ignore = !TheCondState.CondMet;
2292 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2294 TheCondStack.push_back(TheCondState);
2295 TheCondState.TheCond = AsmCond::IfCond;
2297 if (TheCondState.Ignore) {
2298 EatToEndOfStatement();
2300 if (ParseIdentifier(Name))
2301 return TokError("expected identifier after '.ifdef'");
2305 MCSymbol *Sym = getContext().LookupSymbol(Name);
2308 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2310 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2311 TheCondState.Ignore = !TheCondState.CondMet;
2317 /// ParseDirectiveElseIf
2318 /// ::= .elseif expression
2319 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2320 if (TheCondState.TheCond != AsmCond::IfCond &&
2321 TheCondState.TheCond != AsmCond::ElseIfCond)
2322 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2324 TheCondState.TheCond = AsmCond::ElseIfCond;
2326 bool LastIgnoreState = false;
2327 if (!TheCondStack.empty())
2328 LastIgnoreState = TheCondStack.back().Ignore;
2329 if (LastIgnoreState || TheCondState.CondMet) {
2330 TheCondState.Ignore = true;
2331 EatToEndOfStatement();
2335 if (ParseAbsoluteExpression(ExprValue))
2338 if (getLexer().isNot(AsmToken::EndOfStatement))
2339 return TokError("unexpected token in '.elseif' directive");
2342 TheCondState.CondMet = ExprValue;
2343 TheCondState.Ignore = !TheCondState.CondMet;
2349 /// ParseDirectiveElse
2351 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2352 if (getLexer().isNot(AsmToken::EndOfStatement))
2353 return TokError("unexpected token in '.else' directive");
2357 if (TheCondState.TheCond != AsmCond::IfCond &&
2358 TheCondState.TheCond != AsmCond::ElseIfCond)
2359 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2361 TheCondState.TheCond = AsmCond::ElseCond;
2362 bool LastIgnoreState = false;
2363 if (!TheCondStack.empty())
2364 LastIgnoreState = TheCondStack.back().Ignore;
2365 if (LastIgnoreState || TheCondState.CondMet)
2366 TheCondState.Ignore = true;
2368 TheCondState.Ignore = false;
2373 /// ParseDirectiveEndIf
2375 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2376 if (getLexer().isNot(AsmToken::EndOfStatement))
2377 return TokError("unexpected token in '.endif' directive");
2381 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2382 TheCondStack.empty())
2383 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2385 if (!TheCondStack.empty()) {
2386 TheCondState = TheCondStack.back();
2387 TheCondStack.pop_back();
2393 /// ParseDirectiveFile
2394 /// ::= .file [number] filename
2395 /// ::= .file number directory filename
2396 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2397 // FIXME: I'm not sure what this is.
2398 int64_t FileNumber = -1;
2399 SMLoc FileNumberLoc = getLexer().getLoc();
2400 if (getLexer().is(AsmToken::Integer)) {
2401 FileNumber = getTok().getIntVal();
2405 return TokError("file number less than one");
2408 if (getLexer().isNot(AsmToken::String))
2409 return TokError("unexpected token in '.file' directive");
2411 // Usually the directory and filename together, otherwise just the directory.
2412 StringRef Path = getTok().getString();
2413 Path = Path.substr(1, Path.size()-2);
2416 StringRef Directory;
2418 if (getLexer().is(AsmToken::String)) {
2419 if (FileNumber == -1)
2420 return TokError("explicit path specified, but no file number");
2421 Filename = getTok().getString();
2422 Filename = Filename.substr(1, Filename.size()-2);
2429 if (getLexer().isNot(AsmToken::EndOfStatement))
2430 return TokError("unexpected token in '.file' directive");
2432 if (FileNumber == -1)
2433 getStreamer().EmitFileDirective(Filename);
2435 if (getContext().getGenDwarfForAssembly() == true)
2436 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2437 "used to generate dwarf debug info for assembly code");
2439 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2440 Error(FileNumberLoc, "file number already allocated");
2446 /// ParseDirectiveLine
2447 /// ::= .line [number]
2448 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2449 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2450 if (getLexer().isNot(AsmToken::Integer))
2451 return TokError("unexpected token in '.line' directive");
2453 int64_t LineNumber = getTok().getIntVal();
2457 // FIXME: Do something with the .line.
2460 if (getLexer().isNot(AsmToken::EndOfStatement))
2461 return TokError("unexpected token in '.line' directive");
2467 /// ParseDirectiveLoc
2468 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2469 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2470 /// The first number is a file number, must have been previously assigned with
2471 /// a .file directive, the second number is the line number and optionally the
2472 /// third number is a column position (zero if not specified). The remaining
2473 /// optional items are .loc sub-directives.
2474 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2476 if (getLexer().isNot(AsmToken::Integer))
2477 return TokError("unexpected token in '.loc' directive");
2478 int64_t FileNumber = getTok().getIntVal();
2480 return TokError("file number less than one in '.loc' directive");
2481 if (!getContext().isValidDwarfFileNumber(FileNumber))
2482 return TokError("unassigned file number in '.loc' directive");
2485 int64_t LineNumber = 0;
2486 if (getLexer().is(AsmToken::Integer)) {
2487 LineNumber = getTok().getIntVal();
2489 return TokError("line number less than one in '.loc' directive");
2493 int64_t ColumnPos = 0;
2494 if (getLexer().is(AsmToken::Integer)) {
2495 ColumnPos = getTok().getIntVal();
2497 return TokError("column position less than zero in '.loc' directive");
2501 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2503 int64_t Discriminator = 0;
2504 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2506 if (getLexer().is(AsmToken::EndOfStatement))
2510 SMLoc Loc = getTok().getLoc();
2511 if (getParser().ParseIdentifier(Name))
2512 return TokError("unexpected token in '.loc' directive");
2514 if (Name == "basic_block")
2515 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2516 else if (Name == "prologue_end")
2517 Flags |= DWARF2_FLAG_PROLOGUE_END;
2518 else if (Name == "epilogue_begin")
2519 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2520 else if (Name == "is_stmt") {
2521 SMLoc Loc = getTok().getLoc();
2522 const MCExpr *Value;
2523 if (getParser().ParseExpression(Value))
2525 // The expression must be the constant 0 or 1.
2526 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2527 int Value = MCE->getValue();
2529 Flags &= ~DWARF2_FLAG_IS_STMT;
2530 else if (Value == 1)
2531 Flags |= DWARF2_FLAG_IS_STMT;
2533 return Error(Loc, "is_stmt value not 0 or 1");
2536 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2539 else if (Name == "isa") {
2540 SMLoc Loc = getTok().getLoc();
2541 const MCExpr *Value;
2542 if (getParser().ParseExpression(Value))
2544 // The expression must be a constant greater or equal to 0.
2545 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2546 int Value = MCE->getValue();
2548 return Error(Loc, "isa number less than zero");
2552 return Error(Loc, "isa number not a constant value");
2555 else if (Name == "discriminator") {
2556 if (getParser().ParseAbsoluteExpression(Discriminator))
2560 return Error(Loc, "unknown sub-directive in '.loc' directive");
2563 if (getLexer().is(AsmToken::EndOfStatement))
2568 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2569 Isa, Discriminator, StringRef());
2574 /// ParseDirectiveStabs
2575 /// ::= .stabs string, number, number, number
2576 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2577 SMLoc DirectiveLoc) {
2578 return TokError("unsupported directive '" + Directive + "'");
2581 /// ParseDirectiveCFISections
2582 /// ::= .cfi_sections section [, section]
2583 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2584 SMLoc DirectiveLoc) {
2589 if (getParser().ParseIdentifier(Name))
2590 return TokError("Expected an identifier");
2592 if (Name == ".eh_frame")
2594 else if (Name == ".debug_frame")
2597 if (getLexer().is(AsmToken::Comma)) {
2600 if (getParser().ParseIdentifier(Name))
2601 return TokError("Expected an identifier");
2603 if (Name == ".eh_frame")
2605 else if (Name == ".debug_frame")
2609 getStreamer().EmitCFISections(EH, Debug);
2614 /// ParseDirectiveCFIStartProc
2615 /// ::= .cfi_startproc
2616 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2617 SMLoc DirectiveLoc) {
2618 getStreamer().EmitCFIStartProc();
2622 /// ParseDirectiveCFIEndProc
2623 /// ::= .cfi_endproc
2624 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2625 getStreamer().EmitCFIEndProc();
2629 /// ParseRegisterOrRegisterNumber - parse register name or number.
2630 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2631 SMLoc DirectiveLoc) {
2634 if (getLexer().isNot(AsmToken::Integer)) {
2635 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2638 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2640 return getParser().ParseAbsoluteExpression(Register);
2645 /// ParseDirectiveCFIDefCfa
2646 /// ::= .cfi_def_cfa register, offset
2647 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2648 SMLoc DirectiveLoc) {
2649 int64_t Register = 0;
2650 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2653 if (getLexer().isNot(AsmToken::Comma))
2654 return TokError("unexpected token in directive");
2658 if (getParser().ParseAbsoluteExpression(Offset))
2661 getStreamer().EmitCFIDefCfa(Register, Offset);
2665 /// ParseDirectiveCFIDefCfaOffset
2666 /// ::= .cfi_def_cfa_offset offset
2667 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2668 SMLoc DirectiveLoc) {
2670 if (getParser().ParseAbsoluteExpression(Offset))
2673 getStreamer().EmitCFIDefCfaOffset(Offset);
2677 /// ParseDirectiveCFIAdjustCfaOffset
2678 /// ::= .cfi_adjust_cfa_offset adjustment
2679 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2680 SMLoc DirectiveLoc) {
2681 int64_t Adjustment = 0;
2682 if (getParser().ParseAbsoluteExpression(Adjustment))
2685 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2689 /// ParseDirectiveCFIDefCfaRegister
2690 /// ::= .cfi_def_cfa_register register
2691 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2692 SMLoc DirectiveLoc) {
2693 int64_t Register = 0;
2694 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2697 getStreamer().EmitCFIDefCfaRegister(Register);
2701 /// ParseDirectiveCFIOffset
2702 /// ::= .cfi_offset register, offset
2703 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2704 int64_t Register = 0;
2707 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2710 if (getLexer().isNot(AsmToken::Comma))
2711 return TokError("unexpected token in directive");
2714 if (getParser().ParseAbsoluteExpression(Offset))
2717 getStreamer().EmitCFIOffset(Register, Offset);
2721 /// ParseDirectiveCFIRelOffset
2722 /// ::= .cfi_rel_offset register, offset
2723 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2724 SMLoc DirectiveLoc) {
2725 int64_t Register = 0;
2727 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2730 if (getLexer().isNot(AsmToken::Comma))
2731 return TokError("unexpected token in directive");
2735 if (getParser().ParseAbsoluteExpression(Offset))
2738 getStreamer().EmitCFIRelOffset(Register, Offset);
2742 static bool isValidEncoding(int64_t Encoding) {
2743 if (Encoding & ~0xff)
2746 if (Encoding == dwarf::DW_EH_PE_omit)
2749 const unsigned Format = Encoding & 0xf;
2750 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2751 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2752 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2753 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2756 const unsigned Application = Encoding & 0x70;
2757 if (Application != dwarf::DW_EH_PE_absptr &&
2758 Application != dwarf::DW_EH_PE_pcrel)
2764 /// ParseDirectiveCFIPersonalityOrLsda
2765 /// ::= .cfi_personality encoding, [symbol_name]
2766 /// ::= .cfi_lsda encoding, [symbol_name]
2767 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2768 SMLoc DirectiveLoc) {
2769 int64_t Encoding = 0;
2770 if (getParser().ParseAbsoluteExpression(Encoding))
2772 if (Encoding == dwarf::DW_EH_PE_omit)
2775 if (!isValidEncoding(Encoding))
2776 return TokError("unsupported encoding.");
2778 if (getLexer().isNot(AsmToken::Comma))
2779 return TokError("unexpected token in directive");
2783 if (getParser().ParseIdentifier(Name))
2784 return TokError("expected identifier in directive");
2786 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2788 if (IDVal == ".cfi_personality")
2789 getStreamer().EmitCFIPersonality(Sym, Encoding);
2791 assert(IDVal == ".cfi_lsda");
2792 getStreamer().EmitCFILsda(Sym, Encoding);
2797 /// ParseDirectiveCFIRememberState
2798 /// ::= .cfi_remember_state
2799 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2800 SMLoc DirectiveLoc) {
2801 getStreamer().EmitCFIRememberState();
2805 /// ParseDirectiveCFIRestoreState
2806 /// ::= .cfi_remember_state
2807 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2808 SMLoc DirectiveLoc) {
2809 getStreamer().EmitCFIRestoreState();
2813 /// ParseDirectiveCFISameValue
2814 /// ::= .cfi_same_value register
2815 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2816 SMLoc DirectiveLoc) {
2817 int64_t Register = 0;
2819 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2822 getStreamer().EmitCFISameValue(Register);
2827 /// ParseDirectiveCFIRestore
2828 /// ::= .cfi_restore register
2829 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2830 SMLoc DirectiveLoc) {
2831 int64_t Register = 0;
2832 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2835 getStreamer().EmitCFIRestore(Register);
2840 /// ParseDirectiveCFIEscape
2841 /// ::= .cfi_escape expression[,...]
2842 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2843 SMLoc DirectiveLoc) {
2846 if (getParser().ParseAbsoluteExpression(CurrValue))
2849 Values.push_back((uint8_t)CurrValue);
2851 while (getLexer().is(AsmToken::Comma)) {
2854 if (getParser().ParseAbsoluteExpression(CurrValue))
2857 Values.push_back((uint8_t)CurrValue);
2860 getStreamer().EmitCFIEscape(Values);
2864 /// ParseDirectiveCFISignalFrame
2865 /// ::= .cfi_signal_frame
2866 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2867 SMLoc DirectiveLoc) {
2868 if (getLexer().isNot(AsmToken::EndOfStatement))
2869 return Error(getLexer().getLoc(),
2870 "unexpected token in '" + Directive + "' directive");
2872 getStreamer().EmitCFISignalFrame();
2877 /// ParseDirectiveMacrosOnOff
2880 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2881 SMLoc DirectiveLoc) {
2882 if (getLexer().isNot(AsmToken::EndOfStatement))
2883 return Error(getLexer().getLoc(),
2884 "unexpected token in '" + Directive + "' directive");
2886 getParser().MacrosEnabled = Directive == ".macros_on";
2891 /// ParseDirectiveMacro
2892 /// ::= .macro name [parameters]
2893 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2894 SMLoc DirectiveLoc) {
2896 if (getParser().ParseIdentifier(Name))
2897 return TokError("expected identifier in directive");
2899 std::vector<StringRef> Parameters;
2900 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2902 StringRef Parameter;
2903 if (getParser().ParseIdentifier(Parameter))
2904 return TokError("expected identifier in directive");
2905 Parameters.push_back(Parameter);
2907 if (getLexer().isNot(AsmToken::Comma))
2913 if (getLexer().isNot(AsmToken::EndOfStatement))
2914 return TokError("unexpected token in '.macro' directive");
2916 // Eat the end of statement.
2919 AsmToken EndToken, StartToken = getTok();
2921 // Lex the macro definition.
2923 // Check whether we have reached the end of the file.
2924 if (getLexer().is(AsmToken::Eof))
2925 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2927 // Otherwise, check whether we have reach the .endmacro.
2928 if (getLexer().is(AsmToken::Identifier) &&
2929 (getTok().getIdentifier() == ".endm" ||
2930 getTok().getIdentifier() == ".endmacro")) {
2931 EndToken = getTok();
2933 if (getLexer().isNot(AsmToken::EndOfStatement))
2934 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2939 // Otherwise, scan til the end of the statement.
2940 getParser().EatToEndOfStatement();
2943 if (getParser().MacroMap.lookup(Name)) {
2944 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2947 const char *BodyStart = StartToken.getLoc().getPointer();
2948 const char *BodyEnd = EndToken.getLoc().getPointer();
2949 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2950 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2954 /// ParseDirectiveEndMacro
2957 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2958 SMLoc DirectiveLoc) {
2959 if (getLexer().isNot(AsmToken::EndOfStatement))
2960 return TokError("unexpected token in '" + Directive + "' directive");
2962 // If we are inside a macro instantiation, terminate the current
2964 if (!getParser().ActiveMacros.empty()) {
2965 getParser().HandleMacroExit();
2969 // Otherwise, this .endmacro is a stray entry in the file; well formed
2970 // .endmacro directives are handled during the macro definition parsing.
2971 return TokError("unexpected '" + Directive + "' in file, "
2972 "no current macro definition");
2975 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2976 getParser().CheckForValidSection();
2978 const MCExpr *Value;
2980 if (getParser().ParseExpression(Value))
2983 if (getLexer().isNot(AsmToken::EndOfStatement))
2984 return TokError("unexpected token in directive");
2986 if (DirName[1] == 's')
2987 getStreamer().EmitSLEB128Value(Value);
2989 getStreamer().EmitULEB128Value(Value);
2995 /// \brief Create an MCAsmParser instance.
2996 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
2997 MCContext &C, MCStreamer &Out,
2998 const MCAsmInfo &MAI) {
2999 return new AsmParser(SM, C, Out, MAI);