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 bool ParseAssignment(StringRef Name, bool allow_redef);
214 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
215 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
216 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
217 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
219 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
220 /// and set \arg Res to the identifier contents.
221 bool ParseIdentifier(StringRef &Res);
223 // Directive Parsing.
225 // ".ascii", ".asciiz", ".string"
226 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
227 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
228 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
229 bool ParseDirectiveFill(); // ".fill"
230 bool ParseDirectiveSpace(); // ".space"
231 bool ParseDirectiveZero(); // ".zero"
232 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
233 bool ParseDirectiveOrg(); // ".org"
234 // ".align{,32}", ".p2align{,w,l}"
235 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
237 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
238 /// accepts a single symbol (which should be a label or an external).
239 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
241 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
243 bool ParseDirectiveAbort(); // ".abort"
244 bool ParseDirectiveInclude(); // ".include"
245 bool ParseDirectiveIncbin(); // ".incbin"
247 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
248 // ".ifb" or ".ifnb", depending on ExpectBlank.
249 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
250 // ".ifdef" or ".ifndef", depending on expect_defined
251 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
252 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
253 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
254 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
256 /// ParseEscapedString - Parse the current token as a string which may include
257 /// escaped characters and return the string contents.
258 bool ParseEscapedString(std::string &Data);
260 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
261 MCSymbolRefExpr::VariantKind Variant);
264 /// \brief Generic implementations of directive handling, etc. which is shared
265 /// (or the default, at least) for all assembler parser.
266 class GenericAsmParser : public MCAsmParserExtension {
267 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
268 void AddDirectiveHandler(StringRef Directive) {
269 getParser().AddDirectiveHandler(this, Directive,
270 HandleDirective<GenericAsmParser, Handler>);
273 GenericAsmParser() {}
275 AsmParser &getParser() {
276 return (AsmParser&) this->MCAsmParserExtension::getParser();
279 virtual void Initialize(MCAsmParser &Parser) {
280 // Call the base implementation.
281 this->MCAsmParserExtension::Initialize(Parser);
283 // Debugging directives.
284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
285 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
287 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
294 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
296 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
298 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
299 ".cfi_def_cfa_offset");
300 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
301 ".cfi_adjust_cfa_offset");
302 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
303 ".cfi_def_cfa_register");
304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
309 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
311 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
313 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
315 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
317 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
319 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
321 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
323 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
326 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
328 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
330 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
331 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
332 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
334 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
335 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
338 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
340 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
341 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
342 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
343 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
344 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
345 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
346 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
347 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
348 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
349 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
350 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
351 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
352 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
353 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
354 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
355 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
356 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
357 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
358 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
359 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
361 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
362 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
363 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
365 bool ParseDirectiveLEB128(StringRef, SMLoc);
372 extern MCAsmParserExtension *createDarwinAsmParser();
373 extern MCAsmParserExtension *createELFAsmParser();
374 extern MCAsmParserExtension *createCOFFAsmParser();
378 enum { DEFAULT_ADDRSPACE = 0 };
380 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
381 MCStreamer &_Out, const MCAsmInfo &_MAI)
382 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
383 GenericParser(new GenericAsmParser), PlatformParser(0),
384 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
385 AssemblerDialect(~0U) {
386 // Save the old handler.
387 SavedDiagHandler = SrcMgr.getDiagHandler();
388 SavedDiagContext = SrcMgr.getDiagContext();
389 // Set our own handler which calls the saved handler.
390 SrcMgr.setDiagHandler(DiagHandler, this);
391 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
393 // Initialize the generic parser.
394 GenericParser->Initialize(*this);
396 // Initialize the platform / file format parser.
398 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
400 if (_MAI.hasMicrosoftFastStdCallMangling()) {
401 PlatformParser = createCOFFAsmParser();
402 PlatformParser->Initialize(*this);
403 } else if (_MAI.hasSubsectionsViaSymbols()) {
404 PlatformParser = createDarwinAsmParser();
405 PlatformParser->Initialize(*this);
407 PlatformParser = createELFAsmParser();
408 PlatformParser->Initialize(*this);
412 AsmParser::~AsmParser() {
413 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
415 // Destroy any macros.
416 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
417 ie = MacroMap.end(); it != ie; ++it)
418 delete it->getValue();
420 delete PlatformParser;
421 delete GenericParser;
424 void AsmParser::PrintMacroInstantiations() {
425 // Print the active macro instantiation stack.
426 for (std::vector<MacroInstantiation*>::const_reverse_iterator
427 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
428 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
429 "while in macro instantiation");
432 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
433 if (FatalAssemblerWarnings)
434 return Error(L, Msg, Ranges);
435 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
436 PrintMacroInstantiations();
440 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
442 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
443 PrintMacroInstantiations();
447 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
448 std::string IncludedFile;
449 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
455 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
460 /// Process the specified .incbin file by seaching for it in the include paths
461 /// then just emiting the byte contents of the file to the streamer. This
462 /// returns true on failure.
463 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
464 std::string IncludedFile;
465 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
469 // Pick up the bytes from the file and emit them.
470 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
475 void AsmParser::JumpToLoc(SMLoc Loc) {
476 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
477 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
480 const AsmToken &AsmParser::Lex() {
481 const AsmToken *tok = &Lexer.Lex();
483 if (tok->is(AsmToken::Eof)) {
484 // If this is the end of an included file, pop the parent file off the
486 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
487 if (ParentIncludeLoc != SMLoc()) {
488 JumpToLoc(ParentIncludeLoc);
493 if (tok->is(AsmToken::Error))
494 Error(Lexer.getErrLoc(), Lexer.getErr());
499 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
500 // Create the initial section, if requested.
501 if (!NoInitialTextSection)
508 AsmCond StartingCondState = TheCondState;
510 // If we are generating dwarf for assembly source files save the initial text
511 // section and generate a .file directive.
512 if (getContext().getGenDwarfForAssembly()) {
513 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
514 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
515 getStreamer().EmitLabel(SectionStartSym);
516 getContext().setGenDwarfSectionStartSym(SectionStartSym);
517 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
518 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
521 // While we have input, parse each statement.
522 while (Lexer.isNot(AsmToken::Eof)) {
523 if (!ParseStatement()) continue;
525 // We had an error, validate that one was emitted and recover by skipping to
527 assert(HadError && "Parse statement returned an error, but none emitted!");
528 EatToEndOfStatement();
531 if (TheCondState.TheCond != StartingCondState.TheCond ||
532 TheCondState.Ignore != StartingCondState.Ignore)
533 return TokError("unmatched .ifs or .elses");
535 // Check to see there are no empty DwarfFile slots.
536 const std::vector<MCDwarfFile *> &MCDwarfFiles =
537 getContext().getMCDwarfFiles();
538 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
539 if (!MCDwarfFiles[i])
540 TokError("unassigned file number: " + Twine(i) + " for .file directives");
543 // Check to see that all assembler local symbols were actually defined.
544 // Targets that don't do subsections via symbols may not want this, though,
545 // so conservatively exclude them. Only do this if we're finalizing, though,
546 // as otherwise we won't necessarilly have seen everything yet.
547 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
548 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
549 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
552 MCSymbol *Sym = i->getValue();
553 // Variable symbols may not be marked as defined, so check those
554 // explicitly. If we know it's a variable, we have a definition for
555 // the purposes of this check.
556 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
557 // FIXME: We would really like to refer back to where the symbol was
558 // first referenced for a source location. We need to add something
559 // to track that. Currently, we just point to the end of the file.
560 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
561 "assembler local symbol '" + Sym->getName() +
567 // Finalize the output stream if there are no errors and if the client wants
569 if (!HadError && !NoFinalize)
575 void AsmParser::CheckForValidSection() {
576 if (!getStreamer().getCurrentSection()) {
577 TokError("expected section directive before assembly directive");
578 Out.SwitchSection(Ctx.getMachOSection(
580 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
581 0, SectionKind::getText()));
585 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
586 void AsmParser::EatToEndOfStatement() {
587 while (Lexer.isNot(AsmToken::EndOfStatement) &&
588 Lexer.isNot(AsmToken::Eof))
592 if (Lexer.is(AsmToken::EndOfStatement))
596 StringRef AsmParser::ParseStringToEndOfStatement() {
597 const char *Start = getTok().getLoc().getPointer();
599 while (Lexer.isNot(AsmToken::EndOfStatement) &&
600 Lexer.isNot(AsmToken::Eof))
603 const char *End = getTok().getLoc().getPointer();
604 return StringRef(Start, End - Start);
607 /// ParseParenExpr - Parse a paren expression and return it.
608 /// NOTE: This assumes the leading '(' has already been consumed.
610 /// parenexpr ::= expr)
612 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
613 if (ParseExpression(Res)) return true;
614 if (Lexer.isNot(AsmToken::RParen))
615 return TokError("expected ')' in parentheses expression");
616 EndLoc = Lexer.getLoc();
621 /// ParseBracketExpr - Parse a bracket expression and return it.
622 /// NOTE: This assumes the leading '[' has already been consumed.
624 /// bracketexpr ::= expr]
626 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
627 if (ParseExpression(Res)) return true;
628 if (Lexer.isNot(AsmToken::RBrac))
629 return TokError("expected ']' in brackets expression");
630 EndLoc = Lexer.getLoc();
635 /// ParsePrimaryExpr - Parse a primary expression and return it.
636 /// primaryexpr ::= (parenexpr
637 /// primaryexpr ::= symbol
638 /// primaryexpr ::= number
639 /// primaryexpr ::= '.'
640 /// primaryexpr ::= ~,+,- primaryexpr
641 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
642 switch (Lexer.getKind()) {
644 return TokError("unknown token in expression");
645 // If we have an error assume that we've already handled it.
646 case AsmToken::Error:
648 case AsmToken::Exclaim:
649 Lex(); // Eat the operator.
650 if (ParsePrimaryExpr(Res, EndLoc))
652 Res = MCUnaryExpr::CreateLNot(Res, getContext());
654 case AsmToken::Dollar:
655 case AsmToken::String:
656 case AsmToken::Identifier: {
657 EndLoc = Lexer.getLoc();
659 StringRef Identifier;
660 if (ParseIdentifier(Identifier))
663 // This is a symbol reference.
664 std::pair<StringRef, StringRef> Split = Identifier.split('@');
665 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
667 // Lookup the symbol variant if used.
668 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
669 if (Split.first.size() != Identifier.size()) {
670 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
671 if (Variant == MCSymbolRefExpr::VK_Invalid) {
672 Variant = MCSymbolRefExpr::VK_None;
673 return TokError("invalid variant '" + Split.second + "'");
677 // If this is an absolute variable reference, substitute it now to preserve
678 // semantics in the face of reassignment.
679 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
681 return Error(EndLoc, "unexpected modifier on variable reference");
683 Res = Sym->getVariableValue();
687 // Otherwise create a symbol ref.
688 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
691 case AsmToken::Integer: {
692 SMLoc Loc = getTok().getLoc();
693 int64_t IntVal = getTok().getIntVal();
694 Res = MCConstantExpr::Create(IntVal, getContext());
695 EndLoc = Lexer.getLoc();
697 // Look for 'b' or 'f' following an Integer as a directional label
698 if (Lexer.getKind() == AsmToken::Identifier) {
699 StringRef IDVal = getTok().getString();
700 if (IDVal == "f" || IDVal == "b"){
701 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
702 IDVal == "f" ? 1 : 0);
703 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
705 if(IDVal == "b" && Sym->isUndefined())
706 return Error(Loc, "invalid reference to undefined symbol");
707 EndLoc = Lexer.getLoc();
708 Lex(); // Eat identifier.
713 case AsmToken::Real: {
714 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
715 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
716 Res = MCConstantExpr::Create(IntVal, getContext());
720 case AsmToken::Dot: {
721 // This is a '.' reference, which references the current PC. Emit a
722 // temporary label to the streamer and refer to it.
723 MCSymbol *Sym = Ctx.CreateTempSymbol();
725 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
726 EndLoc = Lexer.getLoc();
727 Lex(); // Eat identifier.
730 case AsmToken::LParen:
731 Lex(); // Eat the '('.
732 return ParseParenExpr(Res, EndLoc);
733 case AsmToken::LBrac:
734 if (!PlatformParser->HasBracketExpressions())
735 return TokError("brackets expression not supported on this target");
736 Lex(); // Eat the '['.
737 return ParseBracketExpr(Res, EndLoc);
738 case AsmToken::Minus:
739 Lex(); // Eat the operator.
740 if (ParsePrimaryExpr(Res, EndLoc))
742 Res = MCUnaryExpr::CreateMinus(Res, getContext());
745 Lex(); // Eat the operator.
746 if (ParsePrimaryExpr(Res, EndLoc))
748 Res = MCUnaryExpr::CreatePlus(Res, getContext());
750 case AsmToken::Tilde:
751 Lex(); // Eat the operator.
752 if (ParsePrimaryExpr(Res, EndLoc))
754 Res = MCUnaryExpr::CreateNot(Res, getContext());
759 bool AsmParser::ParseExpression(const MCExpr *&Res) {
761 return ParseExpression(Res, EndLoc);
765 AsmParser::ApplyModifierToExpr(const MCExpr *E,
766 MCSymbolRefExpr::VariantKind Variant) {
767 // Recurse over the given expression, rebuilding it to apply the given variant
768 // if there is exactly one symbol.
769 switch (E->getKind()) {
771 case MCExpr::Constant:
774 case MCExpr::SymbolRef: {
775 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
777 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
778 TokError("invalid variant on expression '" +
779 getTok().getIdentifier() + "' (already modified)");
783 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
786 case MCExpr::Unary: {
787 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
788 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
791 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
794 case MCExpr::Binary: {
795 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
796 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
797 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
802 if (!LHS) LHS = BE->getLHS();
803 if (!RHS) RHS = BE->getRHS();
805 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
809 llvm_unreachable("Invalid expression kind!");
812 /// ParseExpression - Parse an expression and return it.
814 /// expr ::= expr &&,|| expr -> lowest.
815 /// expr ::= expr |,^,&,! expr
816 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
817 /// expr ::= expr <<,>> expr
818 /// expr ::= expr +,- expr
819 /// expr ::= expr *,/,% expr -> highest.
820 /// expr ::= primaryexpr
822 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
823 // Parse the expression.
825 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
828 // As a special case, we support 'a op b @ modifier' by rewriting the
829 // expression to include the modifier. This is inefficient, but in general we
830 // expect users to use 'a@modifier op b'.
831 if (Lexer.getKind() == AsmToken::At) {
834 if (Lexer.isNot(AsmToken::Identifier))
835 return TokError("unexpected symbol modifier following '@'");
837 MCSymbolRefExpr::VariantKind Variant =
838 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
839 if (Variant == MCSymbolRefExpr::VK_Invalid)
840 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
842 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
844 return TokError("invalid modifier '" + getTok().getIdentifier() +
845 "' (no symbols present)");
852 // Try to constant fold it up front, if possible.
854 if (Res->EvaluateAsAbsolute(Value))
855 Res = MCConstantExpr::Create(Value, getContext());
860 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
862 return ParseParenExpr(Res, EndLoc) ||
863 ParseBinOpRHS(1, Res, EndLoc);
866 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
869 SMLoc StartLoc = Lexer.getLoc();
870 if (ParseExpression(Expr))
873 if (!Expr->EvaluateAsAbsolute(Res))
874 return Error(StartLoc, "expected absolute expression");
879 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
880 MCBinaryExpr::Opcode &Kind) {
883 return 0; // not a binop.
885 // Lowest Precedence: &&, ||
886 case AsmToken::AmpAmp:
887 Kind = MCBinaryExpr::LAnd;
889 case AsmToken::PipePipe:
890 Kind = MCBinaryExpr::LOr;
894 // Low Precedence: |, &, ^
896 // FIXME: gas seems to support '!' as an infix operator?
898 Kind = MCBinaryExpr::Or;
900 case AsmToken::Caret:
901 Kind = MCBinaryExpr::Xor;
904 Kind = MCBinaryExpr::And;
907 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
908 case AsmToken::EqualEqual:
909 Kind = MCBinaryExpr::EQ;
911 case AsmToken::ExclaimEqual:
912 case AsmToken::LessGreater:
913 Kind = MCBinaryExpr::NE;
916 Kind = MCBinaryExpr::LT;
918 case AsmToken::LessEqual:
919 Kind = MCBinaryExpr::LTE;
921 case AsmToken::Greater:
922 Kind = MCBinaryExpr::GT;
924 case AsmToken::GreaterEqual:
925 Kind = MCBinaryExpr::GTE;
928 // Intermediate Precedence: <<, >>
929 case AsmToken::LessLess:
930 Kind = MCBinaryExpr::Shl;
932 case AsmToken::GreaterGreater:
933 Kind = MCBinaryExpr::Shr;
936 // High Intermediate Precedence: +, -
938 Kind = MCBinaryExpr::Add;
940 case AsmToken::Minus:
941 Kind = MCBinaryExpr::Sub;
944 // Highest Precedence: *, /, %
946 Kind = MCBinaryExpr::Mul;
948 case AsmToken::Slash:
949 Kind = MCBinaryExpr::Div;
951 case AsmToken::Percent:
952 Kind = MCBinaryExpr::Mod;
958 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
959 /// Res contains the LHS of the expression on input.
960 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
963 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
964 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
966 // If the next token is lower precedence than we are allowed to eat, return
967 // successfully with what we ate already.
968 if (TokPrec < Precedence)
973 // Eat the next primary expression.
975 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
977 // If BinOp binds less tightly with RHS than the operator after RHS, let
978 // the pending operator take RHS as its LHS.
979 MCBinaryExpr::Opcode Dummy;
980 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
981 if (TokPrec < NextTokPrec) {
982 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
985 // Merge LHS and RHS according to operator.
986 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
994 /// ::= EndOfStatement
995 /// ::= Label* Directive ...Operands... EndOfStatement
996 /// ::= Label* Identifier OperandList* EndOfStatement
997 bool AsmParser::ParseStatement() {
998 if (Lexer.is(AsmToken::EndOfStatement)) {
1004 // Statements always start with an identifier or are a full line comment.
1005 AsmToken ID = getTok();
1006 SMLoc IDLoc = ID.getLoc();
1008 int64_t LocalLabelVal = -1;
1009 // A full line comment is a '#' as the first token.
1010 if (Lexer.is(AsmToken::Hash))
1011 return ParseCppHashLineFilenameComment(IDLoc);
1013 // Allow an integer followed by a ':' as a directional local label.
1014 if (Lexer.is(AsmToken::Integer)) {
1015 LocalLabelVal = getTok().getIntVal();
1016 if (LocalLabelVal < 0) {
1017 if (!TheCondState.Ignore)
1018 return TokError("unexpected token at start of statement");
1022 IDVal = getTok().getString();
1023 Lex(); // Consume the integer token to be used as an identifier token.
1024 if (Lexer.getKind() != AsmToken::Colon) {
1025 if (!TheCondState.Ignore)
1026 return TokError("unexpected token at start of statement");
1030 } else if (Lexer.is(AsmToken::Dot)) {
1031 // Treat '.' as a valid identifier in this context.
1035 } else if (ParseIdentifier(IDVal)) {
1036 if (!TheCondState.Ignore)
1037 return TokError("unexpected token at start of statement");
1042 // Handle conditional assembly here before checking for skipping. We
1043 // have to do this so that .endif isn't skipped in a ".if 0" block for
1046 return ParseDirectiveIf(IDLoc);
1047 if (IDVal == ".ifb")
1048 return ParseDirectiveIfb(IDLoc, true);
1049 if (IDVal == ".ifnb")
1050 return ParseDirectiveIfb(IDLoc, false);
1051 if (IDVal == ".ifdef")
1052 return ParseDirectiveIfdef(IDLoc, true);
1053 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1054 return ParseDirectiveIfdef(IDLoc, false);
1055 if (IDVal == ".elseif")
1056 return ParseDirectiveElseIf(IDLoc);
1057 if (IDVal == ".else")
1058 return ParseDirectiveElse(IDLoc);
1059 if (IDVal == ".endif")
1060 return ParseDirectiveEndIf(IDLoc);
1062 // If we are in a ".if 0" block, ignore this statement.
1063 if (TheCondState.Ignore) {
1064 EatToEndOfStatement();
1068 // FIXME: Recurse on local labels?
1070 // See what kind of statement we have.
1071 switch (Lexer.getKind()) {
1072 case AsmToken::Colon: {
1073 CheckForValidSection();
1075 // identifier ':' -> Label.
1078 // Diagnose attempt to use '.' as a label.
1080 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1082 // Diagnose attempt to use a variable as a label.
1084 // FIXME: Diagnostics. Note the location of the definition as a label.
1085 // FIXME: This doesn't diagnose assignment to a symbol which has been
1086 // implicitly marked as external.
1088 if (LocalLabelVal == -1)
1089 Sym = getContext().GetOrCreateSymbol(IDVal);
1091 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1092 if (!Sym->isUndefined() || Sym->isVariable())
1093 return Error(IDLoc, "invalid symbol redefinition");
1098 // If we are generating dwarf for assembly source files then gather the
1099 // info to make a dwarf label entry for this label if needed.
1100 if (getContext().getGenDwarfForAssembly())
1101 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1104 // Consume any end of statement token, if present, to avoid spurious
1105 // AddBlankLine calls().
1106 if (Lexer.is(AsmToken::EndOfStatement)) {
1108 if (Lexer.is(AsmToken::Eof))
1112 return ParseStatement();
1115 case AsmToken::Equal:
1116 // identifier '=' ... -> assignment statement
1119 return ParseAssignment(IDVal, true);
1121 default: // Normal instruction or directive.
1125 // If macros are enabled, check to see if this is a macro instantiation.
1127 if (const Macro *M = MacroMap.lookup(IDVal))
1128 return HandleMacroEntry(IDVal, IDLoc, M);
1130 // Otherwise, we have a normal instruction or directive.
1131 if (IDVal[0] == '.' && IDVal != ".") {
1132 // Assembler features
1133 if (IDVal == ".set" || IDVal == ".equ")
1134 return ParseDirectiveSet(IDVal, true);
1135 if (IDVal == ".equiv")
1136 return ParseDirectiveSet(IDVal, false);
1140 if (IDVal == ".ascii")
1141 return ParseDirectiveAscii(IDVal, false);
1142 if (IDVal == ".asciz" || IDVal == ".string")
1143 return ParseDirectiveAscii(IDVal, true);
1145 if (IDVal == ".byte")
1146 return ParseDirectiveValue(1);
1147 if (IDVal == ".short")
1148 return ParseDirectiveValue(2);
1149 if (IDVal == ".value")
1150 return ParseDirectiveValue(2);
1151 if (IDVal == ".2byte")
1152 return ParseDirectiveValue(2);
1153 if (IDVal == ".long")
1154 return ParseDirectiveValue(4);
1155 if (IDVal == ".int")
1156 return ParseDirectiveValue(4);
1157 if (IDVal == ".4byte")
1158 return ParseDirectiveValue(4);
1159 if (IDVal == ".quad")
1160 return ParseDirectiveValue(8);
1161 if (IDVal == ".8byte")
1162 return ParseDirectiveValue(8);
1163 if (IDVal == ".single" || IDVal == ".float")
1164 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1165 if (IDVal == ".double")
1166 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1168 if (IDVal == ".align") {
1169 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1170 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1172 if (IDVal == ".align32") {
1173 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1174 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1176 if (IDVal == ".balign")
1177 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1178 if (IDVal == ".balignw")
1179 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1180 if (IDVal == ".balignl")
1181 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1182 if (IDVal == ".p2align")
1183 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1184 if (IDVal == ".p2alignw")
1185 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1186 if (IDVal == ".p2alignl")
1187 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1189 if (IDVal == ".org")
1190 return ParseDirectiveOrg();
1192 if (IDVal == ".fill")
1193 return ParseDirectiveFill();
1194 if (IDVal == ".space" || IDVal == ".skip")
1195 return ParseDirectiveSpace();
1196 if (IDVal == ".zero")
1197 return ParseDirectiveZero();
1199 // Symbol attribute directives
1201 if (IDVal == ".globl" || IDVal == ".global")
1202 return ParseDirectiveSymbolAttribute(MCSA_Global);
1203 if (IDVal == ".indirect_symbol")
1204 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1205 if (IDVal == ".lazy_reference")
1206 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1207 if (IDVal == ".no_dead_strip")
1208 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1209 if (IDVal == ".symbol_resolver")
1210 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1211 if (IDVal == ".private_extern")
1212 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1213 if (IDVal == ".reference")
1214 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1215 if (IDVal == ".weak_definition")
1216 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1217 if (IDVal == ".weak_reference")
1218 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1219 if (IDVal == ".weak_def_can_be_hidden")
1220 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1222 if (IDVal == ".comm" || IDVal == ".common")
1223 return ParseDirectiveComm(/*IsLocal=*/false);
1224 if (IDVal == ".lcomm")
1225 return ParseDirectiveComm(/*IsLocal=*/true);
1227 if (IDVal == ".abort")
1228 return ParseDirectiveAbort();
1229 if (IDVal == ".include")
1230 return ParseDirectiveInclude();
1231 if (IDVal == ".incbin")
1232 return ParseDirectiveIncbin();
1234 if (IDVal == ".code16")
1235 return TokError(Twine(IDVal) + " not supported yet");
1237 // Look up the handler in the handler table.
1238 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1239 DirectiveMap.lookup(IDVal);
1241 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1243 // Target hook for parsing target specific directives.
1244 if (!getTargetParser().ParseDirective(ID))
1247 return Error(IDLoc, "unknown directive");
1250 CheckForValidSection();
1252 // Canonicalize the opcode to lower case.
1253 SmallString<128> Opcode;
1254 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1255 Opcode.push_back(tolower(IDVal[i]));
1257 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1258 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1261 // Dump the parsed representation, if requested.
1262 if (getShowParsedOperands()) {
1263 SmallString<256> Str;
1264 raw_svector_ostream OS(Str);
1265 OS << "parsed instruction: [";
1266 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1269 ParsedOperands[i]->print(OS);
1273 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1276 // If we are generating dwarf for assembly source files and the current
1277 // section is the initial text section then generate a .loc directive for
1279 if (!HadError && getContext().getGenDwarfForAssembly() &&
1280 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1281 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1282 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1283 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1284 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1288 // If parsing succeeded, match the instruction.
1290 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1293 // Free any parsed operands.
1294 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1295 delete ParsedOperands[i];
1297 // Don't skip the rest of the line, the instruction parser is responsible for
1302 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1303 /// since they may not be able to be tokenized to get to the end of line token.
1304 void AsmParser::EatToEndOfLine() {
1305 if (!Lexer.is(AsmToken::EndOfStatement))
1306 Lexer.LexUntilEndOfLine();
1311 /// ParseCppHashLineFilenameComment as this:
1312 /// ::= # number "filename"
1313 /// or just as a full line comment if it doesn't have a number and a string.
1314 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1315 Lex(); // Eat the hash token.
1317 if (getLexer().isNot(AsmToken::Integer)) {
1318 // Consume the line since in cases it is not a well-formed line directive,
1319 // as if were simply a full line comment.
1324 int64_t LineNumber = getTok().getIntVal();
1327 if (getLexer().isNot(AsmToken::String)) {
1332 StringRef Filename = getTok().getString();
1333 // Get rid of the enclosing quotes.
1334 Filename = Filename.substr(1, Filename.size()-2);
1336 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1338 CppHashFilename = Filename;
1339 CppHashLineNumber = LineNumber;
1341 // Ignore any trailing characters, they're just comment.
1346 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1347 /// for the Filename and LineNo if any in the diagnostic.
1348 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1349 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1350 raw_ostream &OS = errs();
1352 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1353 const SMLoc &DiagLoc = Diag.getLoc();
1354 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1355 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1357 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1358 // before printing the message.
1359 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1360 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1361 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1362 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1365 // If we have not parsed a cpp hash line filename comment or the source
1366 // manager changed or buffer changed (like in a nested include) then just
1367 // print the normal diagnostic using its Filename and LineNo.
1368 if (!Parser->CppHashLineNumber ||
1369 &DiagSrcMgr != &Parser->SrcMgr ||
1370 DiagBuf != CppHashBuf) {
1371 if (Parser->SavedDiagHandler)
1372 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1378 // Use the CppHashFilename and calculate a line number based on the
1379 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1381 const std::string Filename = Parser->CppHashFilename;
1383 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1384 int CppHashLocLineNo =
1385 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1386 int LineNo = Parser->CppHashLineNumber - 1 +
1387 (DiagLocLineNo - CppHashLocLineNo);
1389 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1390 Filename, LineNo, Diag.getColumnNo(),
1391 Diag.getKind(), Diag.getMessage(),
1392 Diag.getLineContents(), Diag.getRanges());
1394 if (Parser->SavedDiagHandler)
1395 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1397 NewDiag.print(0, OS);
1400 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1401 const std::vector<StringRef> &Parameters,
1402 const std::vector<std::vector<AsmToken> > &A,
1404 raw_svector_ostream OS(Buf);
1405 unsigned NParameters = Parameters.size();
1406 if (NParameters != 0 && NParameters != A.size())
1407 return Error(L, "Wrong number of arguments");
1409 while (!Body.empty()) {
1410 // Scan for the next substitution.
1411 std::size_t End = Body.size(), Pos = 0;
1412 for (; Pos != End; ++Pos) {
1413 // Check for a substitution or escape.
1415 // This macro has no parameters, look for $0, $1, etc.
1416 if (Body[Pos] != '$' || Pos + 1 == End)
1419 char Next = Body[Pos + 1];
1420 if (Next == '$' || Next == 'n' || isdigit(Next))
1423 // This macro has parameters, look for \foo, \bar, etc.
1424 if (Body[Pos] == '\\' && Pos + 1 != End)
1430 OS << Body.slice(0, Pos);
1432 // Check if we reached the end.
1437 switch (Body[Pos+1]) {
1443 // $n => number of arguments
1448 // $[0-9] => argument
1450 // Missing arguments are ignored.
1451 unsigned Index = Body[Pos+1] - '0';
1452 if (Index >= A.size())
1455 // Otherwise substitute with the token values, with spaces eliminated.
1456 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1457 ie = A[Index].end(); it != ie; ++it)
1458 OS << it->getString();
1464 unsigned I = Pos + 1;
1465 while (isalnum(Body[I]) && I + 1 != End)
1468 const char *Begin = Body.data() + Pos +1;
1469 StringRef Argument(Begin, I - (Pos +1));
1471 for (; Index < NParameters; ++Index)
1472 if (Parameters[Index] == Argument)
1475 // FIXME: We should error at the macro definition.
1476 if (Index == NParameters)
1477 return Error(L, "Parameter not found");
1479 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1480 ie = A[Index].end(); it != ie; ++it)
1481 OS << it->getString();
1483 Pos += 1 + Argument.size();
1485 // Update the scan point.
1486 Body = Body.substr(Pos);
1489 // We include the .endmacro in the buffer as our queue to exit the macro
1491 OS << ".endmacro\n";
1495 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1497 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1501 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1503 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1504 // this, although we should protect against infinite loops.
1505 if (ActiveMacros.size() == 20)
1506 return TokError("macros cannot be nested more than 20 levels deep");
1508 // Parse the macro instantiation arguments.
1509 std::vector<std::vector<AsmToken> > MacroArguments;
1510 MacroArguments.push_back(std::vector<AsmToken>());
1511 unsigned ParenLevel = 0;
1513 if (Lexer.is(AsmToken::Eof))
1514 return TokError("unexpected token in macro instantiation");
1515 if (Lexer.is(AsmToken::EndOfStatement))
1518 // If we aren't inside parentheses and this is a comma, start a new token
1520 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1521 MacroArguments.push_back(std::vector<AsmToken>());
1523 // Adjust the current parentheses level.
1524 if (Lexer.is(AsmToken::LParen))
1526 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1529 // Append the token to the current argument list.
1530 MacroArguments.back().push_back(getTok());
1534 // If the last argument didn't end up with any tokens, it's not a real
1535 // argument and we should remove it from the list. This happens with either
1536 // a tailing comma or an empty argument list.
1537 if (MacroArguments.back().empty())
1538 MacroArguments.pop_back();
1540 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1541 // to hold the macro body with substitutions.
1542 SmallString<256> Buf;
1543 StringRef Body = M->Body;
1545 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1548 MemoryBuffer *Instantiation =
1549 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1551 // Create the macro instantiation object and add to the current macro
1552 // instantiation stack.
1553 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1556 ActiveMacros.push_back(MI);
1558 // Jump to the macro instantiation and prime the lexer.
1559 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1560 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1566 void AsmParser::HandleMacroExit() {
1567 // Jump to the EndOfStatement we should return to, and consume it.
1568 JumpToLoc(ActiveMacros.back()->ExitLoc);
1571 // Pop the instantiation entry.
1572 delete ActiveMacros.back();
1573 ActiveMacros.pop_back();
1576 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1577 switch (Value->getKind()) {
1578 case MCExpr::Binary: {
1579 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1580 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1583 case MCExpr::Target:
1584 case MCExpr::Constant:
1586 case MCExpr::SymbolRef: {
1587 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1589 return IsUsedIn(Sym, S.getVariableValue());
1593 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1596 llvm_unreachable("Unknown expr kind!");
1599 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1600 // FIXME: Use better location, we should use proper tokens.
1601 SMLoc EqualLoc = Lexer.getLoc();
1603 const MCExpr *Value;
1604 if (ParseExpression(Value))
1607 // Note: we don't count b as used in "a = b". This is to allow
1611 if (Lexer.isNot(AsmToken::EndOfStatement))
1612 return TokError("unexpected token in assignment");
1614 // Error on assignment to '.'.
1616 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1617 "(use '.space' or '.org').)"));
1620 // Eat the end of statement marker.
1623 // Validate that the LHS is allowed to be a variable (either it has not been
1624 // used as a symbol, or it is an absolute symbol).
1625 MCSymbol *Sym = getContext().LookupSymbol(Name);
1627 // Diagnose assignment to a label.
1629 // FIXME: Diagnostics. Note the location of the definition as a label.
1630 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1631 if (IsUsedIn(Sym, Value))
1632 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1633 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1634 ; // Allow redefinitions of undefined symbols only used in directives.
1635 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1636 ; // Allow redefinitions of variables that haven't yet been used.
1637 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1638 return Error(EqualLoc, "redefinition of '" + Name + "'");
1639 else if (!Sym->isVariable())
1640 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1641 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1642 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1645 // Don't count these checks as uses.
1646 Sym->setUsed(false);
1648 Sym = getContext().GetOrCreateSymbol(Name);
1650 // FIXME: Handle '.'.
1652 // Do the assignment.
1653 Out.EmitAssignment(Sym, Value);
1658 /// ParseIdentifier:
1661 bool AsmParser::ParseIdentifier(StringRef &Res) {
1662 // The assembler has relaxed rules for accepting identifiers, in particular we
1663 // allow things like '.globl $foo', which would normally be separate
1664 // tokens. At this level, we have already lexed so we cannot (currently)
1665 // handle this as a context dependent token, instead we detect adjacent tokens
1666 // and return the combined identifier.
1667 if (Lexer.is(AsmToken::Dollar)) {
1668 SMLoc DollarLoc = getLexer().getLoc();
1670 // Consume the dollar sign, and check for a following identifier.
1672 if (Lexer.isNot(AsmToken::Identifier))
1675 // We have a '$' followed by an identifier, make sure they are adjacent.
1676 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1679 // Construct the joined identifier and consume the token.
1680 Res = StringRef(DollarLoc.getPointer(),
1681 getTok().getIdentifier().size() + 1);
1686 if (Lexer.isNot(AsmToken::Identifier) &&
1687 Lexer.isNot(AsmToken::String))
1690 Res = getTok().getIdentifier();
1692 Lex(); // Consume the identifier token.
1697 /// ParseDirectiveSet:
1698 /// ::= .equ identifier ',' expression
1699 /// ::= .equiv identifier ',' expression
1700 /// ::= .set identifier ',' expression
1701 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1704 if (ParseIdentifier(Name))
1705 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1707 if (getLexer().isNot(AsmToken::Comma))
1708 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1711 return ParseAssignment(Name, allow_redef);
1714 bool AsmParser::ParseEscapedString(std::string &Data) {
1715 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1718 StringRef Str = getTok().getStringContents();
1719 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1720 if (Str[i] != '\\') {
1725 // Recognize escaped characters. Note that this escape semantics currently
1726 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1729 return TokError("unexpected backslash at end of string");
1731 // Recognize octal sequences.
1732 if ((unsigned) (Str[i] - '0') <= 7) {
1733 // Consume up to three octal characters.
1734 unsigned Value = Str[i] - '0';
1736 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1738 Value = Value * 8 + (Str[i] - '0');
1740 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1742 Value = Value * 8 + (Str[i] - '0');
1747 return TokError("invalid octal escape sequence (out of range)");
1749 Data += (unsigned char) Value;
1753 // Otherwise recognize individual escapes.
1756 // Just reject invalid escape sequences for now.
1757 return TokError("invalid escape sequence (unrecognized character)");
1759 case 'b': Data += '\b'; break;
1760 case 'f': Data += '\f'; break;
1761 case 'n': Data += '\n'; break;
1762 case 'r': Data += '\r'; break;
1763 case 't': Data += '\t'; break;
1764 case '"': Data += '"'; break;
1765 case '\\': Data += '\\'; break;
1772 /// ParseDirectiveAscii:
1773 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1774 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1775 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1776 CheckForValidSection();
1779 if (getLexer().isNot(AsmToken::String))
1780 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1783 if (ParseEscapedString(Data))
1786 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1788 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1792 if (getLexer().is(AsmToken::EndOfStatement))
1795 if (getLexer().isNot(AsmToken::Comma))
1796 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1805 /// ParseDirectiveValue
1806 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1807 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1808 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1809 CheckForValidSection();
1812 const MCExpr *Value;
1813 SMLoc ExprLoc = getLexer().getLoc();
1814 if (ParseExpression(Value))
1817 // Special case constant expressions to match code generator.
1818 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1819 assert(Size <= 8 && "Invalid size");
1820 uint64_t IntValue = MCE->getValue();
1821 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1822 return Error(ExprLoc, "literal value out of range for directive");
1823 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1825 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1827 if (getLexer().is(AsmToken::EndOfStatement))
1830 // FIXME: Improve diagnostic.
1831 if (getLexer().isNot(AsmToken::Comma))
1832 return TokError("unexpected token in directive");
1841 /// ParseDirectiveRealValue
1842 /// ::= (.single | .double) [ expression (, expression)* ]
1843 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1844 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1845 CheckForValidSection();
1848 // We don't truly support arithmetic on floating point expressions, so we
1849 // have to manually parse unary prefixes.
1851 if (getLexer().is(AsmToken::Minus)) {
1854 } else if (getLexer().is(AsmToken::Plus))
1857 if (getLexer().isNot(AsmToken::Integer) &&
1858 getLexer().isNot(AsmToken::Real) &&
1859 getLexer().isNot(AsmToken::Identifier))
1860 return TokError("unexpected token in directive");
1862 // Convert to an APFloat.
1863 APFloat Value(Semantics);
1864 StringRef IDVal = getTok().getString();
1865 if (getLexer().is(AsmToken::Identifier)) {
1866 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1867 Value = APFloat::getInf(Semantics);
1868 else if (!IDVal.compare_lower("nan"))
1869 Value = APFloat::getNaN(Semantics, false, ~0);
1871 return TokError("invalid floating point literal");
1872 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1873 APFloat::opInvalidOp)
1874 return TokError("invalid floating point literal");
1878 // Consume the numeric token.
1881 // Emit the value as an integer.
1882 APInt AsInt = Value.bitcastToAPInt();
1883 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1884 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1886 if (getLexer().is(AsmToken::EndOfStatement))
1889 if (getLexer().isNot(AsmToken::Comma))
1890 return TokError("unexpected token in directive");
1899 /// ParseDirectiveSpace
1900 /// ::= .space expression [ , expression ]
1901 bool AsmParser::ParseDirectiveSpace() {
1902 CheckForValidSection();
1905 if (ParseAbsoluteExpression(NumBytes))
1908 int64_t FillExpr = 0;
1909 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1910 if (getLexer().isNot(AsmToken::Comma))
1911 return TokError("unexpected token in '.space' directive");
1914 if (ParseAbsoluteExpression(FillExpr))
1917 if (getLexer().isNot(AsmToken::EndOfStatement))
1918 return TokError("unexpected token in '.space' directive");
1924 return TokError("invalid number of bytes in '.space' directive");
1926 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1927 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1932 /// ParseDirectiveZero
1933 /// ::= .zero expression
1934 bool AsmParser::ParseDirectiveZero() {
1935 CheckForValidSection();
1938 if (ParseAbsoluteExpression(NumBytes))
1942 if (getLexer().is(AsmToken::Comma)) {
1944 if (ParseAbsoluteExpression(Val))
1948 if (getLexer().isNot(AsmToken::EndOfStatement))
1949 return TokError("unexpected token in '.zero' directive");
1953 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1958 /// ParseDirectiveFill
1959 /// ::= .fill expression , expression , expression
1960 bool AsmParser::ParseDirectiveFill() {
1961 CheckForValidSection();
1964 if (ParseAbsoluteExpression(NumValues))
1967 if (getLexer().isNot(AsmToken::Comma))
1968 return TokError("unexpected token in '.fill' directive");
1972 if (ParseAbsoluteExpression(FillSize))
1975 if (getLexer().isNot(AsmToken::Comma))
1976 return TokError("unexpected token in '.fill' directive");
1980 if (ParseAbsoluteExpression(FillExpr))
1983 if (getLexer().isNot(AsmToken::EndOfStatement))
1984 return TokError("unexpected token in '.fill' directive");
1988 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1989 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1991 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1992 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1997 /// ParseDirectiveOrg
1998 /// ::= .org expression [ , expression ]
1999 bool AsmParser::ParseDirectiveOrg() {
2000 CheckForValidSection();
2002 const MCExpr *Offset;
2003 SMLoc Loc = getTok().getLoc();
2004 if (ParseExpression(Offset))
2007 // Parse optional fill expression.
2008 int64_t FillExpr = 0;
2009 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2010 if (getLexer().isNot(AsmToken::Comma))
2011 return TokError("unexpected token in '.org' directive");
2014 if (ParseAbsoluteExpression(FillExpr))
2017 if (getLexer().isNot(AsmToken::EndOfStatement))
2018 return TokError("unexpected token in '.org' directive");
2023 // Only limited forms of relocatable expressions are accepted here, it
2024 // has to be relative to the current section. The streamer will return
2025 // 'true' if the expression wasn't evaluatable.
2026 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2027 return Error(Loc, "expected assembly-time absolute expression");
2032 /// ParseDirectiveAlign
2033 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2034 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2035 CheckForValidSection();
2037 SMLoc AlignmentLoc = getLexer().getLoc();
2039 if (ParseAbsoluteExpression(Alignment))
2043 bool HasFillExpr = false;
2044 int64_t FillExpr = 0;
2045 int64_t MaxBytesToFill = 0;
2046 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2047 if (getLexer().isNot(AsmToken::Comma))
2048 return TokError("unexpected token in directive");
2051 // The fill expression can be omitted while specifying a maximum number of
2052 // alignment bytes, e.g:
2054 if (getLexer().isNot(AsmToken::Comma)) {
2056 if (ParseAbsoluteExpression(FillExpr))
2060 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2061 if (getLexer().isNot(AsmToken::Comma))
2062 return TokError("unexpected token in directive");
2065 MaxBytesLoc = getLexer().getLoc();
2066 if (ParseAbsoluteExpression(MaxBytesToFill))
2069 if (getLexer().isNot(AsmToken::EndOfStatement))
2070 return TokError("unexpected token in directive");
2079 // Compute alignment in bytes.
2081 // FIXME: Diagnose overflow.
2082 if (Alignment >= 32) {
2083 Error(AlignmentLoc, "invalid alignment value");
2087 Alignment = 1ULL << Alignment;
2090 // Diagnose non-sensical max bytes to align.
2091 if (MaxBytesLoc.isValid()) {
2092 if (MaxBytesToFill < 1) {
2093 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2094 "many bytes, ignoring maximum bytes expression");
2098 if (MaxBytesToFill >= Alignment) {
2099 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2105 // Check whether we should use optimal code alignment for this .align
2107 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2108 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2109 ValueSize == 1 && UseCodeAlign) {
2110 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2112 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2113 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2120 /// ParseDirectiveSymbolAttribute
2121 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2122 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2123 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2126 SMLoc Loc = getTok().getLoc();
2128 if (ParseIdentifier(Name))
2129 return Error(Loc, "expected identifier in directive");
2131 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2133 // Assembler local symbols don't make any sense here. Complain loudly.
2134 if (Sym->isTemporary())
2135 return Error(Loc, "non-local symbol required in directive");
2137 getStreamer().EmitSymbolAttribute(Sym, Attr);
2139 if (getLexer().is(AsmToken::EndOfStatement))
2142 if (getLexer().isNot(AsmToken::Comma))
2143 return TokError("unexpected token in directive");
2152 /// ParseDirectiveComm
2153 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2154 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2155 CheckForValidSection();
2157 SMLoc IDLoc = getLexer().getLoc();
2159 if (ParseIdentifier(Name))
2160 return TokError("expected identifier in directive");
2162 // Handle the identifier as the key symbol.
2163 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2165 if (getLexer().isNot(AsmToken::Comma))
2166 return TokError("unexpected token in directive");
2170 SMLoc SizeLoc = getLexer().getLoc();
2171 if (ParseAbsoluteExpression(Size))
2174 int64_t Pow2Alignment = 0;
2175 SMLoc Pow2AlignmentLoc;
2176 if (getLexer().is(AsmToken::Comma)) {
2178 Pow2AlignmentLoc = getLexer().getLoc();
2179 if (ParseAbsoluteExpression(Pow2Alignment))
2182 // If this target takes alignments in bytes (not log) validate and convert.
2183 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2184 if (!isPowerOf2_64(Pow2Alignment))
2185 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2186 Pow2Alignment = Log2_64(Pow2Alignment);
2190 if (getLexer().isNot(AsmToken::EndOfStatement))
2191 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2195 // NOTE: a size of zero for a .comm should create a undefined symbol
2196 // but a size of .lcomm creates a bss symbol of size zero.
2198 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2199 "be less than zero");
2201 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2202 // may internally end up wanting an alignment in bytes.
2203 // FIXME: Diagnose overflow.
2204 if (Pow2Alignment < 0)
2205 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2206 "alignment, can't be less than zero");
2208 if (!Sym->isUndefined())
2209 return Error(IDLoc, "invalid symbol redefinition");
2211 // '.lcomm' is equivalent to '.zerofill'.
2212 // Create the Symbol as a common or local common with Size and Pow2Alignment
2214 getStreamer().EmitZerofill(Ctx.getMachOSection(
2215 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2216 0, SectionKind::getBSS()),
2217 Sym, Size, 1 << Pow2Alignment);
2221 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2225 /// ParseDirectiveAbort
2226 /// ::= .abort [... message ...]
2227 bool AsmParser::ParseDirectiveAbort() {
2228 // FIXME: Use loc from directive.
2229 SMLoc Loc = getLexer().getLoc();
2231 StringRef Str = ParseStringToEndOfStatement();
2232 if (getLexer().isNot(AsmToken::EndOfStatement))
2233 return TokError("unexpected token in '.abort' directive");
2238 Error(Loc, ".abort detected. Assembly stopping.");
2240 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2241 // FIXME: Actually abort assembly here.
2246 /// ParseDirectiveInclude
2247 /// ::= .include "filename"
2248 bool AsmParser::ParseDirectiveInclude() {
2249 if (getLexer().isNot(AsmToken::String))
2250 return TokError("expected string in '.include' directive");
2252 std::string Filename = getTok().getString();
2253 SMLoc IncludeLoc = getLexer().getLoc();
2256 if (getLexer().isNot(AsmToken::EndOfStatement))
2257 return TokError("unexpected token in '.include' directive");
2259 // Strip the quotes.
2260 Filename = Filename.substr(1, Filename.size()-2);
2262 // Attempt to switch the lexer to the included file before consuming the end
2263 // of statement to avoid losing it when we switch.
2264 if (EnterIncludeFile(Filename)) {
2265 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2272 /// ParseDirectiveIncbin
2273 /// ::= .incbin "filename"
2274 bool AsmParser::ParseDirectiveIncbin() {
2275 if (getLexer().isNot(AsmToken::String))
2276 return TokError("expected string in '.incbin' directive");
2278 std::string Filename = getTok().getString();
2279 SMLoc IncbinLoc = getLexer().getLoc();
2282 if (getLexer().isNot(AsmToken::EndOfStatement))
2283 return TokError("unexpected token in '.incbin' directive");
2285 // Strip the quotes.
2286 Filename = Filename.substr(1, Filename.size()-2);
2288 // Attempt to process the included file.
2289 if (ProcessIncbinFile(Filename)) {
2290 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2297 /// ParseDirectiveIf
2298 /// ::= .if expression
2299 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2300 TheCondStack.push_back(TheCondState);
2301 TheCondState.TheCond = AsmCond::IfCond;
2302 if(TheCondState.Ignore) {
2303 EatToEndOfStatement();
2307 if (ParseAbsoluteExpression(ExprValue))
2310 if (getLexer().isNot(AsmToken::EndOfStatement))
2311 return TokError("unexpected token in '.if' directive");
2315 TheCondState.CondMet = ExprValue;
2316 TheCondState.Ignore = !TheCondState.CondMet;
2322 /// ParseDirectiveIfb
2324 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2325 TheCondStack.push_back(TheCondState);
2326 TheCondState.TheCond = AsmCond::IfCond;
2328 if(TheCondState.Ignore) {
2329 EatToEndOfStatement();
2331 StringRef Str = ParseStringToEndOfStatement();
2333 if (getLexer().isNot(AsmToken::EndOfStatement))
2334 return TokError("unexpected token in '.ifb' directive");
2338 TheCondState.CondMet = ExpectBlank == Str.empty();
2339 TheCondState.Ignore = !TheCondState.CondMet;
2345 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2347 TheCondStack.push_back(TheCondState);
2348 TheCondState.TheCond = AsmCond::IfCond;
2350 if (TheCondState.Ignore) {
2351 EatToEndOfStatement();
2353 if (ParseIdentifier(Name))
2354 return TokError("expected identifier after '.ifdef'");
2358 MCSymbol *Sym = getContext().LookupSymbol(Name);
2361 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2363 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2364 TheCondState.Ignore = !TheCondState.CondMet;
2370 /// ParseDirectiveElseIf
2371 /// ::= .elseif expression
2372 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2373 if (TheCondState.TheCond != AsmCond::IfCond &&
2374 TheCondState.TheCond != AsmCond::ElseIfCond)
2375 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2377 TheCondState.TheCond = AsmCond::ElseIfCond;
2379 bool LastIgnoreState = false;
2380 if (!TheCondStack.empty())
2381 LastIgnoreState = TheCondStack.back().Ignore;
2382 if (LastIgnoreState || TheCondState.CondMet) {
2383 TheCondState.Ignore = true;
2384 EatToEndOfStatement();
2388 if (ParseAbsoluteExpression(ExprValue))
2391 if (getLexer().isNot(AsmToken::EndOfStatement))
2392 return TokError("unexpected token in '.elseif' directive");
2395 TheCondState.CondMet = ExprValue;
2396 TheCondState.Ignore = !TheCondState.CondMet;
2402 /// ParseDirectiveElse
2404 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2405 if (getLexer().isNot(AsmToken::EndOfStatement))
2406 return TokError("unexpected token in '.else' directive");
2410 if (TheCondState.TheCond != AsmCond::IfCond &&
2411 TheCondState.TheCond != AsmCond::ElseIfCond)
2412 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2414 TheCondState.TheCond = AsmCond::ElseCond;
2415 bool LastIgnoreState = false;
2416 if (!TheCondStack.empty())
2417 LastIgnoreState = TheCondStack.back().Ignore;
2418 if (LastIgnoreState || TheCondState.CondMet)
2419 TheCondState.Ignore = true;
2421 TheCondState.Ignore = false;
2426 /// ParseDirectiveEndIf
2428 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2429 if (getLexer().isNot(AsmToken::EndOfStatement))
2430 return TokError("unexpected token in '.endif' directive");
2434 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2435 TheCondStack.empty())
2436 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2438 if (!TheCondStack.empty()) {
2439 TheCondState = TheCondStack.back();
2440 TheCondStack.pop_back();
2446 /// ParseDirectiveFile
2447 /// ::= .file [number] filename
2448 /// ::= .file number directory filename
2449 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2450 // FIXME: I'm not sure what this is.
2451 int64_t FileNumber = -1;
2452 SMLoc FileNumberLoc = getLexer().getLoc();
2453 if (getLexer().is(AsmToken::Integer)) {
2454 FileNumber = getTok().getIntVal();
2458 return TokError("file number less than one");
2461 if (getLexer().isNot(AsmToken::String))
2462 return TokError("unexpected token in '.file' directive");
2464 // Usually the directory and filename together, otherwise just the directory.
2465 StringRef Path = getTok().getString();
2466 Path = Path.substr(1, Path.size()-2);
2469 StringRef Directory;
2471 if (getLexer().is(AsmToken::String)) {
2472 if (FileNumber == -1)
2473 return TokError("explicit path specified, but no file number");
2474 Filename = getTok().getString();
2475 Filename = Filename.substr(1, Filename.size()-2);
2482 if (getLexer().isNot(AsmToken::EndOfStatement))
2483 return TokError("unexpected token in '.file' directive");
2485 if (FileNumber == -1)
2486 getStreamer().EmitFileDirective(Filename);
2488 if (getContext().getGenDwarfForAssembly() == true)
2489 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2490 "used to generate dwarf debug info for assembly code");
2492 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2493 Error(FileNumberLoc, "file number already allocated");
2499 /// ParseDirectiveLine
2500 /// ::= .line [number]
2501 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2502 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2503 if (getLexer().isNot(AsmToken::Integer))
2504 return TokError("unexpected token in '.line' directive");
2506 int64_t LineNumber = getTok().getIntVal();
2510 // FIXME: Do something with the .line.
2513 if (getLexer().isNot(AsmToken::EndOfStatement))
2514 return TokError("unexpected token in '.line' directive");
2520 /// ParseDirectiveLoc
2521 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2522 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2523 /// The first number is a file number, must have been previously assigned with
2524 /// a .file directive, the second number is the line number and optionally the
2525 /// third number is a column position (zero if not specified). The remaining
2526 /// optional items are .loc sub-directives.
2527 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2529 if (getLexer().isNot(AsmToken::Integer))
2530 return TokError("unexpected token in '.loc' directive");
2531 int64_t FileNumber = getTok().getIntVal();
2533 return TokError("file number less than one in '.loc' directive");
2534 if (!getContext().isValidDwarfFileNumber(FileNumber))
2535 return TokError("unassigned file number in '.loc' directive");
2538 int64_t LineNumber = 0;
2539 if (getLexer().is(AsmToken::Integer)) {
2540 LineNumber = getTok().getIntVal();
2542 return TokError("line number less than one in '.loc' directive");
2546 int64_t ColumnPos = 0;
2547 if (getLexer().is(AsmToken::Integer)) {
2548 ColumnPos = getTok().getIntVal();
2550 return TokError("column position less than zero in '.loc' directive");
2554 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2556 int64_t Discriminator = 0;
2557 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2559 if (getLexer().is(AsmToken::EndOfStatement))
2563 SMLoc Loc = getTok().getLoc();
2564 if (getParser().ParseIdentifier(Name))
2565 return TokError("unexpected token in '.loc' directive");
2567 if (Name == "basic_block")
2568 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2569 else if (Name == "prologue_end")
2570 Flags |= DWARF2_FLAG_PROLOGUE_END;
2571 else if (Name == "epilogue_begin")
2572 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2573 else if (Name == "is_stmt") {
2574 SMLoc Loc = getTok().getLoc();
2575 const MCExpr *Value;
2576 if (getParser().ParseExpression(Value))
2578 // The expression must be the constant 0 or 1.
2579 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2580 int Value = MCE->getValue();
2582 Flags &= ~DWARF2_FLAG_IS_STMT;
2583 else if (Value == 1)
2584 Flags |= DWARF2_FLAG_IS_STMT;
2586 return Error(Loc, "is_stmt value not 0 or 1");
2589 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2592 else if (Name == "isa") {
2593 SMLoc Loc = getTok().getLoc();
2594 const MCExpr *Value;
2595 if (getParser().ParseExpression(Value))
2597 // The expression must be a constant greater or equal to 0.
2598 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2599 int Value = MCE->getValue();
2601 return Error(Loc, "isa number less than zero");
2605 return Error(Loc, "isa number not a constant value");
2608 else if (Name == "discriminator") {
2609 if (getParser().ParseAbsoluteExpression(Discriminator))
2613 return Error(Loc, "unknown sub-directive in '.loc' directive");
2616 if (getLexer().is(AsmToken::EndOfStatement))
2621 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2622 Isa, Discriminator, StringRef());
2627 /// ParseDirectiveStabs
2628 /// ::= .stabs string, number, number, number
2629 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2630 SMLoc DirectiveLoc) {
2631 return TokError("unsupported directive '" + Directive + "'");
2634 /// ParseDirectiveCFISections
2635 /// ::= .cfi_sections section [, section]
2636 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2637 SMLoc DirectiveLoc) {
2642 if (getParser().ParseIdentifier(Name))
2643 return TokError("Expected an identifier");
2645 if (Name == ".eh_frame")
2647 else if (Name == ".debug_frame")
2650 if (getLexer().is(AsmToken::Comma)) {
2653 if (getParser().ParseIdentifier(Name))
2654 return TokError("Expected an identifier");
2656 if (Name == ".eh_frame")
2658 else if (Name == ".debug_frame")
2662 getStreamer().EmitCFISections(EH, Debug);
2667 /// ParseDirectiveCFIStartProc
2668 /// ::= .cfi_startproc
2669 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2670 SMLoc DirectiveLoc) {
2671 getStreamer().EmitCFIStartProc();
2675 /// ParseDirectiveCFIEndProc
2676 /// ::= .cfi_endproc
2677 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2678 getStreamer().EmitCFIEndProc();
2682 /// ParseRegisterOrRegisterNumber - parse register name or number.
2683 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2684 SMLoc DirectiveLoc) {
2687 if (getLexer().isNot(AsmToken::Integer)) {
2688 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2691 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2693 return getParser().ParseAbsoluteExpression(Register);
2698 /// ParseDirectiveCFIDefCfa
2699 /// ::= .cfi_def_cfa register, offset
2700 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2701 SMLoc DirectiveLoc) {
2702 int64_t Register = 0;
2703 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2706 if (getLexer().isNot(AsmToken::Comma))
2707 return TokError("unexpected token in directive");
2711 if (getParser().ParseAbsoluteExpression(Offset))
2714 getStreamer().EmitCFIDefCfa(Register, Offset);
2718 /// ParseDirectiveCFIDefCfaOffset
2719 /// ::= .cfi_def_cfa_offset offset
2720 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2721 SMLoc DirectiveLoc) {
2723 if (getParser().ParseAbsoluteExpression(Offset))
2726 getStreamer().EmitCFIDefCfaOffset(Offset);
2730 /// ParseDirectiveCFIAdjustCfaOffset
2731 /// ::= .cfi_adjust_cfa_offset adjustment
2732 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2733 SMLoc DirectiveLoc) {
2734 int64_t Adjustment = 0;
2735 if (getParser().ParseAbsoluteExpression(Adjustment))
2738 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2742 /// ParseDirectiveCFIDefCfaRegister
2743 /// ::= .cfi_def_cfa_register register
2744 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2745 SMLoc DirectiveLoc) {
2746 int64_t Register = 0;
2747 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2750 getStreamer().EmitCFIDefCfaRegister(Register);
2754 /// ParseDirectiveCFIOffset
2755 /// ::= .cfi_offset register, offset
2756 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2757 int64_t Register = 0;
2760 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2763 if (getLexer().isNot(AsmToken::Comma))
2764 return TokError("unexpected token in directive");
2767 if (getParser().ParseAbsoluteExpression(Offset))
2770 getStreamer().EmitCFIOffset(Register, Offset);
2774 /// ParseDirectiveCFIRelOffset
2775 /// ::= .cfi_rel_offset register, offset
2776 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2777 SMLoc DirectiveLoc) {
2778 int64_t Register = 0;
2780 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2783 if (getLexer().isNot(AsmToken::Comma))
2784 return TokError("unexpected token in directive");
2788 if (getParser().ParseAbsoluteExpression(Offset))
2791 getStreamer().EmitCFIRelOffset(Register, Offset);
2795 static bool isValidEncoding(int64_t Encoding) {
2796 if (Encoding & ~0xff)
2799 if (Encoding == dwarf::DW_EH_PE_omit)
2802 const unsigned Format = Encoding & 0xf;
2803 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2804 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2805 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2806 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2809 const unsigned Application = Encoding & 0x70;
2810 if (Application != dwarf::DW_EH_PE_absptr &&
2811 Application != dwarf::DW_EH_PE_pcrel)
2817 /// ParseDirectiveCFIPersonalityOrLsda
2818 /// ::= .cfi_personality encoding, [symbol_name]
2819 /// ::= .cfi_lsda encoding, [symbol_name]
2820 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2821 SMLoc DirectiveLoc) {
2822 int64_t Encoding = 0;
2823 if (getParser().ParseAbsoluteExpression(Encoding))
2825 if (Encoding == dwarf::DW_EH_PE_omit)
2828 if (!isValidEncoding(Encoding))
2829 return TokError("unsupported encoding.");
2831 if (getLexer().isNot(AsmToken::Comma))
2832 return TokError("unexpected token in directive");
2836 if (getParser().ParseIdentifier(Name))
2837 return TokError("expected identifier in directive");
2839 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2841 if (IDVal == ".cfi_personality")
2842 getStreamer().EmitCFIPersonality(Sym, Encoding);
2844 assert(IDVal == ".cfi_lsda");
2845 getStreamer().EmitCFILsda(Sym, Encoding);
2850 /// ParseDirectiveCFIRememberState
2851 /// ::= .cfi_remember_state
2852 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2853 SMLoc DirectiveLoc) {
2854 getStreamer().EmitCFIRememberState();
2858 /// ParseDirectiveCFIRestoreState
2859 /// ::= .cfi_remember_state
2860 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2861 SMLoc DirectiveLoc) {
2862 getStreamer().EmitCFIRestoreState();
2866 /// ParseDirectiveCFISameValue
2867 /// ::= .cfi_same_value register
2868 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2869 SMLoc DirectiveLoc) {
2870 int64_t Register = 0;
2872 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2875 getStreamer().EmitCFISameValue(Register);
2880 /// ParseDirectiveCFIRestore
2881 /// ::= .cfi_restore register
2882 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2883 SMLoc DirectiveLoc) {
2884 int64_t Register = 0;
2885 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2888 getStreamer().EmitCFIRestore(Register);
2893 /// ParseDirectiveCFIEscape
2894 /// ::= .cfi_escape expression[,...]
2895 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2896 SMLoc DirectiveLoc) {
2899 if (getParser().ParseAbsoluteExpression(CurrValue))
2902 Values.push_back((uint8_t)CurrValue);
2904 while (getLexer().is(AsmToken::Comma)) {
2907 if (getParser().ParseAbsoluteExpression(CurrValue))
2910 Values.push_back((uint8_t)CurrValue);
2913 getStreamer().EmitCFIEscape(Values);
2917 /// ParseDirectiveCFISignalFrame
2918 /// ::= .cfi_signal_frame
2919 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2920 SMLoc DirectiveLoc) {
2921 if (getLexer().isNot(AsmToken::EndOfStatement))
2922 return Error(getLexer().getLoc(),
2923 "unexpected token in '" + Directive + "' directive");
2925 getStreamer().EmitCFISignalFrame();
2930 /// ParseDirectiveMacrosOnOff
2933 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2934 SMLoc DirectiveLoc) {
2935 if (getLexer().isNot(AsmToken::EndOfStatement))
2936 return Error(getLexer().getLoc(),
2937 "unexpected token in '" + Directive + "' directive");
2939 getParser().MacrosEnabled = Directive == ".macros_on";
2944 /// ParseDirectiveMacro
2945 /// ::= .macro name [parameters]
2946 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2947 SMLoc DirectiveLoc) {
2949 if (getParser().ParseIdentifier(Name))
2950 return TokError("expected identifier in directive");
2952 std::vector<StringRef> Parameters;
2953 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2955 StringRef Parameter;
2956 if (getParser().ParseIdentifier(Parameter))
2957 return TokError("expected identifier in directive");
2958 Parameters.push_back(Parameter);
2960 if (getLexer().isNot(AsmToken::Comma))
2966 if (getLexer().isNot(AsmToken::EndOfStatement))
2967 return TokError("unexpected token in '.macro' directive");
2969 // Eat the end of statement.
2972 AsmToken EndToken, StartToken = getTok();
2974 // Lex the macro definition.
2976 // Check whether we have reached the end of the file.
2977 if (getLexer().is(AsmToken::Eof))
2978 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2980 // Otherwise, check whether we have reach the .endmacro.
2981 if (getLexer().is(AsmToken::Identifier) &&
2982 (getTok().getIdentifier() == ".endm" ||
2983 getTok().getIdentifier() == ".endmacro")) {
2984 EndToken = getTok();
2986 if (getLexer().isNot(AsmToken::EndOfStatement))
2987 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2992 // Otherwise, scan til the end of the statement.
2993 getParser().EatToEndOfStatement();
2996 if (getParser().MacroMap.lookup(Name)) {
2997 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3000 const char *BodyStart = StartToken.getLoc().getPointer();
3001 const char *BodyEnd = EndToken.getLoc().getPointer();
3002 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3003 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3007 /// ParseDirectiveEndMacro
3010 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3011 SMLoc DirectiveLoc) {
3012 if (getLexer().isNot(AsmToken::EndOfStatement))
3013 return TokError("unexpected token in '" + Directive + "' directive");
3015 // If we are inside a macro instantiation, terminate the current
3017 if (!getParser().ActiveMacros.empty()) {
3018 getParser().HandleMacroExit();
3022 // Otherwise, this .endmacro is a stray entry in the file; well formed
3023 // .endmacro directives are handled during the macro definition parsing.
3024 return TokError("unexpected '" + Directive + "' in file, "
3025 "no current macro definition");
3028 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3029 getParser().CheckForValidSection();
3031 const MCExpr *Value;
3033 if (getParser().ParseExpression(Value))
3036 if (getLexer().isNot(AsmToken::EndOfStatement))
3037 return TokError("unexpected token in directive");
3039 if (DirName[1] == 's')
3040 getStreamer().EmitSLEB128Value(Value);
3042 getStreamer().EmitULEB128Value(Value);
3048 /// \brief Create an MCAsmParser instance.
3049 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3050 MCContext &C, MCStreamer &Out,
3051 const MCAsmInfo &MAI) {
3052 return new AsmParser(SM, C, Out, MAI);