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 /// ActiveRept - Stack of active .rept directives.
115 std::vector<SMLoc> ActiveRept;
117 /// Boolean tracking whether macro substitution is enabled.
118 unsigned MacrosEnabled : 1;
120 /// Flag tracking whether any errors have been encountered.
121 unsigned HadError : 1;
123 /// The values from the last parsed cpp hash file line comment if any.
124 StringRef CppHashFilename;
125 int64_t CppHashLineNumber;
128 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
129 unsigned AssemblerDialect;
132 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
133 const MCAsmInfo &MAI);
136 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
138 void AddDirectiveHandler(MCAsmParserExtension *Object,
140 DirectiveHandler Handler) {
141 DirectiveMap[Directive] = std::make_pair(Object, Handler);
145 /// @name MCAsmParser Interface
148 virtual SourceMgr &getSourceManager() { return SrcMgr; }
149 virtual MCAsmLexer &getLexer() { return Lexer; }
150 virtual MCContext &getContext() { return Ctx; }
151 virtual MCStreamer &getStreamer() { return Out; }
152 virtual unsigned getAssemblerDialect() {
153 if (AssemblerDialect == ~0U)
154 return MAI.getAssemblerDialect();
156 return AssemblerDialect;
158 virtual void setAssemblerDialect(unsigned i) {
159 AssemblerDialect = i;
162 virtual bool Warning(SMLoc L, const Twine &Msg,
163 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
164 virtual bool Error(SMLoc L, const Twine &Msg,
165 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
167 const AsmToken &Lex();
169 bool ParseExpression(const MCExpr *&Res);
170 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
171 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
172 virtual bool ParseAbsoluteExpression(int64_t &Res);
177 void CheckForValidSection();
179 bool ParseStatement();
180 void EatToEndOfLine();
181 bool ParseCppHashLineFilenameComment(const SMLoc &L);
183 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
184 bool expandMacro(SmallString<256> &Buf, StringRef Body,
185 const std::vector<StringRef> &Parameters,
186 const std::vector<std::vector<AsmToken> > &A,
188 void HandleMacroExit();
190 void PrintMacroInstantiations();
191 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
192 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
193 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
195 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
197 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
198 bool EnterIncludeFile(const std::string &Filename);
199 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
200 /// This returns true on failure.
201 bool ProcessIncbinFile(const std::string &Filename);
203 /// \brief Reset the current lexer position to that given by \arg Loc. The
204 /// current token is not set; clients should ensure Lex() is called
206 void JumpToLoc(SMLoc Loc);
208 void EatToEndOfStatement();
210 /// \brief Parse up to the end of statement and a return the contents from the
211 /// current token until the end of the statement; the current token on exit
212 /// will be either the EndOfStatement or EOF.
213 StringRef ParseStringToEndOfStatement();
215 /// \brief Parse until the end of a statement or a comma is encountered,
216 /// return the contents from the current token up to the end or comma.
217 StringRef ParseStringToComma();
219 bool ParseAssignment(StringRef Name, bool allow_redef);
221 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
222 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
223 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
224 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
226 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
227 /// and set \arg Res to the identifier contents.
228 bool ParseIdentifier(StringRef &Res);
230 // Directive Parsing.
232 // ".ascii", ".asciiz", ".string"
233 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
234 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
235 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
236 bool ParseDirectiveFill(); // ".fill"
237 bool ParseDirectiveSpace(); // ".space"
238 bool ParseDirectiveZero(); // ".zero"
239 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
240 bool ParseDirectiveOrg(); // ".org"
241 // ".align{,32}", ".p2align{,w,l}"
242 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
244 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
245 /// accepts a single symbol (which should be a label or an external).
246 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
248 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
250 bool ParseDirectiveAbort(); // ".abort"
251 bool ParseDirectiveInclude(); // ".include"
252 bool ParseDirectiveIncbin(); // ".incbin"
254 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
255 // ".ifb" or ".ifnb", depending on ExpectBlank.
256 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
257 // ".ifc" or ".ifnc", depending on ExpectEqual.
258 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
259 // ".ifdef" or ".ifndef", depending on expect_defined
260 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
261 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
262 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
263 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
265 /// ParseEscapedString - Parse the current token as a string which may include
266 /// escaped characters and return the string contents.
267 bool ParseEscapedString(std::string &Data);
269 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
270 MCSymbolRefExpr::VariantKind Variant);
272 bool ParseDirectiveRept(SMLoc DirectiveLoc);
273 bool ParseDirectiveEndRept(SMLoc DirectiveLoc);
276 /// \brief Generic implementations of directive handling, etc. which is shared
277 /// (or the default, at least) for all assembler parser.
278 class GenericAsmParser : public MCAsmParserExtension {
279 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
280 void AddDirectiveHandler(StringRef Directive) {
281 getParser().AddDirectiveHandler(this, Directive,
282 HandleDirective<GenericAsmParser, Handler>);
285 GenericAsmParser() {}
287 AsmParser &getParser() {
288 return (AsmParser&) this->MCAsmParserExtension::getParser();
291 virtual void Initialize(MCAsmParser &Parser) {
292 // Call the base implementation.
293 this->MCAsmParserExtension::Initialize(Parser);
295 // Debugging directives.
296 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
297 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
298 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
299 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
302 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
308 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
310 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
311 ".cfi_def_cfa_offset");
312 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
313 ".cfi_adjust_cfa_offset");
314 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
315 ".cfi_def_cfa_register");
316 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
318 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
321 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
323 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
325 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
327 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
329 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
331 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
333 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
335 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
338 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
340 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
342 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
343 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
344 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
345 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
347 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
348 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
351 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
353 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
354 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
355 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
356 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
357 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
358 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
359 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
360 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
361 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
362 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
363 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
364 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
365 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
366 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
367 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
368 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
369 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
370 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
371 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
372 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
374 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
375 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
376 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
377 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
379 bool ParseDirectiveLEB128(StringRef, SMLoc);
386 extern MCAsmParserExtension *createDarwinAsmParser();
387 extern MCAsmParserExtension *createELFAsmParser();
388 extern MCAsmParserExtension *createCOFFAsmParser();
392 enum { DEFAULT_ADDRSPACE = 0 };
394 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
395 MCStreamer &_Out, const MCAsmInfo &_MAI)
396 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
397 GenericParser(new GenericAsmParser), PlatformParser(0),
398 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
399 AssemblerDialect(~0U) {
400 // Save the old handler.
401 SavedDiagHandler = SrcMgr.getDiagHandler();
402 SavedDiagContext = SrcMgr.getDiagContext();
403 // Set our own handler which calls the saved handler.
404 SrcMgr.setDiagHandler(DiagHandler, this);
405 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
407 // Initialize the generic parser.
408 GenericParser->Initialize(*this);
410 // Initialize the platform / file format parser.
412 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
414 if (_MAI.hasMicrosoftFastStdCallMangling()) {
415 PlatformParser = createCOFFAsmParser();
416 PlatformParser->Initialize(*this);
417 } else if (_MAI.hasSubsectionsViaSymbols()) {
418 PlatformParser = createDarwinAsmParser();
419 PlatformParser->Initialize(*this);
421 PlatformParser = createELFAsmParser();
422 PlatformParser->Initialize(*this);
426 AsmParser::~AsmParser() {
427 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
429 // Destroy any macros.
430 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
431 ie = MacroMap.end(); it != ie; ++it)
432 delete it->getValue();
434 delete PlatformParser;
435 delete GenericParser;
438 void AsmParser::PrintMacroInstantiations() {
439 // Print the active macro instantiation stack.
440 for (std::vector<MacroInstantiation*>::const_reverse_iterator
441 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
442 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
443 "while in macro instantiation");
446 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
447 if (FatalAssemblerWarnings)
448 return Error(L, Msg, Ranges);
449 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
450 PrintMacroInstantiations();
454 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
456 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
457 PrintMacroInstantiations();
461 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
462 std::string IncludedFile;
463 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
469 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
474 /// Process the specified .incbin file by seaching for it in the include paths
475 /// then just emiting the byte contents of the file to the streamer. This
476 /// returns true on failure.
477 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
478 std::string IncludedFile;
479 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
483 // Pick up the bytes from the file and emit them.
484 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
489 void AsmParser::JumpToLoc(SMLoc Loc) {
490 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
491 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
494 const AsmToken &AsmParser::Lex() {
495 const AsmToken *tok = &Lexer.Lex();
497 if (tok->is(AsmToken::Eof)) {
498 // If this is the end of an included file, pop the parent file off the
500 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
501 if (ParentIncludeLoc != SMLoc()) {
502 JumpToLoc(ParentIncludeLoc);
507 if (tok->is(AsmToken::Error))
508 Error(Lexer.getErrLoc(), Lexer.getErr());
513 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
514 // Create the initial section, if requested.
515 if (!NoInitialTextSection)
522 AsmCond StartingCondState = TheCondState;
524 // If we are generating dwarf for assembly source files save the initial text
525 // section and generate a .file directive.
526 if (getContext().getGenDwarfForAssembly()) {
527 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
528 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
529 getStreamer().EmitLabel(SectionStartSym);
530 getContext().setGenDwarfSectionStartSym(SectionStartSym);
531 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
532 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
535 // While we have input, parse each statement.
536 while (Lexer.isNot(AsmToken::Eof)) {
537 if (!ParseStatement()) continue;
539 // We had an error, validate that one was emitted and recover by skipping to
541 assert(HadError && "Parse statement returned an error, but none emitted!");
542 EatToEndOfStatement();
545 if (TheCondState.TheCond != StartingCondState.TheCond ||
546 TheCondState.Ignore != StartingCondState.Ignore)
547 return TokError("unmatched .ifs or .elses");
549 // Check to see there are no empty DwarfFile slots.
550 const std::vector<MCDwarfFile *> &MCDwarfFiles =
551 getContext().getMCDwarfFiles();
552 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
553 if (!MCDwarfFiles[i])
554 TokError("unassigned file number: " + Twine(i) + " for .file directives");
557 // Check to see that all assembler local symbols were actually defined.
558 // Targets that don't do subsections via symbols may not want this, though,
559 // so conservatively exclude them. Only do this if we're finalizing, though,
560 // as otherwise we won't necessarilly have seen everything yet.
561 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
562 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
563 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
566 MCSymbol *Sym = i->getValue();
567 // Variable symbols may not be marked as defined, so check those
568 // explicitly. If we know it's a variable, we have a definition for
569 // the purposes of this check.
570 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
571 // FIXME: We would really like to refer back to where the symbol was
572 // first referenced for a source location. We need to add something
573 // to track that. Currently, we just point to the end of the file.
574 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
575 "assembler local symbol '" + Sym->getName() +
581 // Finalize the output stream if there are no errors and if the client wants
583 if (!HadError && !NoFinalize)
589 void AsmParser::CheckForValidSection() {
590 if (!getStreamer().getCurrentSection()) {
591 TokError("expected section directive before assembly directive");
592 Out.SwitchSection(Ctx.getMachOSection(
594 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
595 0, SectionKind::getText()));
599 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
600 void AsmParser::EatToEndOfStatement() {
601 while (Lexer.isNot(AsmToken::EndOfStatement) &&
602 Lexer.isNot(AsmToken::Eof))
606 if (Lexer.is(AsmToken::EndOfStatement))
610 StringRef AsmParser::ParseStringToEndOfStatement() {
611 const char *Start = getTok().getLoc().getPointer();
613 while (Lexer.isNot(AsmToken::EndOfStatement) &&
614 Lexer.isNot(AsmToken::Eof))
617 const char *End = getTok().getLoc().getPointer();
618 return StringRef(Start, End - Start);
621 StringRef AsmParser::ParseStringToComma() {
622 const char *Start = getTok().getLoc().getPointer();
624 while (Lexer.isNot(AsmToken::EndOfStatement) &&
625 Lexer.isNot(AsmToken::Comma) &&
626 Lexer.isNot(AsmToken::Eof))
629 const char *End = getTok().getLoc().getPointer();
630 return StringRef(Start, End - Start);
633 /// ParseParenExpr - Parse a paren expression and return it.
634 /// NOTE: This assumes the leading '(' has already been consumed.
636 /// parenexpr ::= expr)
638 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
639 if (ParseExpression(Res)) return true;
640 if (Lexer.isNot(AsmToken::RParen))
641 return TokError("expected ')' in parentheses expression");
642 EndLoc = Lexer.getLoc();
647 /// ParseBracketExpr - Parse a bracket expression and return it.
648 /// NOTE: This assumes the leading '[' has already been consumed.
650 /// bracketexpr ::= expr]
652 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
653 if (ParseExpression(Res)) return true;
654 if (Lexer.isNot(AsmToken::RBrac))
655 return TokError("expected ']' in brackets expression");
656 EndLoc = Lexer.getLoc();
661 /// ParsePrimaryExpr - Parse a primary expression and return it.
662 /// primaryexpr ::= (parenexpr
663 /// primaryexpr ::= symbol
664 /// primaryexpr ::= number
665 /// primaryexpr ::= '.'
666 /// primaryexpr ::= ~,+,- primaryexpr
667 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
668 switch (Lexer.getKind()) {
670 return TokError("unknown token in expression");
671 // If we have an error assume that we've already handled it.
672 case AsmToken::Error:
674 case AsmToken::Exclaim:
675 Lex(); // Eat the operator.
676 if (ParsePrimaryExpr(Res, EndLoc))
678 Res = MCUnaryExpr::CreateLNot(Res, getContext());
680 case AsmToken::Dollar:
681 case AsmToken::String:
682 case AsmToken::Identifier: {
683 EndLoc = Lexer.getLoc();
685 StringRef Identifier;
686 if (ParseIdentifier(Identifier))
689 // This is a symbol reference.
690 std::pair<StringRef, StringRef> Split = Identifier.split('@');
691 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
693 // Lookup the symbol variant if used.
694 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
695 if (Split.first.size() != Identifier.size()) {
696 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
697 if (Variant == MCSymbolRefExpr::VK_Invalid) {
698 Variant = MCSymbolRefExpr::VK_None;
699 return TokError("invalid variant '" + Split.second + "'");
703 // If this is an absolute variable reference, substitute it now to preserve
704 // semantics in the face of reassignment.
705 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
707 return Error(EndLoc, "unexpected modifier on variable reference");
709 Res = Sym->getVariableValue();
713 // Otherwise create a symbol ref.
714 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
717 case AsmToken::Integer: {
718 SMLoc Loc = getTok().getLoc();
719 int64_t IntVal = getTok().getIntVal();
720 Res = MCConstantExpr::Create(IntVal, getContext());
721 EndLoc = Lexer.getLoc();
723 // Look for 'b' or 'f' following an Integer as a directional label
724 if (Lexer.getKind() == AsmToken::Identifier) {
725 StringRef IDVal = getTok().getString();
726 if (IDVal == "f" || IDVal == "b"){
727 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
728 IDVal == "f" ? 1 : 0);
729 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
731 if(IDVal == "b" && Sym->isUndefined())
732 return Error(Loc, "invalid reference to undefined symbol");
733 EndLoc = Lexer.getLoc();
734 Lex(); // Eat identifier.
739 case AsmToken::Real: {
740 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
741 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
742 Res = MCConstantExpr::Create(IntVal, getContext());
746 case AsmToken::Dot: {
747 // This is a '.' reference, which references the current PC. Emit a
748 // temporary label to the streamer and refer to it.
749 MCSymbol *Sym = Ctx.CreateTempSymbol();
751 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
752 EndLoc = Lexer.getLoc();
753 Lex(); // Eat identifier.
756 case AsmToken::LParen:
757 Lex(); // Eat the '('.
758 return ParseParenExpr(Res, EndLoc);
759 case AsmToken::LBrac:
760 if (!PlatformParser->HasBracketExpressions())
761 return TokError("brackets expression not supported on this target");
762 Lex(); // Eat the '['.
763 return ParseBracketExpr(Res, EndLoc);
764 case AsmToken::Minus:
765 Lex(); // Eat the operator.
766 if (ParsePrimaryExpr(Res, EndLoc))
768 Res = MCUnaryExpr::CreateMinus(Res, getContext());
771 Lex(); // Eat the operator.
772 if (ParsePrimaryExpr(Res, EndLoc))
774 Res = MCUnaryExpr::CreatePlus(Res, getContext());
776 case AsmToken::Tilde:
777 Lex(); // Eat the operator.
778 if (ParsePrimaryExpr(Res, EndLoc))
780 Res = MCUnaryExpr::CreateNot(Res, getContext());
785 bool AsmParser::ParseExpression(const MCExpr *&Res) {
787 return ParseExpression(Res, EndLoc);
791 AsmParser::ApplyModifierToExpr(const MCExpr *E,
792 MCSymbolRefExpr::VariantKind Variant) {
793 // Recurse over the given expression, rebuilding it to apply the given variant
794 // if there is exactly one symbol.
795 switch (E->getKind()) {
797 case MCExpr::Constant:
800 case MCExpr::SymbolRef: {
801 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
803 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
804 TokError("invalid variant on expression '" +
805 getTok().getIdentifier() + "' (already modified)");
809 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
812 case MCExpr::Unary: {
813 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
814 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
817 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
820 case MCExpr::Binary: {
821 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
822 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
823 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
828 if (!LHS) LHS = BE->getLHS();
829 if (!RHS) RHS = BE->getRHS();
831 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
835 llvm_unreachable("Invalid expression kind!");
838 /// ParseExpression - Parse an expression and return it.
840 /// expr ::= expr &&,|| expr -> lowest.
841 /// expr ::= expr |,^,&,! expr
842 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
843 /// expr ::= expr <<,>> expr
844 /// expr ::= expr +,- expr
845 /// expr ::= expr *,/,% expr -> highest.
846 /// expr ::= primaryexpr
848 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
849 // Parse the expression.
851 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
854 // As a special case, we support 'a op b @ modifier' by rewriting the
855 // expression to include the modifier. This is inefficient, but in general we
856 // expect users to use 'a@modifier op b'.
857 if (Lexer.getKind() == AsmToken::At) {
860 if (Lexer.isNot(AsmToken::Identifier))
861 return TokError("unexpected symbol modifier following '@'");
863 MCSymbolRefExpr::VariantKind Variant =
864 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
865 if (Variant == MCSymbolRefExpr::VK_Invalid)
866 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
868 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
870 return TokError("invalid modifier '" + getTok().getIdentifier() +
871 "' (no symbols present)");
878 // Try to constant fold it up front, if possible.
880 if (Res->EvaluateAsAbsolute(Value))
881 Res = MCConstantExpr::Create(Value, getContext());
886 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
888 return ParseParenExpr(Res, EndLoc) ||
889 ParseBinOpRHS(1, Res, EndLoc);
892 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
895 SMLoc StartLoc = Lexer.getLoc();
896 if (ParseExpression(Expr))
899 if (!Expr->EvaluateAsAbsolute(Res))
900 return Error(StartLoc, "expected absolute expression");
905 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
906 MCBinaryExpr::Opcode &Kind) {
909 return 0; // not a binop.
911 // Lowest Precedence: &&, ||
912 case AsmToken::AmpAmp:
913 Kind = MCBinaryExpr::LAnd;
915 case AsmToken::PipePipe:
916 Kind = MCBinaryExpr::LOr;
920 // Low Precedence: |, &, ^
922 // FIXME: gas seems to support '!' as an infix operator?
924 Kind = MCBinaryExpr::Or;
926 case AsmToken::Caret:
927 Kind = MCBinaryExpr::Xor;
930 Kind = MCBinaryExpr::And;
933 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
934 case AsmToken::EqualEqual:
935 Kind = MCBinaryExpr::EQ;
937 case AsmToken::ExclaimEqual:
938 case AsmToken::LessGreater:
939 Kind = MCBinaryExpr::NE;
942 Kind = MCBinaryExpr::LT;
944 case AsmToken::LessEqual:
945 Kind = MCBinaryExpr::LTE;
947 case AsmToken::Greater:
948 Kind = MCBinaryExpr::GT;
950 case AsmToken::GreaterEqual:
951 Kind = MCBinaryExpr::GTE;
954 // Intermediate Precedence: <<, >>
955 case AsmToken::LessLess:
956 Kind = MCBinaryExpr::Shl;
958 case AsmToken::GreaterGreater:
959 Kind = MCBinaryExpr::Shr;
962 // High Intermediate Precedence: +, -
964 Kind = MCBinaryExpr::Add;
966 case AsmToken::Minus:
967 Kind = MCBinaryExpr::Sub;
970 // Highest Precedence: *, /, %
972 Kind = MCBinaryExpr::Mul;
974 case AsmToken::Slash:
975 Kind = MCBinaryExpr::Div;
977 case AsmToken::Percent:
978 Kind = MCBinaryExpr::Mod;
984 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
985 /// Res contains the LHS of the expression on input.
986 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
989 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
990 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
992 // If the next token is lower precedence than we are allowed to eat, return
993 // successfully with what we ate already.
994 if (TokPrec < Precedence)
999 // Eat the next primary expression.
1001 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1003 // If BinOp binds less tightly with RHS than the operator after RHS, let
1004 // the pending operator take RHS as its LHS.
1005 MCBinaryExpr::Opcode Dummy;
1006 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1007 if (TokPrec < NextTokPrec) {
1008 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1011 // Merge LHS and RHS according to operator.
1012 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1020 /// ::= EndOfStatement
1021 /// ::= Label* Directive ...Operands... EndOfStatement
1022 /// ::= Label* Identifier OperandList* EndOfStatement
1023 bool AsmParser::ParseStatement() {
1024 if (Lexer.is(AsmToken::EndOfStatement)) {
1030 // Statements always start with an identifier or are a full line comment.
1031 AsmToken ID = getTok();
1032 SMLoc IDLoc = ID.getLoc();
1034 int64_t LocalLabelVal = -1;
1035 // A full line comment is a '#' as the first token.
1036 if (Lexer.is(AsmToken::Hash))
1037 return ParseCppHashLineFilenameComment(IDLoc);
1039 // Allow an integer followed by a ':' as a directional local label.
1040 if (Lexer.is(AsmToken::Integer)) {
1041 LocalLabelVal = getTok().getIntVal();
1042 if (LocalLabelVal < 0) {
1043 if (!TheCondState.Ignore)
1044 return TokError("unexpected token at start of statement");
1048 IDVal = getTok().getString();
1049 Lex(); // Consume the integer token to be used as an identifier token.
1050 if (Lexer.getKind() != AsmToken::Colon) {
1051 if (!TheCondState.Ignore)
1052 return TokError("unexpected token at start of statement");
1056 } else if (Lexer.is(AsmToken::Dot)) {
1057 // Treat '.' as a valid identifier in this context.
1061 } else if (ParseIdentifier(IDVal)) {
1062 if (!TheCondState.Ignore)
1063 return TokError("unexpected token at start of statement");
1068 // Handle conditional assembly here before checking for skipping. We
1069 // have to do this so that .endif isn't skipped in a ".if 0" block for
1072 return ParseDirectiveIf(IDLoc);
1073 if (IDVal == ".ifb")
1074 return ParseDirectiveIfb(IDLoc, true);
1075 if (IDVal == ".ifnb")
1076 return ParseDirectiveIfb(IDLoc, false);
1077 if (IDVal == ".ifc")
1078 return ParseDirectiveIfc(IDLoc, true);
1079 if (IDVal == ".ifnc")
1080 return ParseDirectiveIfc(IDLoc, false);
1081 if (IDVal == ".ifdef")
1082 return ParseDirectiveIfdef(IDLoc, true);
1083 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1084 return ParseDirectiveIfdef(IDLoc, false);
1085 if (IDVal == ".elseif")
1086 return ParseDirectiveElseIf(IDLoc);
1087 if (IDVal == ".else")
1088 return ParseDirectiveElse(IDLoc);
1089 if (IDVal == ".endif")
1090 return ParseDirectiveEndIf(IDLoc);
1092 // If we are in a ".if 0" block, ignore this statement.
1093 if (TheCondState.Ignore) {
1094 EatToEndOfStatement();
1098 // FIXME: Recurse on local labels?
1100 // See what kind of statement we have.
1101 switch (Lexer.getKind()) {
1102 case AsmToken::Colon: {
1103 CheckForValidSection();
1105 // identifier ':' -> Label.
1108 // Diagnose attempt to use '.' as a label.
1110 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1112 // Diagnose attempt to use a variable as a label.
1114 // FIXME: Diagnostics. Note the location of the definition as a label.
1115 // FIXME: This doesn't diagnose assignment to a symbol which has been
1116 // implicitly marked as external.
1118 if (LocalLabelVal == -1)
1119 Sym = getContext().GetOrCreateSymbol(IDVal);
1121 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1122 if (!Sym->isUndefined() || Sym->isVariable())
1123 return Error(IDLoc, "invalid symbol redefinition");
1128 // If we are generating dwarf for assembly source files then gather the
1129 // info to make a dwarf label entry for this label if needed.
1130 if (getContext().getGenDwarfForAssembly())
1131 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1134 // Consume any end of statement token, if present, to avoid spurious
1135 // AddBlankLine calls().
1136 if (Lexer.is(AsmToken::EndOfStatement)) {
1138 if (Lexer.is(AsmToken::Eof))
1142 return ParseStatement();
1145 case AsmToken::Equal:
1146 // identifier '=' ... -> assignment statement
1149 return ParseAssignment(IDVal, true);
1151 default: // Normal instruction or directive.
1155 // If macros are enabled, check to see if this is a macro instantiation.
1157 if (const Macro *M = MacroMap.lookup(IDVal))
1158 return HandleMacroEntry(IDVal, IDLoc, M);
1160 // Otherwise, we have a normal instruction or directive.
1161 if (IDVal[0] == '.' && IDVal != ".") {
1162 // Assembler features
1163 if (IDVal == ".set" || IDVal == ".equ")
1164 return ParseDirectiveSet(IDVal, true);
1165 if (IDVal == ".equiv")
1166 return ParseDirectiveSet(IDVal, false);
1170 if (IDVal == ".ascii")
1171 return ParseDirectiveAscii(IDVal, false);
1172 if (IDVal == ".asciz" || IDVal == ".string")
1173 return ParseDirectiveAscii(IDVal, true);
1175 if (IDVal == ".byte")
1176 return ParseDirectiveValue(1);
1177 if (IDVal == ".short")
1178 return ParseDirectiveValue(2);
1179 if (IDVal == ".value")
1180 return ParseDirectiveValue(2);
1181 if (IDVal == ".2byte")
1182 return ParseDirectiveValue(2);
1183 if (IDVal == ".long")
1184 return ParseDirectiveValue(4);
1185 if (IDVal == ".int")
1186 return ParseDirectiveValue(4);
1187 if (IDVal == ".4byte")
1188 return ParseDirectiveValue(4);
1189 if (IDVal == ".quad")
1190 return ParseDirectiveValue(8);
1191 if (IDVal == ".8byte")
1192 return ParseDirectiveValue(8);
1193 if (IDVal == ".single" || IDVal == ".float")
1194 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1195 if (IDVal == ".double")
1196 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1198 if (IDVal == ".align") {
1199 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1200 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1202 if (IDVal == ".align32") {
1203 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1204 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1206 if (IDVal == ".balign")
1207 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1208 if (IDVal == ".balignw")
1209 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1210 if (IDVal == ".balignl")
1211 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1212 if (IDVal == ".p2align")
1213 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1214 if (IDVal == ".p2alignw")
1215 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1216 if (IDVal == ".p2alignl")
1217 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1219 if (IDVal == ".org")
1220 return ParseDirectiveOrg();
1222 if (IDVal == ".fill")
1223 return ParseDirectiveFill();
1224 if (IDVal == ".space" || IDVal == ".skip")
1225 return ParseDirectiveSpace();
1226 if (IDVal == ".zero")
1227 return ParseDirectiveZero();
1229 // Symbol attribute directives
1231 if (IDVal == ".extern") {
1232 EatToEndOfStatement(); // .extern is the default, ignore it.
1235 if (IDVal == ".globl" || IDVal == ".global")
1236 return ParseDirectiveSymbolAttribute(MCSA_Global);
1237 if (IDVal == ".indirect_symbol")
1238 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1239 if (IDVal == ".lazy_reference")
1240 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1241 if (IDVal == ".no_dead_strip")
1242 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1243 if (IDVal == ".symbol_resolver")
1244 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1245 if (IDVal == ".private_extern")
1246 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1247 if (IDVal == ".reference")
1248 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1249 if (IDVal == ".weak_definition")
1250 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1251 if (IDVal == ".weak_reference")
1252 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1253 if (IDVal == ".weak_def_can_be_hidden")
1254 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1256 if (IDVal == ".comm" || IDVal == ".common")
1257 return ParseDirectiveComm(/*IsLocal=*/false);
1258 if (IDVal == ".lcomm")
1259 return ParseDirectiveComm(/*IsLocal=*/true);
1261 if (IDVal == ".abort")
1262 return ParseDirectiveAbort();
1263 if (IDVal == ".include")
1264 return ParseDirectiveInclude();
1265 if (IDVal == ".incbin")
1266 return ParseDirectiveIncbin();
1268 if (IDVal == ".code16" || IDVal == ".code16gcc")
1269 return TokError(Twine(IDVal) + " not supported yet");
1271 if (IDVal == ".rept")
1272 return ParseDirectiveRept(IDLoc);
1273 if (IDVal == ".endr")
1274 return ParseDirectiveEndRept(IDLoc);
1276 // Look up the handler in the handler table.
1277 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1278 DirectiveMap.lookup(IDVal);
1280 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1282 // Target hook for parsing target specific directives.
1283 if (!getTargetParser().ParseDirective(ID))
1286 return Error(IDLoc, "unknown directive");
1289 CheckForValidSection();
1291 // Canonicalize the opcode to lower case.
1292 SmallString<128> Opcode;
1293 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1294 Opcode.push_back(tolower(IDVal[i]));
1296 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1297 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1300 // Dump the parsed representation, if requested.
1301 if (getShowParsedOperands()) {
1302 SmallString<256> Str;
1303 raw_svector_ostream OS(Str);
1304 OS << "parsed instruction: [";
1305 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1308 ParsedOperands[i]->print(OS);
1312 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1315 // If we are generating dwarf for assembly source files and the current
1316 // section is the initial text section then generate a .loc directive for
1318 if (!HadError && getContext().getGenDwarfForAssembly() &&
1319 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1320 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1321 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1322 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1323 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1327 // If parsing succeeded, match the instruction.
1329 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1332 // Free any parsed operands.
1333 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1334 delete ParsedOperands[i];
1336 // Don't skip the rest of the line, the instruction parser is responsible for
1341 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1342 /// since they may not be able to be tokenized to get to the end of line token.
1343 void AsmParser::EatToEndOfLine() {
1344 if (!Lexer.is(AsmToken::EndOfStatement))
1345 Lexer.LexUntilEndOfLine();
1350 /// ParseCppHashLineFilenameComment as this:
1351 /// ::= # number "filename"
1352 /// or just as a full line comment if it doesn't have a number and a string.
1353 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1354 Lex(); // Eat the hash token.
1356 if (getLexer().isNot(AsmToken::Integer)) {
1357 // Consume the line since in cases it is not a well-formed line directive,
1358 // as if were simply a full line comment.
1363 int64_t LineNumber = getTok().getIntVal();
1366 if (getLexer().isNot(AsmToken::String)) {
1371 StringRef Filename = getTok().getString();
1372 // Get rid of the enclosing quotes.
1373 Filename = Filename.substr(1, Filename.size()-2);
1375 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1377 CppHashFilename = Filename;
1378 CppHashLineNumber = LineNumber;
1380 // Ignore any trailing characters, they're just comment.
1385 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1386 /// for the Filename and LineNo if any in the diagnostic.
1387 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1388 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1389 raw_ostream &OS = errs();
1391 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1392 const SMLoc &DiagLoc = Diag.getLoc();
1393 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1394 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1396 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1397 // before printing the message.
1398 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1399 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1400 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1401 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1404 // If we have not parsed a cpp hash line filename comment or the source
1405 // manager changed or buffer changed (like in a nested include) then just
1406 // print the normal diagnostic using its Filename and LineNo.
1407 if (!Parser->CppHashLineNumber ||
1408 &DiagSrcMgr != &Parser->SrcMgr ||
1409 DiagBuf != CppHashBuf) {
1410 if (Parser->SavedDiagHandler)
1411 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1417 // Use the CppHashFilename and calculate a line number based on the
1418 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1420 const std::string Filename = Parser->CppHashFilename;
1422 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1423 int CppHashLocLineNo =
1424 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1425 int LineNo = Parser->CppHashLineNumber - 1 +
1426 (DiagLocLineNo - CppHashLocLineNo);
1428 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1429 Filename, LineNo, Diag.getColumnNo(),
1430 Diag.getKind(), Diag.getMessage(),
1431 Diag.getLineContents(), Diag.getRanges());
1433 if (Parser->SavedDiagHandler)
1434 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1436 NewDiag.print(0, OS);
1439 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1440 const std::vector<StringRef> &Parameters,
1441 const std::vector<std::vector<AsmToken> > &A,
1443 raw_svector_ostream OS(Buf);
1444 unsigned NParameters = Parameters.size();
1445 if (NParameters != 0 && NParameters != A.size())
1446 return Error(L, "Wrong number of arguments");
1448 while (!Body.empty()) {
1449 // Scan for the next substitution.
1450 std::size_t End = Body.size(), Pos = 0;
1451 for (; Pos != End; ++Pos) {
1452 // Check for a substitution or escape.
1454 // This macro has no parameters, look for $0, $1, etc.
1455 if (Body[Pos] != '$' || Pos + 1 == End)
1458 char Next = Body[Pos + 1];
1459 if (Next == '$' || Next == 'n' || isdigit(Next))
1462 // This macro has parameters, look for \foo, \bar, etc.
1463 if (Body[Pos] == '\\' && Pos + 1 != End)
1469 OS << Body.slice(0, Pos);
1471 // Check if we reached the end.
1476 switch (Body[Pos+1]) {
1482 // $n => number of arguments
1487 // $[0-9] => argument
1489 // Missing arguments are ignored.
1490 unsigned Index = Body[Pos+1] - '0';
1491 if (Index >= A.size())
1494 // Otherwise substitute with the token values, with spaces eliminated.
1495 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1496 ie = A[Index].end(); it != ie; ++it)
1497 OS << it->getString();
1503 unsigned I = Pos + 1;
1504 while (isalnum(Body[I]) && I + 1 != End)
1507 const char *Begin = Body.data() + Pos +1;
1508 StringRef Argument(Begin, I - (Pos +1));
1510 for (; Index < NParameters; ++Index)
1511 if (Parameters[Index] == Argument)
1514 // FIXME: We should error at the macro definition.
1515 if (Index == NParameters)
1516 return Error(L, "Parameter not found");
1518 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1519 ie = A[Index].end(); it != ie; ++it)
1520 OS << it->getString();
1522 Pos += 1 + Argument.size();
1524 // Update the scan point.
1525 Body = Body.substr(Pos);
1528 // We include the .endmacro in the buffer as our queue to exit the macro
1530 OS << ".endmacro\n";
1534 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1536 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1540 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1542 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1543 // this, although we should protect against infinite loops.
1544 if (ActiveMacros.size() == 20)
1545 return TokError("macros cannot be nested more than 20 levels deep");
1547 // Parse the macro instantiation arguments.
1548 std::vector<std::vector<AsmToken> > MacroArguments;
1549 MacroArguments.push_back(std::vector<AsmToken>());
1550 unsigned ParenLevel = 0;
1552 if (Lexer.is(AsmToken::Eof))
1553 return TokError("unexpected token in macro instantiation");
1554 if (Lexer.is(AsmToken::EndOfStatement))
1557 // If we aren't inside parentheses and this is a comma, start a new token
1559 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1560 MacroArguments.push_back(std::vector<AsmToken>());
1562 // Adjust the current parentheses level.
1563 if (Lexer.is(AsmToken::LParen))
1565 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1568 // Append the token to the current argument list.
1569 MacroArguments.back().push_back(getTok());
1573 // If the last argument didn't end up with any tokens, it's not a real
1574 // argument and we should remove it from the list. This happens with either
1575 // a tailing comma or an empty argument list.
1576 if (MacroArguments.back().empty())
1577 MacroArguments.pop_back();
1579 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1580 // to hold the macro body with substitutions.
1581 SmallString<256> Buf;
1582 StringRef Body = M->Body;
1584 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1587 MemoryBuffer *Instantiation =
1588 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1590 // Create the macro instantiation object and add to the current macro
1591 // instantiation stack.
1592 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1595 ActiveMacros.push_back(MI);
1597 // Jump to the macro instantiation and prime the lexer.
1598 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1599 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1605 void AsmParser::HandleMacroExit() {
1606 // Jump to the EndOfStatement we should return to, and consume it.
1607 JumpToLoc(ActiveMacros.back()->ExitLoc);
1610 // Pop the instantiation entry.
1611 delete ActiveMacros.back();
1612 ActiveMacros.pop_back();
1615 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1616 switch (Value->getKind()) {
1617 case MCExpr::Binary: {
1618 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1619 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1622 case MCExpr::Target:
1623 case MCExpr::Constant:
1625 case MCExpr::SymbolRef: {
1626 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1628 return IsUsedIn(Sym, S.getVariableValue());
1632 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1635 llvm_unreachable("Unknown expr kind!");
1638 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1639 // FIXME: Use better location, we should use proper tokens.
1640 SMLoc EqualLoc = Lexer.getLoc();
1642 const MCExpr *Value;
1643 if (ParseExpression(Value))
1646 // Note: we don't count b as used in "a = b". This is to allow
1650 if (Lexer.isNot(AsmToken::EndOfStatement))
1651 return TokError("unexpected token in assignment");
1653 // Error on assignment to '.'.
1655 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1656 "(use '.space' or '.org').)"));
1659 // Eat the end of statement marker.
1662 // Validate that the LHS is allowed to be a variable (either it has not been
1663 // used as a symbol, or it is an absolute symbol).
1664 MCSymbol *Sym = getContext().LookupSymbol(Name);
1666 // Diagnose assignment to a label.
1668 // FIXME: Diagnostics. Note the location of the definition as a label.
1669 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1670 if (IsUsedIn(Sym, Value))
1671 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1672 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1673 ; // Allow redefinitions of undefined symbols only used in directives.
1674 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1675 ; // Allow redefinitions of variables that haven't yet been used.
1676 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1677 return Error(EqualLoc, "redefinition of '" + Name + "'");
1678 else if (!Sym->isVariable())
1679 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1680 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1681 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1684 // Don't count these checks as uses.
1685 Sym->setUsed(false);
1687 Sym = getContext().GetOrCreateSymbol(Name);
1689 // FIXME: Handle '.'.
1691 // Do the assignment.
1692 Out.EmitAssignment(Sym, Value);
1697 /// ParseIdentifier:
1700 bool AsmParser::ParseIdentifier(StringRef &Res) {
1701 // The assembler has relaxed rules for accepting identifiers, in particular we
1702 // allow things like '.globl $foo', which would normally be separate
1703 // tokens. At this level, we have already lexed so we cannot (currently)
1704 // handle this as a context dependent token, instead we detect adjacent tokens
1705 // and return the combined identifier.
1706 if (Lexer.is(AsmToken::Dollar)) {
1707 SMLoc DollarLoc = getLexer().getLoc();
1709 // Consume the dollar sign, and check for a following identifier.
1711 if (Lexer.isNot(AsmToken::Identifier))
1714 // We have a '$' followed by an identifier, make sure they are adjacent.
1715 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1718 // Construct the joined identifier and consume the token.
1719 Res = StringRef(DollarLoc.getPointer(),
1720 getTok().getIdentifier().size() + 1);
1725 if (Lexer.isNot(AsmToken::Identifier) &&
1726 Lexer.isNot(AsmToken::String))
1729 Res = getTok().getIdentifier();
1731 Lex(); // Consume the identifier token.
1736 /// ParseDirectiveSet:
1737 /// ::= .equ identifier ',' expression
1738 /// ::= .equiv identifier ',' expression
1739 /// ::= .set identifier ',' expression
1740 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1743 if (ParseIdentifier(Name))
1744 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1746 if (getLexer().isNot(AsmToken::Comma))
1747 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1750 return ParseAssignment(Name, allow_redef);
1753 bool AsmParser::ParseEscapedString(std::string &Data) {
1754 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1757 StringRef Str = getTok().getStringContents();
1758 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1759 if (Str[i] != '\\') {
1764 // Recognize escaped characters. Note that this escape semantics currently
1765 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1768 return TokError("unexpected backslash at end of string");
1770 // Recognize octal sequences.
1771 if ((unsigned) (Str[i] - '0') <= 7) {
1772 // Consume up to three octal characters.
1773 unsigned Value = Str[i] - '0';
1775 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1777 Value = Value * 8 + (Str[i] - '0');
1779 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1781 Value = Value * 8 + (Str[i] - '0');
1786 return TokError("invalid octal escape sequence (out of range)");
1788 Data += (unsigned char) Value;
1792 // Otherwise recognize individual escapes.
1795 // Just reject invalid escape sequences for now.
1796 return TokError("invalid escape sequence (unrecognized character)");
1798 case 'b': Data += '\b'; break;
1799 case 'f': Data += '\f'; break;
1800 case 'n': Data += '\n'; break;
1801 case 'r': Data += '\r'; break;
1802 case 't': Data += '\t'; break;
1803 case '"': Data += '"'; break;
1804 case '\\': Data += '\\'; break;
1811 /// ParseDirectiveAscii:
1812 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1813 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1814 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1815 CheckForValidSection();
1818 if (getLexer().isNot(AsmToken::String))
1819 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1822 if (ParseEscapedString(Data))
1825 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1827 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1831 if (getLexer().is(AsmToken::EndOfStatement))
1834 if (getLexer().isNot(AsmToken::Comma))
1835 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1844 /// ParseDirectiveValue
1845 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1846 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1847 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1848 CheckForValidSection();
1851 const MCExpr *Value;
1852 SMLoc ExprLoc = getLexer().getLoc();
1853 if (ParseExpression(Value))
1856 // Special case constant expressions to match code generator.
1857 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1858 assert(Size <= 8 && "Invalid size");
1859 uint64_t IntValue = MCE->getValue();
1860 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1861 return Error(ExprLoc, "literal value out of range for directive");
1862 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1864 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1866 if (getLexer().is(AsmToken::EndOfStatement))
1869 // FIXME: Improve diagnostic.
1870 if (getLexer().isNot(AsmToken::Comma))
1871 return TokError("unexpected token in directive");
1880 /// ParseDirectiveRealValue
1881 /// ::= (.single | .double) [ expression (, expression)* ]
1882 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1883 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1884 CheckForValidSection();
1887 // We don't truly support arithmetic on floating point expressions, so we
1888 // have to manually parse unary prefixes.
1890 if (getLexer().is(AsmToken::Minus)) {
1893 } else if (getLexer().is(AsmToken::Plus))
1896 if (getLexer().isNot(AsmToken::Integer) &&
1897 getLexer().isNot(AsmToken::Real) &&
1898 getLexer().isNot(AsmToken::Identifier))
1899 return TokError("unexpected token in directive");
1901 // Convert to an APFloat.
1902 APFloat Value(Semantics);
1903 StringRef IDVal = getTok().getString();
1904 if (getLexer().is(AsmToken::Identifier)) {
1905 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1906 Value = APFloat::getInf(Semantics);
1907 else if (!IDVal.compare_lower("nan"))
1908 Value = APFloat::getNaN(Semantics, false, ~0);
1910 return TokError("invalid floating point literal");
1911 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1912 APFloat::opInvalidOp)
1913 return TokError("invalid floating point literal");
1917 // Consume the numeric token.
1920 // Emit the value as an integer.
1921 APInt AsInt = Value.bitcastToAPInt();
1922 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1923 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1925 if (getLexer().is(AsmToken::EndOfStatement))
1928 if (getLexer().isNot(AsmToken::Comma))
1929 return TokError("unexpected token in directive");
1938 /// ParseDirectiveSpace
1939 /// ::= .space expression [ , expression ]
1940 bool AsmParser::ParseDirectiveSpace() {
1941 CheckForValidSection();
1944 if (ParseAbsoluteExpression(NumBytes))
1947 int64_t FillExpr = 0;
1948 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1949 if (getLexer().isNot(AsmToken::Comma))
1950 return TokError("unexpected token in '.space' directive");
1953 if (ParseAbsoluteExpression(FillExpr))
1956 if (getLexer().isNot(AsmToken::EndOfStatement))
1957 return TokError("unexpected token in '.space' directive");
1963 return TokError("invalid number of bytes in '.space' directive");
1965 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1966 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1971 /// ParseDirectiveZero
1972 /// ::= .zero expression
1973 bool AsmParser::ParseDirectiveZero() {
1974 CheckForValidSection();
1977 if (ParseAbsoluteExpression(NumBytes))
1981 if (getLexer().is(AsmToken::Comma)) {
1983 if (ParseAbsoluteExpression(Val))
1987 if (getLexer().isNot(AsmToken::EndOfStatement))
1988 return TokError("unexpected token in '.zero' directive");
1992 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1997 /// ParseDirectiveFill
1998 /// ::= .fill expression , expression , expression
1999 bool AsmParser::ParseDirectiveFill() {
2000 CheckForValidSection();
2003 if (ParseAbsoluteExpression(NumValues))
2006 if (getLexer().isNot(AsmToken::Comma))
2007 return TokError("unexpected token in '.fill' directive");
2011 if (ParseAbsoluteExpression(FillSize))
2014 if (getLexer().isNot(AsmToken::Comma))
2015 return TokError("unexpected token in '.fill' directive");
2019 if (ParseAbsoluteExpression(FillExpr))
2022 if (getLexer().isNot(AsmToken::EndOfStatement))
2023 return TokError("unexpected token in '.fill' directive");
2027 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2028 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2030 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2031 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2036 /// ParseDirectiveOrg
2037 /// ::= .org expression [ , expression ]
2038 bool AsmParser::ParseDirectiveOrg() {
2039 CheckForValidSection();
2041 const MCExpr *Offset;
2042 SMLoc Loc = getTok().getLoc();
2043 if (ParseExpression(Offset))
2046 // Parse optional fill expression.
2047 int64_t FillExpr = 0;
2048 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2049 if (getLexer().isNot(AsmToken::Comma))
2050 return TokError("unexpected token in '.org' directive");
2053 if (ParseAbsoluteExpression(FillExpr))
2056 if (getLexer().isNot(AsmToken::EndOfStatement))
2057 return TokError("unexpected token in '.org' directive");
2062 // Only limited forms of relocatable expressions are accepted here, it
2063 // has to be relative to the current section. The streamer will return
2064 // 'true' if the expression wasn't evaluatable.
2065 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2066 return Error(Loc, "expected assembly-time absolute expression");
2071 /// ParseDirectiveAlign
2072 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2073 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2074 CheckForValidSection();
2076 SMLoc AlignmentLoc = getLexer().getLoc();
2078 if (ParseAbsoluteExpression(Alignment))
2082 bool HasFillExpr = false;
2083 int64_t FillExpr = 0;
2084 int64_t MaxBytesToFill = 0;
2085 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2086 if (getLexer().isNot(AsmToken::Comma))
2087 return TokError("unexpected token in directive");
2090 // The fill expression can be omitted while specifying a maximum number of
2091 // alignment bytes, e.g:
2093 if (getLexer().isNot(AsmToken::Comma)) {
2095 if (ParseAbsoluteExpression(FillExpr))
2099 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2100 if (getLexer().isNot(AsmToken::Comma))
2101 return TokError("unexpected token in directive");
2104 MaxBytesLoc = getLexer().getLoc();
2105 if (ParseAbsoluteExpression(MaxBytesToFill))
2108 if (getLexer().isNot(AsmToken::EndOfStatement))
2109 return TokError("unexpected token in directive");
2118 // Compute alignment in bytes.
2120 // FIXME: Diagnose overflow.
2121 if (Alignment >= 32) {
2122 Error(AlignmentLoc, "invalid alignment value");
2126 Alignment = 1ULL << Alignment;
2129 // Diagnose non-sensical max bytes to align.
2130 if (MaxBytesLoc.isValid()) {
2131 if (MaxBytesToFill < 1) {
2132 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2133 "many bytes, ignoring maximum bytes expression");
2137 if (MaxBytesToFill >= Alignment) {
2138 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2144 // Check whether we should use optimal code alignment for this .align
2146 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2147 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2148 ValueSize == 1 && UseCodeAlign) {
2149 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2151 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2152 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2159 /// ParseDirectiveSymbolAttribute
2160 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2161 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2162 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2165 SMLoc Loc = getTok().getLoc();
2167 if (ParseIdentifier(Name))
2168 return Error(Loc, "expected identifier in directive");
2170 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2172 // Assembler local symbols don't make any sense here. Complain loudly.
2173 if (Sym->isTemporary())
2174 return Error(Loc, "non-local symbol required in directive");
2176 getStreamer().EmitSymbolAttribute(Sym, Attr);
2178 if (getLexer().is(AsmToken::EndOfStatement))
2181 if (getLexer().isNot(AsmToken::Comma))
2182 return TokError("unexpected token in directive");
2191 /// ParseDirectiveComm
2192 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2193 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2194 CheckForValidSection();
2196 SMLoc IDLoc = getLexer().getLoc();
2198 if (ParseIdentifier(Name))
2199 return TokError("expected identifier in directive");
2201 // Handle the identifier as the key symbol.
2202 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2204 if (getLexer().isNot(AsmToken::Comma))
2205 return TokError("unexpected token in directive");
2209 SMLoc SizeLoc = getLexer().getLoc();
2210 if (ParseAbsoluteExpression(Size))
2213 int64_t Pow2Alignment = 0;
2214 SMLoc Pow2AlignmentLoc;
2215 if (getLexer().is(AsmToken::Comma)) {
2217 Pow2AlignmentLoc = getLexer().getLoc();
2218 if (ParseAbsoluteExpression(Pow2Alignment))
2221 // If this target takes alignments in bytes (not log) validate and convert.
2222 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2223 if (!isPowerOf2_64(Pow2Alignment))
2224 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2225 Pow2Alignment = Log2_64(Pow2Alignment);
2229 if (getLexer().isNot(AsmToken::EndOfStatement))
2230 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2234 // NOTE: a size of zero for a .comm should create a undefined symbol
2235 // but a size of .lcomm creates a bss symbol of size zero.
2237 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2238 "be less than zero");
2240 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2241 // may internally end up wanting an alignment in bytes.
2242 // FIXME: Diagnose overflow.
2243 if (Pow2Alignment < 0)
2244 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2245 "alignment, can't be less than zero");
2247 if (!Sym->isUndefined())
2248 return Error(IDLoc, "invalid symbol redefinition");
2250 // '.lcomm' is equivalent to '.zerofill'.
2251 // Create the Symbol as a common or local common with Size and Pow2Alignment
2253 getStreamer().EmitZerofill(Ctx.getMachOSection(
2254 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2255 0, SectionKind::getBSS()),
2256 Sym, Size, 1 << Pow2Alignment);
2260 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2264 /// ParseDirectiveAbort
2265 /// ::= .abort [... message ...]
2266 bool AsmParser::ParseDirectiveAbort() {
2267 // FIXME: Use loc from directive.
2268 SMLoc Loc = getLexer().getLoc();
2270 StringRef Str = ParseStringToEndOfStatement();
2271 if (getLexer().isNot(AsmToken::EndOfStatement))
2272 return TokError("unexpected token in '.abort' directive");
2277 Error(Loc, ".abort detected. Assembly stopping.");
2279 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2280 // FIXME: Actually abort assembly here.
2285 /// ParseDirectiveInclude
2286 /// ::= .include "filename"
2287 bool AsmParser::ParseDirectiveInclude() {
2288 if (getLexer().isNot(AsmToken::String))
2289 return TokError("expected string in '.include' directive");
2291 std::string Filename = getTok().getString();
2292 SMLoc IncludeLoc = getLexer().getLoc();
2295 if (getLexer().isNot(AsmToken::EndOfStatement))
2296 return TokError("unexpected token in '.include' directive");
2298 // Strip the quotes.
2299 Filename = Filename.substr(1, Filename.size()-2);
2301 // Attempt to switch the lexer to the included file before consuming the end
2302 // of statement to avoid losing it when we switch.
2303 if (EnterIncludeFile(Filename)) {
2304 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2311 /// ParseDirectiveIncbin
2312 /// ::= .incbin "filename"
2313 bool AsmParser::ParseDirectiveIncbin() {
2314 if (getLexer().isNot(AsmToken::String))
2315 return TokError("expected string in '.incbin' directive");
2317 std::string Filename = getTok().getString();
2318 SMLoc IncbinLoc = getLexer().getLoc();
2321 if (getLexer().isNot(AsmToken::EndOfStatement))
2322 return TokError("unexpected token in '.incbin' directive");
2324 // Strip the quotes.
2325 Filename = Filename.substr(1, Filename.size()-2);
2327 // Attempt to process the included file.
2328 if (ProcessIncbinFile(Filename)) {
2329 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2336 /// ParseDirectiveIf
2337 /// ::= .if expression
2338 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2339 TheCondStack.push_back(TheCondState);
2340 TheCondState.TheCond = AsmCond::IfCond;
2341 if(TheCondState.Ignore) {
2342 EatToEndOfStatement();
2346 if (ParseAbsoluteExpression(ExprValue))
2349 if (getLexer().isNot(AsmToken::EndOfStatement))
2350 return TokError("unexpected token in '.if' directive");
2354 TheCondState.CondMet = ExprValue;
2355 TheCondState.Ignore = !TheCondState.CondMet;
2361 /// ParseDirectiveIfb
2363 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2364 TheCondStack.push_back(TheCondState);
2365 TheCondState.TheCond = AsmCond::IfCond;
2367 if(TheCondState.Ignore) {
2368 EatToEndOfStatement();
2370 StringRef Str = ParseStringToEndOfStatement();
2372 if (getLexer().isNot(AsmToken::EndOfStatement))
2373 return TokError("unexpected token in '.ifb' directive");
2377 TheCondState.CondMet = ExpectBlank == Str.empty();
2378 TheCondState.Ignore = !TheCondState.CondMet;
2384 /// ParseDirectiveIfc
2385 /// ::= .ifc string1, string2
2386 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2387 TheCondStack.push_back(TheCondState);
2388 TheCondState.TheCond = AsmCond::IfCond;
2390 if(TheCondState.Ignore) {
2391 EatToEndOfStatement();
2393 StringRef Str1 = ParseStringToComma();
2395 if (getLexer().isNot(AsmToken::Comma))
2396 return TokError("unexpected token in '.ifc' directive");
2400 StringRef Str2 = ParseStringToEndOfStatement();
2402 if (getLexer().isNot(AsmToken::EndOfStatement))
2403 return TokError("unexpected token in '.ifc' directive");
2407 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2408 TheCondState.Ignore = !TheCondState.CondMet;
2414 /// ParseDirectiveIfdef
2415 /// ::= .ifdef symbol
2416 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2418 TheCondStack.push_back(TheCondState);
2419 TheCondState.TheCond = AsmCond::IfCond;
2421 if (TheCondState.Ignore) {
2422 EatToEndOfStatement();
2424 if (ParseIdentifier(Name))
2425 return TokError("expected identifier after '.ifdef'");
2429 MCSymbol *Sym = getContext().LookupSymbol(Name);
2432 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2434 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2435 TheCondState.Ignore = !TheCondState.CondMet;
2441 /// ParseDirectiveElseIf
2442 /// ::= .elseif expression
2443 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2444 if (TheCondState.TheCond != AsmCond::IfCond &&
2445 TheCondState.TheCond != AsmCond::ElseIfCond)
2446 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2448 TheCondState.TheCond = AsmCond::ElseIfCond;
2450 bool LastIgnoreState = false;
2451 if (!TheCondStack.empty())
2452 LastIgnoreState = TheCondStack.back().Ignore;
2453 if (LastIgnoreState || TheCondState.CondMet) {
2454 TheCondState.Ignore = true;
2455 EatToEndOfStatement();
2459 if (ParseAbsoluteExpression(ExprValue))
2462 if (getLexer().isNot(AsmToken::EndOfStatement))
2463 return TokError("unexpected token in '.elseif' directive");
2466 TheCondState.CondMet = ExprValue;
2467 TheCondState.Ignore = !TheCondState.CondMet;
2473 /// ParseDirectiveElse
2475 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2476 if (getLexer().isNot(AsmToken::EndOfStatement))
2477 return TokError("unexpected token in '.else' directive");
2481 if (TheCondState.TheCond != AsmCond::IfCond &&
2482 TheCondState.TheCond != AsmCond::ElseIfCond)
2483 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2485 TheCondState.TheCond = AsmCond::ElseCond;
2486 bool LastIgnoreState = false;
2487 if (!TheCondStack.empty())
2488 LastIgnoreState = TheCondStack.back().Ignore;
2489 if (LastIgnoreState || TheCondState.CondMet)
2490 TheCondState.Ignore = true;
2492 TheCondState.Ignore = false;
2497 /// ParseDirectiveEndIf
2499 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2500 if (getLexer().isNot(AsmToken::EndOfStatement))
2501 return TokError("unexpected token in '.endif' directive");
2505 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2506 TheCondStack.empty())
2507 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2509 if (!TheCondStack.empty()) {
2510 TheCondState = TheCondStack.back();
2511 TheCondStack.pop_back();
2517 /// ParseDirectiveFile
2518 /// ::= .file [number] filename
2519 /// ::= .file number directory filename
2520 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2521 // FIXME: I'm not sure what this is.
2522 int64_t FileNumber = -1;
2523 SMLoc FileNumberLoc = getLexer().getLoc();
2524 if (getLexer().is(AsmToken::Integer)) {
2525 FileNumber = getTok().getIntVal();
2529 return TokError("file number less than one");
2532 if (getLexer().isNot(AsmToken::String))
2533 return TokError("unexpected token in '.file' directive");
2535 // Usually the directory and filename together, otherwise just the directory.
2536 StringRef Path = getTok().getString();
2537 Path = Path.substr(1, Path.size()-2);
2540 StringRef Directory;
2542 if (getLexer().is(AsmToken::String)) {
2543 if (FileNumber == -1)
2544 return TokError("explicit path specified, but no file number");
2545 Filename = getTok().getString();
2546 Filename = Filename.substr(1, Filename.size()-2);
2553 if (getLexer().isNot(AsmToken::EndOfStatement))
2554 return TokError("unexpected token in '.file' directive");
2556 if (FileNumber == -1)
2557 getStreamer().EmitFileDirective(Filename);
2559 if (getContext().getGenDwarfForAssembly() == true)
2560 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2561 "used to generate dwarf debug info for assembly code");
2563 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2564 Error(FileNumberLoc, "file number already allocated");
2570 /// ParseDirectiveLine
2571 /// ::= .line [number]
2572 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2573 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2574 if (getLexer().isNot(AsmToken::Integer))
2575 return TokError("unexpected token in '.line' directive");
2577 int64_t LineNumber = getTok().getIntVal();
2581 // FIXME: Do something with the .line.
2584 if (getLexer().isNot(AsmToken::EndOfStatement))
2585 return TokError("unexpected token in '.line' directive");
2591 /// ParseDirectiveLoc
2592 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2593 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2594 /// The first number is a file number, must have been previously assigned with
2595 /// a .file directive, the second number is the line number and optionally the
2596 /// third number is a column position (zero if not specified). The remaining
2597 /// optional items are .loc sub-directives.
2598 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2600 if (getLexer().isNot(AsmToken::Integer))
2601 return TokError("unexpected token in '.loc' directive");
2602 int64_t FileNumber = getTok().getIntVal();
2604 return TokError("file number less than one in '.loc' directive");
2605 if (!getContext().isValidDwarfFileNumber(FileNumber))
2606 return TokError("unassigned file number in '.loc' directive");
2609 int64_t LineNumber = 0;
2610 if (getLexer().is(AsmToken::Integer)) {
2611 LineNumber = getTok().getIntVal();
2613 return TokError("line number less than one in '.loc' directive");
2617 int64_t ColumnPos = 0;
2618 if (getLexer().is(AsmToken::Integer)) {
2619 ColumnPos = getTok().getIntVal();
2621 return TokError("column position less than zero in '.loc' directive");
2625 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2627 int64_t Discriminator = 0;
2628 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2630 if (getLexer().is(AsmToken::EndOfStatement))
2634 SMLoc Loc = getTok().getLoc();
2635 if (getParser().ParseIdentifier(Name))
2636 return TokError("unexpected token in '.loc' directive");
2638 if (Name == "basic_block")
2639 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2640 else if (Name == "prologue_end")
2641 Flags |= DWARF2_FLAG_PROLOGUE_END;
2642 else if (Name == "epilogue_begin")
2643 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2644 else if (Name == "is_stmt") {
2645 SMLoc Loc = getTok().getLoc();
2646 const MCExpr *Value;
2647 if (getParser().ParseExpression(Value))
2649 // The expression must be the constant 0 or 1.
2650 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2651 int Value = MCE->getValue();
2653 Flags &= ~DWARF2_FLAG_IS_STMT;
2654 else if (Value == 1)
2655 Flags |= DWARF2_FLAG_IS_STMT;
2657 return Error(Loc, "is_stmt value not 0 or 1");
2660 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2663 else if (Name == "isa") {
2664 SMLoc Loc = getTok().getLoc();
2665 const MCExpr *Value;
2666 if (getParser().ParseExpression(Value))
2668 // The expression must be a constant greater or equal to 0.
2669 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2670 int Value = MCE->getValue();
2672 return Error(Loc, "isa number less than zero");
2676 return Error(Loc, "isa number not a constant value");
2679 else if (Name == "discriminator") {
2680 if (getParser().ParseAbsoluteExpression(Discriminator))
2684 return Error(Loc, "unknown sub-directive in '.loc' directive");
2687 if (getLexer().is(AsmToken::EndOfStatement))
2692 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2693 Isa, Discriminator, StringRef());
2698 /// ParseDirectiveStabs
2699 /// ::= .stabs string, number, number, number
2700 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2701 SMLoc DirectiveLoc) {
2702 return TokError("unsupported directive '" + Directive + "'");
2705 /// ParseDirectiveCFISections
2706 /// ::= .cfi_sections section [, section]
2707 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2708 SMLoc DirectiveLoc) {
2713 if (getParser().ParseIdentifier(Name))
2714 return TokError("Expected an identifier");
2716 if (Name == ".eh_frame")
2718 else if (Name == ".debug_frame")
2721 if (getLexer().is(AsmToken::Comma)) {
2724 if (getParser().ParseIdentifier(Name))
2725 return TokError("Expected an identifier");
2727 if (Name == ".eh_frame")
2729 else if (Name == ".debug_frame")
2733 getStreamer().EmitCFISections(EH, Debug);
2738 /// ParseDirectiveCFIStartProc
2739 /// ::= .cfi_startproc
2740 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2741 SMLoc DirectiveLoc) {
2742 getStreamer().EmitCFIStartProc();
2746 /// ParseDirectiveCFIEndProc
2747 /// ::= .cfi_endproc
2748 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2749 getStreamer().EmitCFIEndProc();
2753 /// ParseRegisterOrRegisterNumber - parse register name or number.
2754 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2755 SMLoc DirectiveLoc) {
2758 if (getLexer().isNot(AsmToken::Integer)) {
2759 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2762 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2764 return getParser().ParseAbsoluteExpression(Register);
2769 /// ParseDirectiveCFIDefCfa
2770 /// ::= .cfi_def_cfa register, offset
2771 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2772 SMLoc DirectiveLoc) {
2773 int64_t Register = 0;
2774 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2777 if (getLexer().isNot(AsmToken::Comma))
2778 return TokError("unexpected token in directive");
2782 if (getParser().ParseAbsoluteExpression(Offset))
2785 getStreamer().EmitCFIDefCfa(Register, Offset);
2789 /// ParseDirectiveCFIDefCfaOffset
2790 /// ::= .cfi_def_cfa_offset offset
2791 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2792 SMLoc DirectiveLoc) {
2794 if (getParser().ParseAbsoluteExpression(Offset))
2797 getStreamer().EmitCFIDefCfaOffset(Offset);
2801 /// ParseDirectiveCFIAdjustCfaOffset
2802 /// ::= .cfi_adjust_cfa_offset adjustment
2803 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2804 SMLoc DirectiveLoc) {
2805 int64_t Adjustment = 0;
2806 if (getParser().ParseAbsoluteExpression(Adjustment))
2809 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2813 /// ParseDirectiveCFIDefCfaRegister
2814 /// ::= .cfi_def_cfa_register register
2815 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2816 SMLoc DirectiveLoc) {
2817 int64_t Register = 0;
2818 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2821 getStreamer().EmitCFIDefCfaRegister(Register);
2825 /// ParseDirectiveCFIOffset
2826 /// ::= .cfi_offset register, offset
2827 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2828 int64_t Register = 0;
2831 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2834 if (getLexer().isNot(AsmToken::Comma))
2835 return TokError("unexpected token in directive");
2838 if (getParser().ParseAbsoluteExpression(Offset))
2841 getStreamer().EmitCFIOffset(Register, Offset);
2845 /// ParseDirectiveCFIRelOffset
2846 /// ::= .cfi_rel_offset register, offset
2847 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2848 SMLoc DirectiveLoc) {
2849 int64_t Register = 0;
2851 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2854 if (getLexer().isNot(AsmToken::Comma))
2855 return TokError("unexpected token in directive");
2859 if (getParser().ParseAbsoluteExpression(Offset))
2862 getStreamer().EmitCFIRelOffset(Register, Offset);
2866 static bool isValidEncoding(int64_t Encoding) {
2867 if (Encoding & ~0xff)
2870 if (Encoding == dwarf::DW_EH_PE_omit)
2873 const unsigned Format = Encoding & 0xf;
2874 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2875 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2876 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2877 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2880 const unsigned Application = Encoding & 0x70;
2881 if (Application != dwarf::DW_EH_PE_absptr &&
2882 Application != dwarf::DW_EH_PE_pcrel)
2888 /// ParseDirectiveCFIPersonalityOrLsda
2889 /// ::= .cfi_personality encoding, [symbol_name]
2890 /// ::= .cfi_lsda encoding, [symbol_name]
2891 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2892 SMLoc DirectiveLoc) {
2893 int64_t Encoding = 0;
2894 if (getParser().ParseAbsoluteExpression(Encoding))
2896 if (Encoding == dwarf::DW_EH_PE_omit)
2899 if (!isValidEncoding(Encoding))
2900 return TokError("unsupported encoding.");
2902 if (getLexer().isNot(AsmToken::Comma))
2903 return TokError("unexpected token in directive");
2907 if (getParser().ParseIdentifier(Name))
2908 return TokError("expected identifier in directive");
2910 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2912 if (IDVal == ".cfi_personality")
2913 getStreamer().EmitCFIPersonality(Sym, Encoding);
2915 assert(IDVal == ".cfi_lsda");
2916 getStreamer().EmitCFILsda(Sym, Encoding);
2921 /// ParseDirectiveCFIRememberState
2922 /// ::= .cfi_remember_state
2923 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2924 SMLoc DirectiveLoc) {
2925 getStreamer().EmitCFIRememberState();
2929 /// ParseDirectiveCFIRestoreState
2930 /// ::= .cfi_remember_state
2931 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2932 SMLoc DirectiveLoc) {
2933 getStreamer().EmitCFIRestoreState();
2937 /// ParseDirectiveCFISameValue
2938 /// ::= .cfi_same_value register
2939 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2940 SMLoc DirectiveLoc) {
2941 int64_t Register = 0;
2943 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2946 getStreamer().EmitCFISameValue(Register);
2951 /// ParseDirectiveCFIRestore
2952 /// ::= .cfi_restore register
2953 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2954 SMLoc DirectiveLoc) {
2955 int64_t Register = 0;
2956 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2959 getStreamer().EmitCFIRestore(Register);
2964 /// ParseDirectiveCFIEscape
2965 /// ::= .cfi_escape expression[,...]
2966 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2967 SMLoc DirectiveLoc) {
2970 if (getParser().ParseAbsoluteExpression(CurrValue))
2973 Values.push_back((uint8_t)CurrValue);
2975 while (getLexer().is(AsmToken::Comma)) {
2978 if (getParser().ParseAbsoluteExpression(CurrValue))
2981 Values.push_back((uint8_t)CurrValue);
2984 getStreamer().EmitCFIEscape(Values);
2988 /// ParseDirectiveCFISignalFrame
2989 /// ::= .cfi_signal_frame
2990 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2991 SMLoc DirectiveLoc) {
2992 if (getLexer().isNot(AsmToken::EndOfStatement))
2993 return Error(getLexer().getLoc(),
2994 "unexpected token in '" + Directive + "' directive");
2996 getStreamer().EmitCFISignalFrame();
3001 /// ParseDirectiveMacrosOnOff
3004 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3005 SMLoc DirectiveLoc) {
3006 if (getLexer().isNot(AsmToken::EndOfStatement))
3007 return Error(getLexer().getLoc(),
3008 "unexpected token in '" + Directive + "' directive");
3010 getParser().MacrosEnabled = Directive == ".macros_on";
3015 /// ParseDirectiveMacro
3016 /// ::= .macro name [parameters]
3017 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3018 SMLoc DirectiveLoc) {
3020 if (getParser().ParseIdentifier(Name))
3021 return TokError("expected identifier in directive");
3023 std::vector<StringRef> Parameters;
3024 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3026 StringRef Parameter;
3027 if (getParser().ParseIdentifier(Parameter))
3028 return TokError("expected identifier in directive");
3029 Parameters.push_back(Parameter);
3031 if (getLexer().isNot(AsmToken::Comma))
3037 if (getLexer().isNot(AsmToken::EndOfStatement))
3038 return TokError("unexpected token in '.macro' directive");
3040 // Eat the end of statement.
3043 AsmToken EndToken, StartToken = getTok();
3045 // Lex the macro definition.
3047 // Check whether we have reached the end of the file.
3048 if (getLexer().is(AsmToken::Eof))
3049 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3051 // Otherwise, check whether we have reach the .endmacro.
3052 if (getLexer().is(AsmToken::Identifier) &&
3053 (getTok().getIdentifier() == ".endm" ||
3054 getTok().getIdentifier() == ".endmacro")) {
3055 EndToken = getTok();
3057 if (getLexer().isNot(AsmToken::EndOfStatement))
3058 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3063 // Otherwise, scan til the end of the statement.
3064 getParser().EatToEndOfStatement();
3067 if (getParser().MacroMap.lookup(Name)) {
3068 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3071 const char *BodyStart = StartToken.getLoc().getPointer();
3072 const char *BodyEnd = EndToken.getLoc().getPointer();
3073 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3074 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3078 /// ParseDirectiveEndMacro
3081 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3082 SMLoc DirectiveLoc) {
3083 if (getLexer().isNot(AsmToken::EndOfStatement))
3084 return TokError("unexpected token in '" + Directive + "' directive");
3086 // If we are inside a macro instantiation, terminate the current
3088 if (!getParser().ActiveMacros.empty()) {
3089 getParser().HandleMacroExit();
3093 // Otherwise, this .endmacro is a stray entry in the file; well formed
3094 // .endmacro directives are handled during the macro definition parsing.
3095 return TokError("unexpected '" + Directive + "' in file, "
3096 "no current macro definition");
3099 /// ParseDirectivePurgeMacro
3101 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3102 SMLoc DirectiveLoc) {
3104 if (getParser().ParseIdentifier(Name))
3105 return TokError("expected identifier in '.purgem' directive");
3107 if (getLexer().isNot(AsmToken::EndOfStatement))
3108 return TokError("unexpected token in '.purgem' directive");
3110 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3111 if (I == getParser().MacroMap.end())
3112 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3114 // Undefine the macro.
3115 delete I->getValue();
3116 getParser().MacroMap.erase(I);
3120 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3121 getParser().CheckForValidSection();
3123 const MCExpr *Value;
3125 if (getParser().ParseExpression(Value))
3128 if (getLexer().isNot(AsmToken::EndOfStatement))
3129 return TokError("unexpected token in directive");
3131 if (DirName[1] == 's')
3132 getStreamer().EmitSLEB128Value(Value);
3134 getStreamer().EmitULEB128Value(Value);
3139 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3140 const MCExpr *Value;
3142 if (ParseExpression(Value))
3146 if (!Value->EvaluateAsAbsolute(Count))
3147 return TokError("Cannot evaluate value");
3150 return TokError("Count is negative");
3152 AsmToken EndToken, StartToken = getTok();
3155 // Lex the macro definition.
3157 // Check whether we have reached the end of the file.
3158 if (getLexer().is(AsmToken::Eof))
3159 return Error(DirectiveLoc, "no matching '.endr' in definition");
3161 // Chcek if we have a nested .rept.
3162 if (getLexer().is(AsmToken::Identifier) &&
3163 (getTok().getIdentifier() == ".rept")) {
3165 EatToEndOfStatement();
3169 // Otherwise, check whether we have reach the .endr.
3170 if (getLexer().is(AsmToken::Identifier) &&
3171 (getTok().getIdentifier() == ".endr")) {
3174 EndToken = getTok();
3176 if (getLexer().isNot(AsmToken::EndOfStatement))
3177 return TokError("unexpected token in '.endr' directive");
3182 // Otherwise, scan til the end of the statement.
3183 EatToEndOfStatement();
3186 const char *BodyStart = StartToken.getLoc().getPointer();
3187 const char *BodyEnd = EndToken.getLoc().getPointer();
3188 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3190 SmallString<256> Buf;
3191 raw_svector_ostream OS(Buf);
3192 for (int i = 0; i < Count; i++)
3196 MemoryBuffer *Instantiation =
3197 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3199 CurBuffer = SrcMgr.AddNewSourceBuffer(Instantiation, SMLoc());
3200 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3202 ActiveRept.push_back(getTok().getLoc());
3207 bool AsmParser::ParseDirectiveEndRept(SMLoc DirectiveLoc) {
3208 if (ActiveRept.empty())
3209 return TokError("unexpected '.endr' directive, no current .rept");
3211 // The only .repl that should get here are the ones created by
3212 // ParseDirectiveRept.
3213 assert(getLexer().is(AsmToken::EndOfStatement));
3215 JumpToLoc(ActiveRept.back());
3216 ActiveRept.pop_back();
3220 /// \brief Create an MCAsmParser instance.
3221 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3222 MCContext &C, MCStreamer &Out,
3223 const MCAsmInfo &MAI) {
3224 return new AsmParser(SM, C, Out, MAI);