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.
48 typedef std::vector<AsmToken> MacroArgument;
53 std::vector<StringRef> Parameters;
56 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
57 Name(N), Body(B), Parameters(P) {}
60 /// \brief Helper class for storing information about an active macro
62 struct MacroInstantiation {
63 /// The macro being instantiated.
64 const Macro *TheMacro;
66 /// The macro instantiation with substitutions.
67 MemoryBuffer *Instantiation;
69 /// The location of the instantiation.
70 SMLoc InstantiationLoc;
72 /// The location where parsing should resume upon instantiation completion.
76 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
80 /// \brief The concrete assembly parser instance.
81 class AsmParser : public MCAsmParser {
82 friend class GenericAsmParser;
84 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
85 void operator=(const AsmParser &); // DO NOT IMPLEMENT
92 SourceMgr::DiagHandlerTy SavedDiagHandler;
93 void *SavedDiagContext;
94 MCAsmParserExtension *GenericParser;
95 MCAsmParserExtension *PlatformParser;
97 /// This is the current buffer index we're lexing from as managed by the
101 AsmCond TheCondState;
102 std::vector<AsmCond> TheCondStack;
104 /// DirectiveMap - This is a table handlers for directives. Each handler is
105 /// invoked after the directive identifier is read and is responsible for
106 /// parsing and validating the rest of the directive. The handler is passed
107 /// in the directive name and the location of the directive keyword.
108 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
110 /// MacroMap - Map of currently defined macros.
111 StringMap<Macro*> MacroMap;
113 /// ActiveMacros - Stack of active macro instantiations.
114 std::vector<MacroInstantiation*> ActiveMacros;
116 /// Boolean tracking whether macro substitution is enabled.
117 unsigned MacrosEnabled : 1;
119 /// Flag tracking whether any errors have been encountered.
120 unsigned HadError : 1;
122 /// The values from the last parsed cpp hash file line comment if any.
123 StringRef CppHashFilename;
124 int64_t CppHashLineNumber;
127 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
128 unsigned AssemblerDialect;
131 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
132 const MCAsmInfo &MAI);
135 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
137 void AddDirectiveHandler(MCAsmParserExtension *Object,
139 DirectiveHandler Handler) {
140 DirectiveMap[Directive] = std::make_pair(Object, Handler);
144 /// @name MCAsmParser Interface
147 virtual SourceMgr &getSourceManager() { return SrcMgr; }
148 virtual MCAsmLexer &getLexer() { return Lexer; }
149 virtual MCContext &getContext() { return Ctx; }
150 virtual MCStreamer &getStreamer() { return Out; }
151 virtual unsigned getAssemblerDialect() {
152 if (AssemblerDialect == ~0U)
153 return MAI.getAssemblerDialect();
155 return AssemblerDialect;
157 virtual void setAssemblerDialect(unsigned i) {
158 AssemblerDialect = i;
161 virtual bool Warning(SMLoc L, const Twine &Msg,
162 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
163 virtual bool Error(SMLoc L, const Twine &Msg,
164 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
166 const AsmToken &Lex();
168 bool ParseExpression(const MCExpr *&Res);
169 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
170 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
171 virtual bool ParseAbsoluteExpression(int64_t &Res);
176 void CheckForValidSection();
178 bool ParseStatement();
179 void EatToEndOfLine();
180 bool ParseCppHashLineFilenameComment(const SMLoc &L);
182 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
183 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
184 const std::vector<StringRef> &Parameters,
185 const std::vector<MacroArgument> &A,
187 void HandleMacroExit();
189 void PrintMacroInstantiations();
190 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
191 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
192 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
194 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
196 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
197 bool EnterIncludeFile(const std::string &Filename);
198 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
199 /// This returns true on failure.
200 bool ProcessIncbinFile(const std::string &Filename);
202 /// \brief Reset the current lexer position to that given by \arg Loc. The
203 /// current token is not set; clients should ensure Lex() is called
205 void JumpToLoc(SMLoc Loc);
207 void EatToEndOfStatement();
209 bool ParseMacroArgument(MacroArgument &MA);
210 bool ParseMacroArguments(const Macro *M, std::vector<MacroArgument> &A);
212 /// \brief Parse up to the end of statement and a return the contents from the
213 /// current token until the end of the statement; the current token on exit
214 /// will be either the EndOfStatement or EOF.
215 StringRef ParseStringToEndOfStatement();
217 /// \brief Parse until the end of a statement or a comma is encountered,
218 /// return the contents from the current token up to the end or comma.
219 StringRef ParseStringToComma();
221 bool ParseAssignment(StringRef Name, bool allow_redef);
223 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
224 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
225 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
226 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
228 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
229 /// and set \arg Res to the identifier contents.
230 bool ParseIdentifier(StringRef &Res);
232 // Directive Parsing.
234 // ".ascii", ".asciiz", ".string"
235 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
236 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
237 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
238 bool ParseDirectiveFill(); // ".fill"
239 bool ParseDirectiveSpace(); // ".space"
240 bool ParseDirectiveZero(); // ".zero"
241 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
242 bool ParseDirectiveOrg(); // ".org"
243 // ".align{,32}", ".p2align{,w,l}"
244 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
246 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
247 /// accepts a single symbol (which should be a label or an external).
248 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
250 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
252 bool ParseDirectiveAbort(); // ".abort"
253 bool ParseDirectiveInclude(); // ".include"
254 bool ParseDirectiveIncbin(); // ".incbin"
256 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
257 // ".ifb" or ".ifnb", depending on ExpectBlank.
258 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
259 // ".ifc" or ".ifnc", depending on ExpectEqual.
260 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
261 // ".ifdef" or ".ifndef", depending on expect_defined
262 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
263 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
264 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
265 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
267 /// ParseEscapedString - Parse the current token as a string which may include
268 /// escaped characters and return the string contents.
269 bool ParseEscapedString(std::string &Data);
271 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
272 MCSymbolRefExpr::VariantKind Variant);
274 // Macro-like directives
275 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
276 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
277 raw_svector_ostream &OS);
278 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
279 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
280 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
281 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
284 /// \brief Generic implementations of directive handling, etc. which is shared
285 /// (or the default, at least) for all assembler parser.
286 class GenericAsmParser : public MCAsmParserExtension {
287 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
288 void AddDirectiveHandler(StringRef Directive) {
289 getParser().AddDirectiveHandler(this, Directive,
290 HandleDirective<GenericAsmParser, Handler>);
293 GenericAsmParser() {}
295 AsmParser &getParser() {
296 return (AsmParser&) this->MCAsmParserExtension::getParser();
299 virtual void Initialize(MCAsmParser &Parser) {
300 // Call the base implementation.
301 this->MCAsmParserExtension::Initialize(Parser);
303 // Debugging directives.
304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
305 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
307 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
310 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
312 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
314 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
316 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
318 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
319 ".cfi_def_cfa_offset");
320 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
321 ".cfi_adjust_cfa_offset");
322 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
323 ".cfi_def_cfa_register");
324 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
326 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
329 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
331 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
333 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
335 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
337 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
339 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
341 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
343 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
346 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
348 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
350 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
351 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
352 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
353 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
355 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
356 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
359 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
361 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
362 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
363 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
364 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
365 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
366 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
367 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
368 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
369 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
370 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
371 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
372 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
373 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
374 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
375 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
376 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
377 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
378 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
379 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
380 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
382 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
383 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
384 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
385 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
387 bool ParseDirectiveLEB128(StringRef, SMLoc);
394 extern MCAsmParserExtension *createDarwinAsmParser();
395 extern MCAsmParserExtension *createELFAsmParser();
396 extern MCAsmParserExtension *createCOFFAsmParser();
400 enum { DEFAULT_ADDRSPACE = 0 };
402 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
403 MCStreamer &_Out, const MCAsmInfo &_MAI)
404 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
405 GenericParser(new GenericAsmParser), PlatformParser(0),
406 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
407 AssemblerDialect(~0U) {
408 // Save the old handler.
409 SavedDiagHandler = SrcMgr.getDiagHandler();
410 SavedDiagContext = SrcMgr.getDiagContext();
411 // Set our own handler which calls the saved handler.
412 SrcMgr.setDiagHandler(DiagHandler, this);
413 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
415 // Initialize the generic parser.
416 GenericParser->Initialize(*this);
418 // Initialize the platform / file format parser.
420 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
422 if (_MAI.hasMicrosoftFastStdCallMangling()) {
423 PlatformParser = createCOFFAsmParser();
424 PlatformParser->Initialize(*this);
425 } else if (_MAI.hasSubsectionsViaSymbols()) {
426 PlatformParser = createDarwinAsmParser();
427 PlatformParser->Initialize(*this);
429 PlatformParser = createELFAsmParser();
430 PlatformParser->Initialize(*this);
434 AsmParser::~AsmParser() {
435 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
437 // Destroy any macros.
438 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
439 ie = MacroMap.end(); it != ie; ++it)
440 delete it->getValue();
442 delete PlatformParser;
443 delete GenericParser;
446 void AsmParser::PrintMacroInstantiations() {
447 // Print the active macro instantiation stack.
448 for (std::vector<MacroInstantiation*>::const_reverse_iterator
449 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
450 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
451 "while in macro instantiation");
454 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
455 if (FatalAssemblerWarnings)
456 return Error(L, Msg, Ranges);
457 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
458 PrintMacroInstantiations();
462 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
464 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
465 PrintMacroInstantiations();
469 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
470 std::string IncludedFile;
471 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
477 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
482 /// Process the specified .incbin file by seaching for it in the include paths
483 /// then just emitting the byte contents of the file to the streamer. This
484 /// returns true on failure.
485 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
486 std::string IncludedFile;
487 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
491 // Pick up the bytes from the file and emit them.
492 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
497 void AsmParser::JumpToLoc(SMLoc Loc) {
498 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
499 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
502 const AsmToken &AsmParser::Lex() {
503 const AsmToken *tok = &Lexer.Lex();
505 if (tok->is(AsmToken::Eof)) {
506 // If this is the end of an included file, pop the parent file off the
508 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
509 if (ParentIncludeLoc != SMLoc()) {
510 JumpToLoc(ParentIncludeLoc);
515 if (tok->is(AsmToken::Error))
516 Error(Lexer.getErrLoc(), Lexer.getErr());
521 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
522 // Create the initial section, if requested.
523 if (!NoInitialTextSection)
530 AsmCond StartingCondState = TheCondState;
532 // If we are generating dwarf for assembly source files save the initial text
533 // section and generate a .file directive.
534 if (getContext().getGenDwarfForAssembly()) {
535 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
536 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
537 getStreamer().EmitLabel(SectionStartSym);
538 getContext().setGenDwarfSectionStartSym(SectionStartSym);
539 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
540 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
543 // While we have input, parse each statement.
544 while (Lexer.isNot(AsmToken::Eof)) {
545 if (!ParseStatement()) continue;
547 // We had an error, validate that one was emitted and recover by skipping to
549 assert(HadError && "Parse statement returned an error, but none emitted!");
550 EatToEndOfStatement();
553 if (TheCondState.TheCond != StartingCondState.TheCond ||
554 TheCondState.Ignore != StartingCondState.Ignore)
555 return TokError("unmatched .ifs or .elses");
557 // Check to see there are no empty DwarfFile slots.
558 const std::vector<MCDwarfFile *> &MCDwarfFiles =
559 getContext().getMCDwarfFiles();
560 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
561 if (!MCDwarfFiles[i])
562 TokError("unassigned file number: " + Twine(i) + " for .file directives");
565 // Check to see that all assembler local symbols were actually defined.
566 // Targets that don't do subsections via symbols may not want this, though,
567 // so conservatively exclude them. Only do this if we're finalizing, though,
568 // as otherwise we won't necessarilly have seen everything yet.
569 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
570 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
571 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
574 MCSymbol *Sym = i->getValue();
575 // Variable symbols may not be marked as defined, so check those
576 // explicitly. If we know it's a variable, we have a definition for
577 // the purposes of this check.
578 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
579 // FIXME: We would really like to refer back to where the symbol was
580 // first referenced for a source location. We need to add something
581 // to track that. Currently, we just point to the end of the file.
582 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
583 "assembler local symbol '" + Sym->getName() +
589 // Finalize the output stream if there are no errors and if the client wants
591 if (!HadError && !NoFinalize)
597 void AsmParser::CheckForValidSection() {
598 if (!getStreamer().getCurrentSection()) {
599 TokError("expected section directive before assembly directive");
600 Out.SwitchSection(Ctx.getMachOSection(
602 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
603 0, SectionKind::getText()));
607 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
608 void AsmParser::EatToEndOfStatement() {
609 while (Lexer.isNot(AsmToken::EndOfStatement) &&
610 Lexer.isNot(AsmToken::Eof))
614 if (Lexer.is(AsmToken::EndOfStatement))
618 StringRef AsmParser::ParseStringToEndOfStatement() {
619 const char *Start = getTok().getLoc().getPointer();
621 while (Lexer.isNot(AsmToken::EndOfStatement) &&
622 Lexer.isNot(AsmToken::Eof))
625 const char *End = getTok().getLoc().getPointer();
626 return StringRef(Start, End - Start);
629 StringRef AsmParser::ParseStringToComma() {
630 const char *Start = getTok().getLoc().getPointer();
632 while (Lexer.isNot(AsmToken::EndOfStatement) &&
633 Lexer.isNot(AsmToken::Comma) &&
634 Lexer.isNot(AsmToken::Eof))
637 const char *End = getTok().getLoc().getPointer();
638 return StringRef(Start, End - Start);
641 /// ParseParenExpr - Parse a paren expression and return it.
642 /// NOTE: This assumes the leading '(' has already been consumed.
644 /// parenexpr ::= expr)
646 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
647 if (ParseExpression(Res)) return true;
648 if (Lexer.isNot(AsmToken::RParen))
649 return TokError("expected ')' in parentheses expression");
650 EndLoc = Lexer.getLoc();
655 /// ParseBracketExpr - Parse a bracket expression and return it.
656 /// NOTE: This assumes the leading '[' has already been consumed.
658 /// bracketexpr ::= expr]
660 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
661 if (ParseExpression(Res)) return true;
662 if (Lexer.isNot(AsmToken::RBrac))
663 return TokError("expected ']' in brackets expression");
664 EndLoc = Lexer.getLoc();
669 /// ParsePrimaryExpr - Parse a primary expression and return it.
670 /// primaryexpr ::= (parenexpr
671 /// primaryexpr ::= symbol
672 /// primaryexpr ::= number
673 /// primaryexpr ::= '.'
674 /// primaryexpr ::= ~,+,- primaryexpr
675 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
676 switch (Lexer.getKind()) {
678 return TokError("unknown token in expression");
679 // If we have an error assume that we've already handled it.
680 case AsmToken::Error:
682 case AsmToken::Exclaim:
683 Lex(); // Eat the operator.
684 if (ParsePrimaryExpr(Res, EndLoc))
686 Res = MCUnaryExpr::CreateLNot(Res, getContext());
688 case AsmToken::Dollar:
689 case AsmToken::String:
690 case AsmToken::Identifier: {
691 EndLoc = Lexer.getLoc();
693 StringRef Identifier;
694 if (ParseIdentifier(Identifier))
697 // This is a symbol reference.
698 std::pair<StringRef, StringRef> Split = Identifier.split('@');
699 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
701 // Lookup the symbol variant if used.
702 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
703 if (Split.first.size() != Identifier.size()) {
704 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
705 if (Variant == MCSymbolRefExpr::VK_Invalid) {
706 Variant = MCSymbolRefExpr::VK_None;
707 return TokError("invalid variant '" + Split.second + "'");
711 // If this is an absolute variable reference, substitute it now to preserve
712 // semantics in the face of reassignment.
713 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
715 return Error(EndLoc, "unexpected modifier on variable reference");
717 Res = Sym->getVariableValue();
721 // Otherwise create a symbol ref.
722 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
725 case AsmToken::Integer: {
726 SMLoc Loc = getTok().getLoc();
727 int64_t IntVal = getTok().getIntVal();
728 Res = MCConstantExpr::Create(IntVal, getContext());
729 EndLoc = Lexer.getLoc();
731 // Look for 'b' or 'f' following an Integer as a directional label
732 if (Lexer.getKind() == AsmToken::Identifier) {
733 StringRef IDVal = getTok().getString();
734 if (IDVal == "f" || IDVal == "b"){
735 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
736 IDVal == "f" ? 1 : 0);
737 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
739 if (IDVal == "b" && Sym->isUndefined())
740 return Error(Loc, "invalid reference to undefined symbol");
741 EndLoc = Lexer.getLoc();
742 Lex(); // Eat identifier.
747 case AsmToken::Real: {
748 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
749 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
750 Res = MCConstantExpr::Create(IntVal, getContext());
754 case AsmToken::Dot: {
755 // This is a '.' reference, which references the current PC. Emit a
756 // temporary label to the streamer and refer to it.
757 MCSymbol *Sym = Ctx.CreateTempSymbol();
759 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
760 EndLoc = Lexer.getLoc();
761 Lex(); // Eat identifier.
764 case AsmToken::LParen:
765 Lex(); // Eat the '('.
766 return ParseParenExpr(Res, EndLoc);
767 case AsmToken::LBrac:
768 if (!PlatformParser->HasBracketExpressions())
769 return TokError("brackets expression not supported on this target");
770 Lex(); // Eat the '['.
771 return ParseBracketExpr(Res, EndLoc);
772 case AsmToken::Minus:
773 Lex(); // Eat the operator.
774 if (ParsePrimaryExpr(Res, EndLoc))
776 Res = MCUnaryExpr::CreateMinus(Res, getContext());
779 Lex(); // Eat the operator.
780 if (ParsePrimaryExpr(Res, EndLoc))
782 Res = MCUnaryExpr::CreatePlus(Res, getContext());
784 case AsmToken::Tilde:
785 Lex(); // Eat the operator.
786 if (ParsePrimaryExpr(Res, EndLoc))
788 Res = MCUnaryExpr::CreateNot(Res, getContext());
793 bool AsmParser::ParseExpression(const MCExpr *&Res) {
795 return ParseExpression(Res, EndLoc);
799 AsmParser::ApplyModifierToExpr(const MCExpr *E,
800 MCSymbolRefExpr::VariantKind Variant) {
801 // Recurse over the given expression, rebuilding it to apply the given variant
802 // if there is exactly one symbol.
803 switch (E->getKind()) {
805 case MCExpr::Constant:
808 case MCExpr::SymbolRef: {
809 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
811 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
812 TokError("invalid variant on expression '" +
813 getTok().getIdentifier() + "' (already modified)");
817 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
820 case MCExpr::Unary: {
821 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
822 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
825 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
828 case MCExpr::Binary: {
829 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
830 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
831 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
836 if (!LHS) LHS = BE->getLHS();
837 if (!RHS) RHS = BE->getRHS();
839 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
843 llvm_unreachable("Invalid expression kind!");
846 /// ParseExpression - Parse an expression and return it.
848 /// expr ::= expr &&,|| expr -> lowest.
849 /// expr ::= expr |,^,&,! expr
850 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
851 /// expr ::= expr <<,>> expr
852 /// expr ::= expr +,- expr
853 /// expr ::= expr *,/,% expr -> highest.
854 /// expr ::= primaryexpr
856 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
857 // Parse the expression.
859 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
862 // As a special case, we support 'a op b @ modifier' by rewriting the
863 // expression to include the modifier. This is inefficient, but in general we
864 // expect users to use 'a@modifier op b'.
865 if (Lexer.getKind() == AsmToken::At) {
868 if (Lexer.isNot(AsmToken::Identifier))
869 return TokError("unexpected symbol modifier following '@'");
871 MCSymbolRefExpr::VariantKind Variant =
872 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
873 if (Variant == MCSymbolRefExpr::VK_Invalid)
874 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
876 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
878 return TokError("invalid modifier '" + getTok().getIdentifier() +
879 "' (no symbols present)");
886 // Try to constant fold it up front, if possible.
888 if (Res->EvaluateAsAbsolute(Value))
889 Res = MCConstantExpr::Create(Value, getContext());
894 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
896 return ParseParenExpr(Res, EndLoc) ||
897 ParseBinOpRHS(1, Res, EndLoc);
900 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
903 SMLoc StartLoc = Lexer.getLoc();
904 if (ParseExpression(Expr))
907 if (!Expr->EvaluateAsAbsolute(Res))
908 return Error(StartLoc, "expected absolute expression");
913 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
914 MCBinaryExpr::Opcode &Kind) {
917 return 0; // not a binop.
919 // Lowest Precedence: &&, ||
920 case AsmToken::AmpAmp:
921 Kind = MCBinaryExpr::LAnd;
923 case AsmToken::PipePipe:
924 Kind = MCBinaryExpr::LOr;
928 // Low Precedence: |, &, ^
930 // FIXME: gas seems to support '!' as an infix operator?
932 Kind = MCBinaryExpr::Or;
934 case AsmToken::Caret:
935 Kind = MCBinaryExpr::Xor;
938 Kind = MCBinaryExpr::And;
941 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
942 case AsmToken::EqualEqual:
943 Kind = MCBinaryExpr::EQ;
945 case AsmToken::ExclaimEqual:
946 case AsmToken::LessGreater:
947 Kind = MCBinaryExpr::NE;
950 Kind = MCBinaryExpr::LT;
952 case AsmToken::LessEqual:
953 Kind = MCBinaryExpr::LTE;
955 case AsmToken::Greater:
956 Kind = MCBinaryExpr::GT;
958 case AsmToken::GreaterEqual:
959 Kind = MCBinaryExpr::GTE;
962 // Intermediate Precedence: <<, >>
963 case AsmToken::LessLess:
964 Kind = MCBinaryExpr::Shl;
966 case AsmToken::GreaterGreater:
967 Kind = MCBinaryExpr::Shr;
970 // High Intermediate Precedence: +, -
972 Kind = MCBinaryExpr::Add;
974 case AsmToken::Minus:
975 Kind = MCBinaryExpr::Sub;
978 // Highest Precedence: *, /, %
980 Kind = MCBinaryExpr::Mul;
982 case AsmToken::Slash:
983 Kind = MCBinaryExpr::Div;
985 case AsmToken::Percent:
986 Kind = MCBinaryExpr::Mod;
992 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
993 /// Res contains the LHS of the expression on input.
994 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
997 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
998 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1000 // If the next token is lower precedence than we are allowed to eat, return
1001 // successfully with what we ate already.
1002 if (TokPrec < Precedence)
1007 // Eat the next primary expression.
1009 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1011 // If BinOp binds less tightly with RHS than the operator after RHS, let
1012 // the pending operator take RHS as its LHS.
1013 MCBinaryExpr::Opcode Dummy;
1014 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1015 if (TokPrec < NextTokPrec) {
1016 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1019 // Merge LHS and RHS according to operator.
1020 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1028 /// ::= EndOfStatement
1029 /// ::= Label* Directive ...Operands... EndOfStatement
1030 /// ::= Label* Identifier OperandList* EndOfStatement
1031 bool AsmParser::ParseStatement() {
1032 if (Lexer.is(AsmToken::EndOfStatement)) {
1038 // Statements always start with an identifier or are a full line comment.
1039 AsmToken ID = getTok();
1040 SMLoc IDLoc = ID.getLoc();
1042 int64_t LocalLabelVal = -1;
1043 // A full line comment is a '#' as the first token.
1044 if (Lexer.is(AsmToken::Hash))
1045 return ParseCppHashLineFilenameComment(IDLoc);
1047 // Allow an integer followed by a ':' as a directional local label.
1048 if (Lexer.is(AsmToken::Integer)) {
1049 LocalLabelVal = getTok().getIntVal();
1050 if (LocalLabelVal < 0) {
1051 if (!TheCondState.Ignore)
1052 return TokError("unexpected token at start of statement");
1056 IDVal = getTok().getString();
1057 Lex(); // Consume the integer token to be used as an identifier token.
1058 if (Lexer.getKind() != AsmToken::Colon) {
1059 if (!TheCondState.Ignore)
1060 return TokError("unexpected token at start of statement");
1064 } else if (Lexer.is(AsmToken::Dot)) {
1065 // Treat '.' as a valid identifier in this context.
1069 } else if (ParseIdentifier(IDVal)) {
1070 if (!TheCondState.Ignore)
1071 return TokError("unexpected token at start of statement");
1076 // Handle conditional assembly here before checking for skipping. We
1077 // have to do this so that .endif isn't skipped in a ".if 0" block for
1080 return ParseDirectiveIf(IDLoc);
1081 if (IDVal == ".ifb")
1082 return ParseDirectiveIfb(IDLoc, true);
1083 if (IDVal == ".ifnb")
1084 return ParseDirectiveIfb(IDLoc, false);
1085 if (IDVal == ".ifc")
1086 return ParseDirectiveIfc(IDLoc, true);
1087 if (IDVal == ".ifnc")
1088 return ParseDirectiveIfc(IDLoc, false);
1089 if (IDVal == ".ifdef")
1090 return ParseDirectiveIfdef(IDLoc, true);
1091 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1092 return ParseDirectiveIfdef(IDLoc, false);
1093 if (IDVal == ".elseif")
1094 return ParseDirectiveElseIf(IDLoc);
1095 if (IDVal == ".else")
1096 return ParseDirectiveElse(IDLoc);
1097 if (IDVal == ".endif")
1098 return ParseDirectiveEndIf(IDLoc);
1100 // If we are in a ".if 0" block, ignore this statement.
1101 if (TheCondState.Ignore) {
1102 EatToEndOfStatement();
1106 // FIXME: Recurse on local labels?
1108 // See what kind of statement we have.
1109 switch (Lexer.getKind()) {
1110 case AsmToken::Colon: {
1111 CheckForValidSection();
1113 // identifier ':' -> Label.
1116 // Diagnose attempt to use '.' as a label.
1118 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1120 // Diagnose attempt to use a variable as a label.
1122 // FIXME: Diagnostics. Note the location of the definition as a label.
1123 // FIXME: This doesn't diagnose assignment to a symbol which has been
1124 // implicitly marked as external.
1126 if (LocalLabelVal == -1)
1127 Sym = getContext().GetOrCreateSymbol(IDVal);
1129 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1130 if (!Sym->isUndefined() || Sym->isVariable())
1131 return Error(IDLoc, "invalid symbol redefinition");
1136 // If we are generating dwarf for assembly source files then gather the
1137 // info to make a dwarf label entry for this label if needed.
1138 if (getContext().getGenDwarfForAssembly())
1139 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1142 // Consume any end of statement token, if present, to avoid spurious
1143 // AddBlankLine calls().
1144 if (Lexer.is(AsmToken::EndOfStatement)) {
1146 if (Lexer.is(AsmToken::Eof))
1150 return ParseStatement();
1153 case AsmToken::Equal:
1154 // identifier '=' ... -> assignment statement
1157 return ParseAssignment(IDVal, true);
1159 default: // Normal instruction or directive.
1163 // If macros are enabled, check to see if this is a macro instantiation.
1165 if (const Macro *M = MacroMap.lookup(IDVal))
1166 return HandleMacroEntry(IDVal, IDLoc, M);
1168 // Otherwise, we have a normal instruction or directive.
1169 if (IDVal[0] == '.' && IDVal != ".") {
1170 // Assembler features
1171 if (IDVal == ".set" || IDVal == ".equ")
1172 return ParseDirectiveSet(IDVal, true);
1173 if (IDVal == ".equiv")
1174 return ParseDirectiveSet(IDVal, false);
1178 if (IDVal == ".ascii")
1179 return ParseDirectiveAscii(IDVal, false);
1180 if (IDVal == ".asciz" || IDVal == ".string")
1181 return ParseDirectiveAscii(IDVal, true);
1183 if (IDVal == ".byte")
1184 return ParseDirectiveValue(1);
1185 if (IDVal == ".short")
1186 return ParseDirectiveValue(2);
1187 if (IDVal == ".value")
1188 return ParseDirectiveValue(2);
1189 if (IDVal == ".2byte")
1190 return ParseDirectiveValue(2);
1191 if (IDVal == ".long")
1192 return ParseDirectiveValue(4);
1193 if (IDVal == ".int")
1194 return ParseDirectiveValue(4);
1195 if (IDVal == ".4byte")
1196 return ParseDirectiveValue(4);
1197 if (IDVal == ".quad")
1198 return ParseDirectiveValue(8);
1199 if (IDVal == ".8byte")
1200 return ParseDirectiveValue(8);
1201 if (IDVal == ".single" || IDVal == ".float")
1202 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1203 if (IDVal == ".double")
1204 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1206 if (IDVal == ".align") {
1207 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1208 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1210 if (IDVal == ".align32") {
1211 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1212 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1214 if (IDVal == ".balign")
1215 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1216 if (IDVal == ".balignw")
1217 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1218 if (IDVal == ".balignl")
1219 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1220 if (IDVal == ".p2align")
1221 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1222 if (IDVal == ".p2alignw")
1223 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1224 if (IDVal == ".p2alignl")
1225 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1227 if (IDVal == ".org")
1228 return ParseDirectiveOrg();
1230 if (IDVal == ".fill")
1231 return ParseDirectiveFill();
1232 if (IDVal == ".space" || IDVal == ".skip")
1233 return ParseDirectiveSpace();
1234 if (IDVal == ".zero")
1235 return ParseDirectiveZero();
1237 // Symbol attribute directives
1239 if (IDVal == ".extern") {
1240 EatToEndOfStatement(); // .extern is the default, ignore it.
1243 if (IDVal == ".globl" || IDVal == ".global")
1244 return ParseDirectiveSymbolAttribute(MCSA_Global);
1245 if (IDVal == ".indirect_symbol")
1246 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1247 if (IDVal == ".lazy_reference")
1248 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1249 if (IDVal == ".no_dead_strip")
1250 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1251 if (IDVal == ".symbol_resolver")
1252 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1253 if (IDVal == ".private_extern")
1254 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1255 if (IDVal == ".reference")
1256 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1257 if (IDVal == ".weak_definition")
1258 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1259 if (IDVal == ".weak_reference")
1260 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1261 if (IDVal == ".weak_def_can_be_hidden")
1262 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1264 if (IDVal == ".comm" || IDVal == ".common")
1265 return ParseDirectiveComm(/*IsLocal=*/false);
1266 if (IDVal == ".lcomm")
1267 return ParseDirectiveComm(/*IsLocal=*/true);
1269 if (IDVal == ".abort")
1270 return ParseDirectiveAbort();
1271 if (IDVal == ".include")
1272 return ParseDirectiveInclude();
1273 if (IDVal == ".incbin")
1274 return ParseDirectiveIncbin();
1276 if (IDVal == ".code16" || IDVal == ".code16gcc")
1277 return TokError(Twine(IDVal) + " not supported yet");
1279 // Macro-like directives
1280 if (IDVal == ".rept")
1281 return ParseDirectiveRept(IDLoc);
1282 if (IDVal == ".irp")
1283 return ParseDirectiveIrp(IDLoc);
1284 if (IDVal == ".irpc")
1285 return ParseDirectiveIrpc(IDLoc);
1286 if (IDVal == ".endr")
1287 return ParseDirectiveEndr(IDLoc);
1289 // Look up the handler in the handler table.
1290 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1291 DirectiveMap.lookup(IDVal);
1293 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1295 // Target hook for parsing target specific directives.
1296 if (!getTargetParser().ParseDirective(ID))
1299 return Error(IDLoc, "unknown directive");
1302 CheckForValidSection();
1304 // Canonicalize the opcode to lower case.
1305 SmallString<128> Opcode;
1306 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1307 Opcode.push_back(tolower(IDVal[i]));
1309 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1310 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1313 // Dump the parsed representation, if requested.
1314 if (getShowParsedOperands()) {
1315 SmallString<256> Str;
1316 raw_svector_ostream OS(Str);
1317 OS << "parsed instruction: [";
1318 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1321 ParsedOperands[i]->print(OS);
1325 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1328 // If we are generating dwarf for assembly source files and the current
1329 // section is the initial text section then generate a .loc directive for
1331 if (!HadError && getContext().getGenDwarfForAssembly() &&
1332 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1333 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1334 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1335 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1336 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1340 // If parsing succeeded, match the instruction.
1342 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1345 // Free any parsed operands.
1346 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1347 delete ParsedOperands[i];
1349 // Don't skip the rest of the line, the instruction parser is responsible for
1354 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1355 /// since they may not be able to be tokenized to get to the end of line token.
1356 void AsmParser::EatToEndOfLine() {
1357 if (!Lexer.is(AsmToken::EndOfStatement))
1358 Lexer.LexUntilEndOfLine();
1363 /// ParseCppHashLineFilenameComment as this:
1364 /// ::= # number "filename"
1365 /// or just as a full line comment if it doesn't have a number and a string.
1366 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1367 Lex(); // Eat the hash token.
1369 if (getLexer().isNot(AsmToken::Integer)) {
1370 // Consume the line since in cases it is not a well-formed line directive,
1371 // as if were simply a full line comment.
1376 int64_t LineNumber = getTok().getIntVal();
1379 if (getLexer().isNot(AsmToken::String)) {
1384 StringRef Filename = getTok().getString();
1385 // Get rid of the enclosing quotes.
1386 Filename = Filename.substr(1, Filename.size()-2);
1388 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1390 CppHashFilename = Filename;
1391 CppHashLineNumber = LineNumber;
1393 // Ignore any trailing characters, they're just comment.
1398 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1399 /// for the Filename and LineNo if any in the diagnostic.
1400 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1401 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1402 raw_ostream &OS = errs();
1404 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1405 const SMLoc &DiagLoc = Diag.getLoc();
1406 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1407 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1409 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1410 // before printing the message.
1411 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1412 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1413 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1414 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1417 // If we have not parsed a cpp hash line filename comment or the source
1418 // manager changed or buffer changed (like in a nested include) then just
1419 // print the normal diagnostic using its Filename and LineNo.
1420 if (!Parser->CppHashLineNumber ||
1421 &DiagSrcMgr != &Parser->SrcMgr ||
1422 DiagBuf != CppHashBuf) {
1423 if (Parser->SavedDiagHandler)
1424 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1430 // Use the CppHashFilename and calculate a line number based on the
1431 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1433 const std::string Filename = Parser->CppHashFilename;
1435 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1436 int CppHashLocLineNo =
1437 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1438 int LineNo = Parser->CppHashLineNumber - 1 +
1439 (DiagLocLineNo - CppHashLocLineNo);
1441 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1442 Filename, LineNo, Diag.getColumnNo(),
1443 Diag.getKind(), Diag.getMessage(),
1444 Diag.getLineContents(), Diag.getRanges());
1446 if (Parser->SavedDiagHandler)
1447 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1449 NewDiag.print(0, OS);
1452 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1453 const std::vector<StringRef> &Parameters,
1454 const std::vector<MacroArgument> &A,
1456 unsigned NParameters = Parameters.size();
1457 if (NParameters != 0 && NParameters != A.size())
1458 return Error(L, "Wrong number of arguments");
1460 while (!Body.empty()) {
1461 // Scan for the next substitution.
1462 std::size_t End = Body.size(), Pos = 0;
1463 for (; Pos != End; ++Pos) {
1464 // Check for a substitution or escape.
1466 // This macro has no parameters, look for $0, $1, etc.
1467 if (Body[Pos] != '$' || Pos + 1 == End)
1470 char Next = Body[Pos + 1];
1471 if (Next == '$' || Next == 'n' || isdigit(Next))
1474 // This macro has parameters, look for \foo, \bar, etc.
1475 if (Body[Pos] == '\\' && Pos + 1 != End)
1481 OS << Body.slice(0, Pos);
1483 // Check if we reached the end.
1488 switch (Body[Pos+1]) {
1494 // $n => number of arguments
1499 // $[0-9] => argument
1501 // Missing arguments are ignored.
1502 unsigned Index = Body[Pos+1] - '0';
1503 if (Index >= A.size())
1506 // Otherwise substitute with the token values, with spaces eliminated.
1507 for (MacroArgument::const_iterator it = A[Index].begin(),
1508 ie = A[Index].end(); it != ie; ++it)
1509 OS << it->getString();
1515 unsigned I = Pos + 1;
1516 while (isalnum(Body[I]) && I + 1 != End)
1519 const char *Begin = Body.data() + Pos +1;
1520 StringRef Argument(Begin, I - (Pos +1));
1522 for (; Index < NParameters; ++Index)
1523 if (Parameters[Index] == Argument)
1526 // FIXME: We should error at the macro definition.
1527 if (Index == NParameters)
1528 return Error(L, "Parameter not found");
1530 for (MacroArgument::const_iterator it = A[Index].begin(),
1531 ie = A[Index].end(); it != ie; ++it)
1532 OS << it->getString();
1534 Pos += 1 + Argument.size();
1536 // Update the scan point.
1537 Body = Body.substr(Pos);
1543 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1545 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1549 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1550 /// This is used for both default macro parameter values and the
1551 /// arguments in macro invocations
1552 bool AsmParser::ParseMacroArgument(MacroArgument &MA) {
1553 unsigned ParenLevel = 0;
1558 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1559 return TokError("unexpected token in macro instantiation");
1561 // HandleMacroEntry relies on not advancing the lexer here
1562 // to be able to fill in the remaining default parameter values
1563 if (Lexer.is(AsmToken::EndOfStatement))
1565 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1568 // Adjust the current parentheses level.
1569 if (Lexer.is(AsmToken::LParen))
1571 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1574 // Append the token to the current argument list.
1575 MA.push_back(getTok());
1578 if (ParenLevel != 0)
1579 return TokError("unbalanced parenthesises in macro argument");
1583 // Parse the macro instantiation arguments.
1584 bool AsmParser::ParseMacroArguments(const Macro *M,
1585 std::vector<MacroArgument> &A) {
1586 const unsigned NParameters = M ? M->Parameters.size() : 0;
1588 // Parse two kinds of macro invocations:
1589 // - macros defined without any parameters accept an arbitrary number of them
1590 // - macros defined with parameters accept at most that many of them
1591 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1595 if (ParseMacroArgument(MA))
1600 if (Lexer.is(AsmToken::EndOfStatement))
1603 if (Lexer.is(AsmToken::Comma))
1606 return TokError("Too many arguments");
1609 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1611 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1612 // this, although we should protect against infinite loops.
1613 if (ActiveMacros.size() == 20)
1614 return TokError("macros cannot be nested more than 20 levels deep");
1616 std::vector<MacroArgument> MacroArguments;
1617 if (ParseMacroArguments(M, MacroArguments))
1620 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1621 // to hold the macro body with substitutions.
1622 SmallString<256> Buf;
1623 StringRef Body = M->Body;
1624 raw_svector_ostream OS(Buf);
1626 if (expandMacro(OS, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1629 // We include the .endmacro in the buffer as our queue to exit the macro
1631 OS << ".endmacro\n";
1633 MemoryBuffer *Instantiation =
1634 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1636 // Create the macro instantiation object and add to the current macro
1637 // instantiation stack.
1638 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1641 ActiveMacros.push_back(MI);
1643 // Jump to the macro instantiation and prime the lexer.
1644 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1645 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1651 void AsmParser::HandleMacroExit() {
1652 // Jump to the EndOfStatement we should return to, and consume it.
1653 JumpToLoc(ActiveMacros.back()->ExitLoc);
1656 // Pop the instantiation entry.
1657 delete ActiveMacros.back();
1658 ActiveMacros.pop_back();
1661 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1662 switch (Value->getKind()) {
1663 case MCExpr::Binary: {
1664 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1665 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1668 case MCExpr::Target:
1669 case MCExpr::Constant:
1671 case MCExpr::SymbolRef: {
1672 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1674 return IsUsedIn(Sym, S.getVariableValue());
1678 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1681 llvm_unreachable("Unknown expr kind!");
1684 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1685 // FIXME: Use better location, we should use proper tokens.
1686 SMLoc EqualLoc = Lexer.getLoc();
1688 const MCExpr *Value;
1689 if (ParseExpression(Value))
1692 // Note: we don't count b as used in "a = b". This is to allow
1696 if (Lexer.isNot(AsmToken::EndOfStatement))
1697 return TokError("unexpected token in assignment");
1699 // Error on assignment to '.'.
1701 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1702 "(use '.space' or '.org').)"));
1705 // Eat the end of statement marker.
1708 // Validate that the LHS is allowed to be a variable (either it has not been
1709 // used as a symbol, or it is an absolute symbol).
1710 MCSymbol *Sym = getContext().LookupSymbol(Name);
1712 // Diagnose assignment to a label.
1714 // FIXME: Diagnostics. Note the location of the definition as a label.
1715 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1716 if (IsUsedIn(Sym, Value))
1717 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1718 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1719 ; // Allow redefinitions of undefined symbols only used in directives.
1720 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1721 ; // Allow redefinitions of variables that haven't yet been used.
1722 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1723 return Error(EqualLoc, "redefinition of '" + Name + "'");
1724 else if (!Sym->isVariable())
1725 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1726 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1727 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1730 // Don't count these checks as uses.
1731 Sym->setUsed(false);
1733 Sym = getContext().GetOrCreateSymbol(Name);
1735 // FIXME: Handle '.'.
1737 // Do the assignment.
1738 Out.EmitAssignment(Sym, Value);
1743 /// ParseIdentifier:
1746 bool AsmParser::ParseIdentifier(StringRef &Res) {
1747 // The assembler has relaxed rules for accepting identifiers, in particular we
1748 // allow things like '.globl $foo', which would normally be separate
1749 // tokens. At this level, we have already lexed so we cannot (currently)
1750 // handle this as a context dependent token, instead we detect adjacent tokens
1751 // and return the combined identifier.
1752 if (Lexer.is(AsmToken::Dollar)) {
1753 SMLoc DollarLoc = getLexer().getLoc();
1755 // Consume the dollar sign, and check for a following identifier.
1757 if (Lexer.isNot(AsmToken::Identifier))
1760 // We have a '$' followed by an identifier, make sure they are adjacent.
1761 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1764 // Construct the joined identifier and consume the token.
1765 Res = StringRef(DollarLoc.getPointer(),
1766 getTok().getIdentifier().size() + 1);
1771 if (Lexer.isNot(AsmToken::Identifier) &&
1772 Lexer.isNot(AsmToken::String))
1775 Res = getTok().getIdentifier();
1777 Lex(); // Consume the identifier token.
1782 /// ParseDirectiveSet:
1783 /// ::= .equ identifier ',' expression
1784 /// ::= .equiv identifier ',' expression
1785 /// ::= .set identifier ',' expression
1786 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1789 if (ParseIdentifier(Name))
1790 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1792 if (getLexer().isNot(AsmToken::Comma))
1793 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1796 return ParseAssignment(Name, allow_redef);
1799 bool AsmParser::ParseEscapedString(std::string &Data) {
1800 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1803 StringRef Str = getTok().getStringContents();
1804 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1805 if (Str[i] != '\\') {
1810 // Recognize escaped characters. Note that this escape semantics currently
1811 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1814 return TokError("unexpected backslash at end of string");
1816 // Recognize octal sequences.
1817 if ((unsigned) (Str[i] - '0') <= 7) {
1818 // Consume up to three octal characters.
1819 unsigned Value = Str[i] - '0';
1821 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1823 Value = Value * 8 + (Str[i] - '0');
1825 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1827 Value = Value * 8 + (Str[i] - '0');
1832 return TokError("invalid octal escape sequence (out of range)");
1834 Data += (unsigned char) Value;
1838 // Otherwise recognize individual escapes.
1841 // Just reject invalid escape sequences for now.
1842 return TokError("invalid escape sequence (unrecognized character)");
1844 case 'b': Data += '\b'; break;
1845 case 'f': Data += '\f'; break;
1846 case 'n': Data += '\n'; break;
1847 case 'r': Data += '\r'; break;
1848 case 't': Data += '\t'; break;
1849 case '"': Data += '"'; break;
1850 case '\\': Data += '\\'; break;
1857 /// ParseDirectiveAscii:
1858 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1859 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1860 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1861 CheckForValidSection();
1864 if (getLexer().isNot(AsmToken::String))
1865 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1868 if (ParseEscapedString(Data))
1871 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1873 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1877 if (getLexer().is(AsmToken::EndOfStatement))
1880 if (getLexer().isNot(AsmToken::Comma))
1881 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1890 /// ParseDirectiveValue
1891 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1892 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1893 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1894 CheckForValidSection();
1897 const MCExpr *Value;
1898 SMLoc ExprLoc = getLexer().getLoc();
1899 if (ParseExpression(Value))
1902 // Special case constant expressions to match code generator.
1903 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1904 assert(Size <= 8 && "Invalid size");
1905 uint64_t IntValue = MCE->getValue();
1906 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1907 return Error(ExprLoc, "literal value out of range for directive");
1908 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1910 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1912 if (getLexer().is(AsmToken::EndOfStatement))
1915 // FIXME: Improve diagnostic.
1916 if (getLexer().isNot(AsmToken::Comma))
1917 return TokError("unexpected token in directive");
1926 /// ParseDirectiveRealValue
1927 /// ::= (.single | .double) [ expression (, expression)* ]
1928 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1929 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1930 CheckForValidSection();
1933 // We don't truly support arithmetic on floating point expressions, so we
1934 // have to manually parse unary prefixes.
1936 if (getLexer().is(AsmToken::Minus)) {
1939 } else if (getLexer().is(AsmToken::Plus))
1942 if (getLexer().isNot(AsmToken::Integer) &&
1943 getLexer().isNot(AsmToken::Real) &&
1944 getLexer().isNot(AsmToken::Identifier))
1945 return TokError("unexpected token in directive");
1947 // Convert to an APFloat.
1948 APFloat Value(Semantics);
1949 StringRef IDVal = getTok().getString();
1950 if (getLexer().is(AsmToken::Identifier)) {
1951 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1952 Value = APFloat::getInf(Semantics);
1953 else if (!IDVal.compare_lower("nan"))
1954 Value = APFloat::getNaN(Semantics, false, ~0);
1956 return TokError("invalid floating point literal");
1957 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1958 APFloat::opInvalidOp)
1959 return TokError("invalid floating point literal");
1963 // Consume the numeric token.
1966 // Emit the value as an integer.
1967 APInt AsInt = Value.bitcastToAPInt();
1968 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1969 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1971 if (getLexer().is(AsmToken::EndOfStatement))
1974 if (getLexer().isNot(AsmToken::Comma))
1975 return TokError("unexpected token in directive");
1984 /// ParseDirectiveSpace
1985 /// ::= .space expression [ , expression ]
1986 bool AsmParser::ParseDirectiveSpace() {
1987 CheckForValidSection();
1990 if (ParseAbsoluteExpression(NumBytes))
1993 int64_t FillExpr = 0;
1994 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1995 if (getLexer().isNot(AsmToken::Comma))
1996 return TokError("unexpected token in '.space' directive");
1999 if (ParseAbsoluteExpression(FillExpr))
2002 if (getLexer().isNot(AsmToken::EndOfStatement))
2003 return TokError("unexpected token in '.space' directive");
2009 return TokError("invalid number of bytes in '.space' directive");
2011 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2012 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2017 /// ParseDirectiveZero
2018 /// ::= .zero expression
2019 bool AsmParser::ParseDirectiveZero() {
2020 CheckForValidSection();
2023 if (ParseAbsoluteExpression(NumBytes))
2027 if (getLexer().is(AsmToken::Comma)) {
2029 if (ParseAbsoluteExpression(Val))
2033 if (getLexer().isNot(AsmToken::EndOfStatement))
2034 return TokError("unexpected token in '.zero' directive");
2038 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2043 /// ParseDirectiveFill
2044 /// ::= .fill expression , expression , expression
2045 bool AsmParser::ParseDirectiveFill() {
2046 CheckForValidSection();
2049 if (ParseAbsoluteExpression(NumValues))
2052 if (getLexer().isNot(AsmToken::Comma))
2053 return TokError("unexpected token in '.fill' directive");
2057 if (ParseAbsoluteExpression(FillSize))
2060 if (getLexer().isNot(AsmToken::Comma))
2061 return TokError("unexpected token in '.fill' directive");
2065 if (ParseAbsoluteExpression(FillExpr))
2068 if (getLexer().isNot(AsmToken::EndOfStatement))
2069 return TokError("unexpected token in '.fill' directive");
2073 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2074 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2076 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2077 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2082 /// ParseDirectiveOrg
2083 /// ::= .org expression [ , expression ]
2084 bool AsmParser::ParseDirectiveOrg() {
2085 CheckForValidSection();
2087 const MCExpr *Offset;
2088 SMLoc Loc = getTok().getLoc();
2089 if (ParseExpression(Offset))
2092 // Parse optional fill expression.
2093 int64_t FillExpr = 0;
2094 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2095 if (getLexer().isNot(AsmToken::Comma))
2096 return TokError("unexpected token in '.org' directive");
2099 if (ParseAbsoluteExpression(FillExpr))
2102 if (getLexer().isNot(AsmToken::EndOfStatement))
2103 return TokError("unexpected token in '.org' directive");
2108 // Only limited forms of relocatable expressions are accepted here, it
2109 // has to be relative to the current section. The streamer will return
2110 // 'true' if the expression wasn't evaluatable.
2111 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2112 return Error(Loc, "expected assembly-time absolute expression");
2117 /// ParseDirectiveAlign
2118 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2119 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2120 CheckForValidSection();
2122 SMLoc AlignmentLoc = getLexer().getLoc();
2124 if (ParseAbsoluteExpression(Alignment))
2128 bool HasFillExpr = false;
2129 int64_t FillExpr = 0;
2130 int64_t MaxBytesToFill = 0;
2131 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2132 if (getLexer().isNot(AsmToken::Comma))
2133 return TokError("unexpected token in directive");
2136 // The fill expression can be omitted while specifying a maximum number of
2137 // alignment bytes, e.g:
2139 if (getLexer().isNot(AsmToken::Comma)) {
2141 if (ParseAbsoluteExpression(FillExpr))
2145 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2146 if (getLexer().isNot(AsmToken::Comma))
2147 return TokError("unexpected token in directive");
2150 MaxBytesLoc = getLexer().getLoc();
2151 if (ParseAbsoluteExpression(MaxBytesToFill))
2154 if (getLexer().isNot(AsmToken::EndOfStatement))
2155 return TokError("unexpected token in directive");
2164 // Compute alignment in bytes.
2166 // FIXME: Diagnose overflow.
2167 if (Alignment >= 32) {
2168 Error(AlignmentLoc, "invalid alignment value");
2172 Alignment = 1ULL << Alignment;
2175 // Diagnose non-sensical max bytes to align.
2176 if (MaxBytesLoc.isValid()) {
2177 if (MaxBytesToFill < 1) {
2178 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2179 "many bytes, ignoring maximum bytes expression");
2183 if (MaxBytesToFill >= Alignment) {
2184 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2190 // Check whether we should use optimal code alignment for this .align
2192 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2193 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2194 ValueSize == 1 && UseCodeAlign) {
2195 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2197 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2198 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2205 /// ParseDirectiveSymbolAttribute
2206 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2207 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2208 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2211 SMLoc Loc = getTok().getLoc();
2213 if (ParseIdentifier(Name))
2214 return Error(Loc, "expected identifier in directive");
2216 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2218 // Assembler local symbols don't make any sense here. Complain loudly.
2219 if (Sym->isTemporary())
2220 return Error(Loc, "non-local symbol required in directive");
2222 getStreamer().EmitSymbolAttribute(Sym, Attr);
2224 if (getLexer().is(AsmToken::EndOfStatement))
2227 if (getLexer().isNot(AsmToken::Comma))
2228 return TokError("unexpected token in directive");
2237 /// ParseDirectiveComm
2238 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2239 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2240 CheckForValidSection();
2242 SMLoc IDLoc = getLexer().getLoc();
2244 if (ParseIdentifier(Name))
2245 return TokError("expected identifier in directive");
2247 // Handle the identifier as the key symbol.
2248 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2250 if (getLexer().isNot(AsmToken::Comma))
2251 return TokError("unexpected token in directive");
2255 SMLoc SizeLoc = getLexer().getLoc();
2256 if (ParseAbsoluteExpression(Size))
2259 int64_t Pow2Alignment = 0;
2260 SMLoc Pow2AlignmentLoc;
2261 if (getLexer().is(AsmToken::Comma)) {
2263 Pow2AlignmentLoc = getLexer().getLoc();
2264 if (ParseAbsoluteExpression(Pow2Alignment))
2267 // If this target takes alignments in bytes (not log) validate and convert.
2268 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2269 if (!isPowerOf2_64(Pow2Alignment))
2270 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2271 Pow2Alignment = Log2_64(Pow2Alignment);
2275 if (getLexer().isNot(AsmToken::EndOfStatement))
2276 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2280 // NOTE: a size of zero for a .comm should create a undefined symbol
2281 // but a size of .lcomm creates a bss symbol of size zero.
2283 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2284 "be less than zero");
2286 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2287 // may internally end up wanting an alignment in bytes.
2288 // FIXME: Diagnose overflow.
2289 if (Pow2Alignment < 0)
2290 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2291 "alignment, can't be less than zero");
2293 if (!Sym->isUndefined())
2294 return Error(IDLoc, "invalid symbol redefinition");
2296 // '.lcomm' is equivalent to '.zerofill'.
2297 // Create the Symbol as a common or local common with Size and Pow2Alignment
2299 getStreamer().EmitZerofill(Ctx.getMachOSection(
2300 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2301 0, SectionKind::getBSS()),
2302 Sym, Size, 1 << Pow2Alignment);
2306 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2310 /// ParseDirectiveAbort
2311 /// ::= .abort [... message ...]
2312 bool AsmParser::ParseDirectiveAbort() {
2313 // FIXME: Use loc from directive.
2314 SMLoc Loc = getLexer().getLoc();
2316 StringRef Str = ParseStringToEndOfStatement();
2317 if (getLexer().isNot(AsmToken::EndOfStatement))
2318 return TokError("unexpected token in '.abort' directive");
2323 Error(Loc, ".abort detected. Assembly stopping.");
2325 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2326 // FIXME: Actually abort assembly here.
2331 /// ParseDirectiveInclude
2332 /// ::= .include "filename"
2333 bool AsmParser::ParseDirectiveInclude() {
2334 if (getLexer().isNot(AsmToken::String))
2335 return TokError("expected string in '.include' directive");
2337 std::string Filename = getTok().getString();
2338 SMLoc IncludeLoc = getLexer().getLoc();
2341 if (getLexer().isNot(AsmToken::EndOfStatement))
2342 return TokError("unexpected token in '.include' directive");
2344 // Strip the quotes.
2345 Filename = Filename.substr(1, Filename.size()-2);
2347 // Attempt to switch the lexer to the included file before consuming the end
2348 // of statement to avoid losing it when we switch.
2349 if (EnterIncludeFile(Filename)) {
2350 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2357 /// ParseDirectiveIncbin
2358 /// ::= .incbin "filename"
2359 bool AsmParser::ParseDirectiveIncbin() {
2360 if (getLexer().isNot(AsmToken::String))
2361 return TokError("expected string in '.incbin' directive");
2363 std::string Filename = getTok().getString();
2364 SMLoc IncbinLoc = getLexer().getLoc();
2367 if (getLexer().isNot(AsmToken::EndOfStatement))
2368 return TokError("unexpected token in '.incbin' directive");
2370 // Strip the quotes.
2371 Filename = Filename.substr(1, Filename.size()-2);
2373 // Attempt to process the included file.
2374 if (ProcessIncbinFile(Filename)) {
2375 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2382 /// ParseDirectiveIf
2383 /// ::= .if expression
2384 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2385 TheCondStack.push_back(TheCondState);
2386 TheCondState.TheCond = AsmCond::IfCond;
2387 if (TheCondState.Ignore) {
2388 EatToEndOfStatement();
2391 if (ParseAbsoluteExpression(ExprValue))
2394 if (getLexer().isNot(AsmToken::EndOfStatement))
2395 return TokError("unexpected token in '.if' directive");
2399 TheCondState.CondMet = ExprValue;
2400 TheCondState.Ignore = !TheCondState.CondMet;
2406 /// ParseDirectiveIfb
2408 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2409 TheCondStack.push_back(TheCondState);
2410 TheCondState.TheCond = AsmCond::IfCond;
2412 if (TheCondState.Ignore) {
2413 EatToEndOfStatement();
2415 StringRef Str = ParseStringToEndOfStatement();
2417 if (getLexer().isNot(AsmToken::EndOfStatement))
2418 return TokError("unexpected token in '.ifb' directive");
2422 TheCondState.CondMet = ExpectBlank == Str.empty();
2423 TheCondState.Ignore = !TheCondState.CondMet;
2429 /// ParseDirectiveIfc
2430 /// ::= .ifc string1, string2
2431 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2432 TheCondStack.push_back(TheCondState);
2433 TheCondState.TheCond = AsmCond::IfCond;
2435 if (TheCondState.Ignore) {
2436 EatToEndOfStatement();
2438 StringRef Str1 = ParseStringToComma();
2440 if (getLexer().isNot(AsmToken::Comma))
2441 return TokError("unexpected token in '.ifc' directive");
2445 StringRef Str2 = ParseStringToEndOfStatement();
2447 if (getLexer().isNot(AsmToken::EndOfStatement))
2448 return TokError("unexpected token in '.ifc' directive");
2452 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2453 TheCondState.Ignore = !TheCondState.CondMet;
2459 /// ParseDirectiveIfdef
2460 /// ::= .ifdef symbol
2461 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2463 TheCondStack.push_back(TheCondState);
2464 TheCondState.TheCond = AsmCond::IfCond;
2466 if (TheCondState.Ignore) {
2467 EatToEndOfStatement();
2469 if (ParseIdentifier(Name))
2470 return TokError("expected identifier after '.ifdef'");
2474 MCSymbol *Sym = getContext().LookupSymbol(Name);
2477 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2479 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2480 TheCondState.Ignore = !TheCondState.CondMet;
2486 /// ParseDirectiveElseIf
2487 /// ::= .elseif expression
2488 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2489 if (TheCondState.TheCond != AsmCond::IfCond &&
2490 TheCondState.TheCond != AsmCond::ElseIfCond)
2491 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2493 TheCondState.TheCond = AsmCond::ElseIfCond;
2495 bool LastIgnoreState = false;
2496 if (!TheCondStack.empty())
2497 LastIgnoreState = TheCondStack.back().Ignore;
2498 if (LastIgnoreState || TheCondState.CondMet) {
2499 TheCondState.Ignore = true;
2500 EatToEndOfStatement();
2504 if (ParseAbsoluteExpression(ExprValue))
2507 if (getLexer().isNot(AsmToken::EndOfStatement))
2508 return TokError("unexpected token in '.elseif' directive");
2511 TheCondState.CondMet = ExprValue;
2512 TheCondState.Ignore = !TheCondState.CondMet;
2518 /// ParseDirectiveElse
2520 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2521 if (getLexer().isNot(AsmToken::EndOfStatement))
2522 return TokError("unexpected token in '.else' directive");
2526 if (TheCondState.TheCond != AsmCond::IfCond &&
2527 TheCondState.TheCond != AsmCond::ElseIfCond)
2528 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2530 TheCondState.TheCond = AsmCond::ElseCond;
2531 bool LastIgnoreState = false;
2532 if (!TheCondStack.empty())
2533 LastIgnoreState = TheCondStack.back().Ignore;
2534 if (LastIgnoreState || TheCondState.CondMet)
2535 TheCondState.Ignore = true;
2537 TheCondState.Ignore = false;
2542 /// ParseDirectiveEndIf
2544 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2545 if (getLexer().isNot(AsmToken::EndOfStatement))
2546 return TokError("unexpected token in '.endif' directive");
2550 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2551 TheCondStack.empty())
2552 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2554 if (!TheCondStack.empty()) {
2555 TheCondState = TheCondStack.back();
2556 TheCondStack.pop_back();
2562 /// ParseDirectiveFile
2563 /// ::= .file [number] filename
2564 /// ::= .file number directory filename
2565 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2566 // FIXME: I'm not sure what this is.
2567 int64_t FileNumber = -1;
2568 SMLoc FileNumberLoc = getLexer().getLoc();
2569 if (getLexer().is(AsmToken::Integer)) {
2570 FileNumber = getTok().getIntVal();
2574 return TokError("file number less than one");
2577 if (getLexer().isNot(AsmToken::String))
2578 return TokError("unexpected token in '.file' directive");
2580 // Usually the directory and filename together, otherwise just the directory.
2581 StringRef Path = getTok().getString();
2582 Path = Path.substr(1, Path.size()-2);
2585 StringRef Directory;
2587 if (getLexer().is(AsmToken::String)) {
2588 if (FileNumber == -1)
2589 return TokError("explicit path specified, but no file number");
2590 Filename = getTok().getString();
2591 Filename = Filename.substr(1, Filename.size()-2);
2598 if (getLexer().isNot(AsmToken::EndOfStatement))
2599 return TokError("unexpected token in '.file' directive");
2601 if (FileNumber == -1)
2602 getStreamer().EmitFileDirective(Filename);
2604 if (getContext().getGenDwarfForAssembly() == true)
2605 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2606 "used to generate dwarf debug info for assembly code");
2608 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2609 Error(FileNumberLoc, "file number already allocated");
2615 /// ParseDirectiveLine
2616 /// ::= .line [number]
2617 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2618 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2619 if (getLexer().isNot(AsmToken::Integer))
2620 return TokError("unexpected token in '.line' directive");
2622 int64_t LineNumber = getTok().getIntVal();
2626 // FIXME: Do something with the .line.
2629 if (getLexer().isNot(AsmToken::EndOfStatement))
2630 return TokError("unexpected token in '.line' directive");
2636 /// ParseDirectiveLoc
2637 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2638 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2639 /// The first number is a file number, must have been previously assigned with
2640 /// a .file directive, the second number is the line number and optionally the
2641 /// third number is a column position (zero if not specified). The remaining
2642 /// optional items are .loc sub-directives.
2643 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2645 if (getLexer().isNot(AsmToken::Integer))
2646 return TokError("unexpected token in '.loc' directive");
2647 int64_t FileNumber = getTok().getIntVal();
2649 return TokError("file number less than one in '.loc' directive");
2650 if (!getContext().isValidDwarfFileNumber(FileNumber))
2651 return TokError("unassigned file number in '.loc' directive");
2654 int64_t LineNumber = 0;
2655 if (getLexer().is(AsmToken::Integer)) {
2656 LineNumber = getTok().getIntVal();
2658 return TokError("line number less than one in '.loc' directive");
2662 int64_t ColumnPos = 0;
2663 if (getLexer().is(AsmToken::Integer)) {
2664 ColumnPos = getTok().getIntVal();
2666 return TokError("column position less than zero in '.loc' directive");
2670 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2672 int64_t Discriminator = 0;
2673 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2675 if (getLexer().is(AsmToken::EndOfStatement))
2679 SMLoc Loc = getTok().getLoc();
2680 if (getParser().ParseIdentifier(Name))
2681 return TokError("unexpected token in '.loc' directive");
2683 if (Name == "basic_block")
2684 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2685 else if (Name == "prologue_end")
2686 Flags |= DWARF2_FLAG_PROLOGUE_END;
2687 else if (Name == "epilogue_begin")
2688 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2689 else if (Name == "is_stmt") {
2690 SMLoc Loc = getTok().getLoc();
2691 const MCExpr *Value;
2692 if (getParser().ParseExpression(Value))
2694 // The expression must be the constant 0 or 1.
2695 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2696 int Value = MCE->getValue();
2698 Flags &= ~DWARF2_FLAG_IS_STMT;
2699 else if (Value == 1)
2700 Flags |= DWARF2_FLAG_IS_STMT;
2702 return Error(Loc, "is_stmt value not 0 or 1");
2705 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2708 else if (Name == "isa") {
2709 SMLoc Loc = getTok().getLoc();
2710 const MCExpr *Value;
2711 if (getParser().ParseExpression(Value))
2713 // The expression must be a constant greater or equal to 0.
2714 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2715 int Value = MCE->getValue();
2717 return Error(Loc, "isa number less than zero");
2721 return Error(Loc, "isa number not a constant value");
2724 else if (Name == "discriminator") {
2725 if (getParser().ParseAbsoluteExpression(Discriminator))
2729 return Error(Loc, "unknown sub-directive in '.loc' directive");
2732 if (getLexer().is(AsmToken::EndOfStatement))
2737 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2738 Isa, Discriminator, StringRef());
2743 /// ParseDirectiveStabs
2744 /// ::= .stabs string, number, number, number
2745 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2746 SMLoc DirectiveLoc) {
2747 return TokError("unsupported directive '" + Directive + "'");
2750 /// ParseDirectiveCFISections
2751 /// ::= .cfi_sections section [, section]
2752 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2753 SMLoc DirectiveLoc) {
2758 if (getParser().ParseIdentifier(Name))
2759 return TokError("Expected an identifier");
2761 if (Name == ".eh_frame")
2763 else if (Name == ".debug_frame")
2766 if (getLexer().is(AsmToken::Comma)) {
2769 if (getParser().ParseIdentifier(Name))
2770 return TokError("Expected an identifier");
2772 if (Name == ".eh_frame")
2774 else if (Name == ".debug_frame")
2778 getStreamer().EmitCFISections(EH, Debug);
2783 /// ParseDirectiveCFIStartProc
2784 /// ::= .cfi_startproc
2785 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2786 SMLoc DirectiveLoc) {
2787 getStreamer().EmitCFIStartProc();
2791 /// ParseDirectiveCFIEndProc
2792 /// ::= .cfi_endproc
2793 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2794 getStreamer().EmitCFIEndProc();
2798 /// ParseRegisterOrRegisterNumber - parse register name or number.
2799 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2800 SMLoc DirectiveLoc) {
2803 if (getLexer().isNot(AsmToken::Integer)) {
2804 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2807 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2809 return getParser().ParseAbsoluteExpression(Register);
2814 /// ParseDirectiveCFIDefCfa
2815 /// ::= .cfi_def_cfa register, offset
2816 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2817 SMLoc DirectiveLoc) {
2818 int64_t Register = 0;
2819 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2822 if (getLexer().isNot(AsmToken::Comma))
2823 return TokError("unexpected token in directive");
2827 if (getParser().ParseAbsoluteExpression(Offset))
2830 getStreamer().EmitCFIDefCfa(Register, Offset);
2834 /// ParseDirectiveCFIDefCfaOffset
2835 /// ::= .cfi_def_cfa_offset offset
2836 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2837 SMLoc DirectiveLoc) {
2839 if (getParser().ParseAbsoluteExpression(Offset))
2842 getStreamer().EmitCFIDefCfaOffset(Offset);
2846 /// ParseDirectiveCFIAdjustCfaOffset
2847 /// ::= .cfi_adjust_cfa_offset adjustment
2848 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2849 SMLoc DirectiveLoc) {
2850 int64_t Adjustment = 0;
2851 if (getParser().ParseAbsoluteExpression(Adjustment))
2854 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2858 /// ParseDirectiveCFIDefCfaRegister
2859 /// ::= .cfi_def_cfa_register register
2860 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2861 SMLoc DirectiveLoc) {
2862 int64_t Register = 0;
2863 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2866 getStreamer().EmitCFIDefCfaRegister(Register);
2870 /// ParseDirectiveCFIOffset
2871 /// ::= .cfi_offset register, offset
2872 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2873 int64_t Register = 0;
2876 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2879 if (getLexer().isNot(AsmToken::Comma))
2880 return TokError("unexpected token in directive");
2883 if (getParser().ParseAbsoluteExpression(Offset))
2886 getStreamer().EmitCFIOffset(Register, Offset);
2890 /// ParseDirectiveCFIRelOffset
2891 /// ::= .cfi_rel_offset register, offset
2892 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2893 SMLoc DirectiveLoc) {
2894 int64_t Register = 0;
2896 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2899 if (getLexer().isNot(AsmToken::Comma))
2900 return TokError("unexpected token in directive");
2904 if (getParser().ParseAbsoluteExpression(Offset))
2907 getStreamer().EmitCFIRelOffset(Register, Offset);
2911 static bool isValidEncoding(int64_t Encoding) {
2912 if (Encoding & ~0xff)
2915 if (Encoding == dwarf::DW_EH_PE_omit)
2918 const unsigned Format = Encoding & 0xf;
2919 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2920 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2921 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2922 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2925 const unsigned Application = Encoding & 0x70;
2926 if (Application != dwarf::DW_EH_PE_absptr &&
2927 Application != dwarf::DW_EH_PE_pcrel)
2933 /// ParseDirectiveCFIPersonalityOrLsda
2934 /// ::= .cfi_personality encoding, [symbol_name]
2935 /// ::= .cfi_lsda encoding, [symbol_name]
2936 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2937 SMLoc DirectiveLoc) {
2938 int64_t Encoding = 0;
2939 if (getParser().ParseAbsoluteExpression(Encoding))
2941 if (Encoding == dwarf::DW_EH_PE_omit)
2944 if (!isValidEncoding(Encoding))
2945 return TokError("unsupported encoding.");
2947 if (getLexer().isNot(AsmToken::Comma))
2948 return TokError("unexpected token in directive");
2952 if (getParser().ParseIdentifier(Name))
2953 return TokError("expected identifier in directive");
2955 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2957 if (IDVal == ".cfi_personality")
2958 getStreamer().EmitCFIPersonality(Sym, Encoding);
2960 assert(IDVal == ".cfi_lsda");
2961 getStreamer().EmitCFILsda(Sym, Encoding);
2966 /// ParseDirectiveCFIRememberState
2967 /// ::= .cfi_remember_state
2968 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2969 SMLoc DirectiveLoc) {
2970 getStreamer().EmitCFIRememberState();
2974 /// ParseDirectiveCFIRestoreState
2975 /// ::= .cfi_remember_state
2976 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2977 SMLoc DirectiveLoc) {
2978 getStreamer().EmitCFIRestoreState();
2982 /// ParseDirectiveCFISameValue
2983 /// ::= .cfi_same_value register
2984 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2985 SMLoc DirectiveLoc) {
2986 int64_t Register = 0;
2988 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2991 getStreamer().EmitCFISameValue(Register);
2996 /// ParseDirectiveCFIRestore
2997 /// ::= .cfi_restore register
2998 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2999 SMLoc DirectiveLoc) {
3000 int64_t Register = 0;
3001 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3004 getStreamer().EmitCFIRestore(Register);
3009 /// ParseDirectiveCFIEscape
3010 /// ::= .cfi_escape expression[,...]
3011 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3012 SMLoc DirectiveLoc) {
3015 if (getParser().ParseAbsoluteExpression(CurrValue))
3018 Values.push_back((uint8_t)CurrValue);
3020 while (getLexer().is(AsmToken::Comma)) {
3023 if (getParser().ParseAbsoluteExpression(CurrValue))
3026 Values.push_back((uint8_t)CurrValue);
3029 getStreamer().EmitCFIEscape(Values);
3033 /// ParseDirectiveCFISignalFrame
3034 /// ::= .cfi_signal_frame
3035 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3036 SMLoc DirectiveLoc) {
3037 if (getLexer().isNot(AsmToken::EndOfStatement))
3038 return Error(getLexer().getLoc(),
3039 "unexpected token in '" + Directive + "' directive");
3041 getStreamer().EmitCFISignalFrame();
3046 /// ParseDirectiveMacrosOnOff
3049 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3050 SMLoc DirectiveLoc) {
3051 if (getLexer().isNot(AsmToken::EndOfStatement))
3052 return Error(getLexer().getLoc(),
3053 "unexpected token in '" + Directive + "' directive");
3055 getParser().MacrosEnabled = Directive == ".macros_on";
3060 /// ParseDirectiveMacro
3061 /// ::= .macro name [parameters]
3062 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3063 SMLoc DirectiveLoc) {
3065 if (getParser().ParseIdentifier(Name))
3066 return TokError("expected identifier in directive");
3068 std::vector<StringRef> Parameters;
3069 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3071 StringRef Parameter;
3072 if (getParser().ParseIdentifier(Parameter))
3073 return TokError("expected identifier in directive");
3074 Parameters.push_back(Parameter);
3076 if (getLexer().isNot(AsmToken::Comma))
3082 if (getLexer().isNot(AsmToken::EndOfStatement))
3083 return TokError("unexpected token in '.macro' directive");
3085 // Eat the end of statement.
3088 AsmToken EndToken, StartToken = getTok();
3090 // Lex the macro definition.
3092 // Check whether we have reached the end of the file.
3093 if (getLexer().is(AsmToken::Eof))
3094 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3096 // Otherwise, check whether we have reach the .endmacro.
3097 if (getLexer().is(AsmToken::Identifier) &&
3098 (getTok().getIdentifier() == ".endm" ||
3099 getTok().getIdentifier() == ".endmacro")) {
3100 EndToken = getTok();
3102 if (getLexer().isNot(AsmToken::EndOfStatement))
3103 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3108 // Otherwise, scan til the end of the statement.
3109 getParser().EatToEndOfStatement();
3112 if (getParser().MacroMap.lookup(Name)) {
3113 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3116 const char *BodyStart = StartToken.getLoc().getPointer();
3117 const char *BodyEnd = EndToken.getLoc().getPointer();
3118 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3119 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3123 /// ParseDirectiveEndMacro
3126 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3127 SMLoc DirectiveLoc) {
3128 if (getLexer().isNot(AsmToken::EndOfStatement))
3129 return TokError("unexpected token in '" + Directive + "' directive");
3131 // If we are inside a macro instantiation, terminate the current
3133 if (!getParser().ActiveMacros.empty()) {
3134 getParser().HandleMacroExit();
3138 // Otherwise, this .endmacro is a stray entry in the file; well formed
3139 // .endmacro directives are handled during the macro definition parsing.
3140 return TokError("unexpected '" + Directive + "' in file, "
3141 "no current macro definition");
3144 /// ParseDirectivePurgeMacro
3146 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3147 SMLoc DirectiveLoc) {
3149 if (getParser().ParseIdentifier(Name))
3150 return TokError("expected identifier in '.purgem' directive");
3152 if (getLexer().isNot(AsmToken::EndOfStatement))
3153 return TokError("unexpected token in '.purgem' directive");
3155 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3156 if (I == getParser().MacroMap.end())
3157 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3159 // Undefine the macro.
3160 delete I->getValue();
3161 getParser().MacroMap.erase(I);
3165 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3166 getParser().CheckForValidSection();
3168 const MCExpr *Value;
3170 if (getParser().ParseExpression(Value))
3173 if (getLexer().isNot(AsmToken::EndOfStatement))
3174 return TokError("unexpected token in directive");
3176 if (DirName[1] == 's')
3177 getStreamer().EmitSLEB128Value(Value);
3179 getStreamer().EmitULEB128Value(Value);
3184 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3185 AsmToken EndToken, StartToken = getTok();
3187 unsigned NestLevel = 0;
3189 // Check whether we have reached the end of the file.
3190 if (getLexer().is(AsmToken::Eof)) {
3191 Error(DirectiveLoc, "no matching '.endr' in definition");
3195 if (Lexer.is(AsmToken::Identifier) &&
3196 (getTok().getIdentifier() == ".rept")) {
3200 // Otherwise, check whether we have reached the .endr.
3201 if (Lexer.is(AsmToken::Identifier) &&
3202 getTok().getIdentifier() == ".endr") {
3203 if (NestLevel == 0) {
3204 EndToken = getTok();
3206 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3207 TokError("unexpected token in '.endr' directive");
3215 // Otherwise, scan till the end of the statement.
3216 EatToEndOfStatement();
3219 const char *BodyStart = StartToken.getLoc().getPointer();
3220 const char *BodyEnd = EndToken.getLoc().getPointer();
3221 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3223 // We Are Anonymous.
3225 std::vector<StringRef> Parameters;
3226 return new Macro(Name, Body, Parameters);
3229 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3230 raw_svector_ostream &OS) {
3233 MemoryBuffer *Instantiation =
3234 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3236 // Create the macro instantiation object and add to the current macro
3237 // instantiation stack.
3238 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3241 ActiveMacros.push_back(MI);
3243 // Jump to the macro instantiation and prime the lexer.
3244 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3245 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3249 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3251 if (ParseAbsoluteExpression(Count))
3252 return TokError("unexpected token in '.rept' directive");
3255 return TokError("Count is negative");
3257 if (Lexer.isNot(AsmToken::EndOfStatement))
3258 return TokError("unexpected token in '.rept' directive");
3260 // Eat the end of statement.
3263 // Lex the rept definition.
3264 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3268 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3269 // to hold the macro body with substitutions.
3270 SmallString<256> Buf;
3271 std::vector<StringRef> Parameters;
3272 const std::vector<MacroArgument> A;
3273 raw_svector_ostream OS(Buf);
3275 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3278 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3283 /// ParseDirectiveIrp
3284 /// ::= .irp symbol,values
3285 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3286 std::vector<StringRef> Parameters;
3287 StringRef Parameter;
3289 if (ParseIdentifier(Parameter))
3290 return TokError("expected identifier in '.irp' directive");
3292 Parameters.push_back(Parameter);
3294 if (Lexer.isNot(AsmToken::Comma))
3295 return TokError("expected comma in '.irp' directive");
3299 std::vector<MacroArgument> A;
3300 if (ParseMacroArguments(0, A))
3303 // Eat the end of statement.
3306 // Lex the irp definition.
3307 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3311 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3312 // to hold the macro body with substitutions.
3313 SmallString<256> Buf;
3314 raw_svector_ostream OS(Buf);
3316 for (std::vector<MacroArgument>::iterator i = A.begin(), e = A.end(); i != e;
3318 std::vector<MacroArgument> Args;
3321 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3325 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3330 /// ParseDirectiveIrpc
3331 /// ::= .irpc symbol,values
3332 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3333 std::vector<StringRef> Parameters;
3334 StringRef Parameter;
3336 if (ParseIdentifier(Parameter))
3337 return TokError("expected identifier in '.irpc' directive");
3339 Parameters.push_back(Parameter);
3341 if (Lexer.isNot(AsmToken::Comma))
3342 return TokError("expected comma in '.irpc' directive");
3346 std::vector<MacroArgument> A;
3347 if (ParseMacroArguments(0, A))
3350 if (A.size() != 1 || A.front().size() != 1)
3351 return TokError("unexpected token in '.irpc' directive");
3353 // Eat the end of statement.
3356 // Lex the irpc definition.
3357 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3361 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3362 // to hold the macro body with substitutions.
3363 SmallString<256> Buf;
3364 raw_svector_ostream OS(Buf);
3366 StringRef Values = A.front().front().getString();
3367 std::size_t I, End = Values.size();
3368 for (I = 0; I < End; ++I) {
3370 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3372 std::vector<MacroArgument> Args;
3373 Args.push_back(Arg);
3375 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3379 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3384 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3385 if (ActiveMacros.empty())
3386 return TokError("unexpected '.endr' directive, no current .rept");
3388 // The only .repl that should get here are the ones created by
3389 // InstantiateMacroLikeBody.
3390 assert(getLexer().is(AsmToken::EndOfStatement));
3396 /// \brief Create an MCAsmParser instance.
3397 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3398 MCContext &C, MCStreamer &Out,
3399 const MCAsmInfo &MAI) {
3400 return new AsmParser(SM, C, Out, MAI);