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 != ".") {
1171 // Target hook for parsing target specific directives.
1172 if (!getTargetParser().ParseDirective(ID))
1175 // Assembler features
1176 if (IDVal == ".set" || IDVal == ".equ")
1177 return ParseDirectiveSet(IDVal, true);
1178 if (IDVal == ".equiv")
1179 return ParseDirectiveSet(IDVal, false);
1183 if (IDVal == ".ascii")
1184 return ParseDirectiveAscii(IDVal, false);
1185 if (IDVal == ".asciz" || IDVal == ".string")
1186 return ParseDirectiveAscii(IDVal, true);
1188 if (IDVal == ".byte")
1189 return ParseDirectiveValue(1);
1190 if (IDVal == ".short")
1191 return ParseDirectiveValue(2);
1192 if (IDVal == ".value")
1193 return ParseDirectiveValue(2);
1194 if (IDVal == ".2byte")
1195 return ParseDirectiveValue(2);
1196 if (IDVal == ".long")
1197 return ParseDirectiveValue(4);
1198 if (IDVal == ".int")
1199 return ParseDirectiveValue(4);
1200 if (IDVal == ".4byte")
1201 return ParseDirectiveValue(4);
1202 if (IDVal == ".quad")
1203 return ParseDirectiveValue(8);
1204 if (IDVal == ".8byte")
1205 return ParseDirectiveValue(8);
1206 if (IDVal == ".single" || IDVal == ".float")
1207 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1208 if (IDVal == ".double")
1209 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1211 if (IDVal == ".align") {
1212 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1213 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1215 if (IDVal == ".align32") {
1216 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1217 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1219 if (IDVal == ".balign")
1220 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1221 if (IDVal == ".balignw")
1222 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1223 if (IDVal == ".balignl")
1224 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1225 if (IDVal == ".p2align")
1226 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1227 if (IDVal == ".p2alignw")
1228 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1229 if (IDVal == ".p2alignl")
1230 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1232 if (IDVal == ".org")
1233 return ParseDirectiveOrg();
1235 if (IDVal == ".fill")
1236 return ParseDirectiveFill();
1237 if (IDVal == ".space" || IDVal == ".skip")
1238 return ParseDirectiveSpace();
1239 if (IDVal == ".zero")
1240 return ParseDirectiveZero();
1242 // Symbol attribute directives
1244 if (IDVal == ".extern") {
1245 EatToEndOfStatement(); // .extern is the default, ignore it.
1248 if (IDVal == ".globl" || IDVal == ".global")
1249 return ParseDirectiveSymbolAttribute(MCSA_Global);
1250 if (IDVal == ".indirect_symbol")
1251 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1252 if (IDVal == ".lazy_reference")
1253 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1254 if (IDVal == ".no_dead_strip")
1255 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1256 if (IDVal == ".symbol_resolver")
1257 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1258 if (IDVal == ".private_extern")
1259 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1260 if (IDVal == ".reference")
1261 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1262 if (IDVal == ".weak_definition")
1263 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1264 if (IDVal == ".weak_reference")
1265 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1266 if (IDVal == ".weak_def_can_be_hidden")
1267 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1269 if (IDVal == ".comm" || IDVal == ".common")
1270 return ParseDirectiveComm(/*IsLocal=*/false);
1271 if (IDVal == ".lcomm")
1272 return ParseDirectiveComm(/*IsLocal=*/true);
1274 if (IDVal == ".abort")
1275 return ParseDirectiveAbort();
1276 if (IDVal == ".include")
1277 return ParseDirectiveInclude();
1278 if (IDVal == ".incbin")
1279 return ParseDirectiveIncbin();
1281 if (IDVal == ".code16" || IDVal == ".code16gcc")
1282 return TokError(Twine(IDVal) + " not supported yet");
1284 // Macro-like directives
1285 if (IDVal == ".rept")
1286 return ParseDirectiveRept(IDLoc);
1287 if (IDVal == ".irp")
1288 return ParseDirectiveIrp(IDLoc);
1289 if (IDVal == ".irpc")
1290 return ParseDirectiveIrpc(IDLoc);
1291 if (IDVal == ".endr")
1292 return ParseDirectiveEndr(IDLoc);
1294 // Look up the handler in the handler table.
1295 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1296 DirectiveMap.lookup(IDVal);
1298 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1301 return Error(IDLoc, "unknown directive");
1304 CheckForValidSection();
1306 // Canonicalize the opcode to lower case.
1307 SmallString<128> Opcode;
1308 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1309 Opcode.push_back(tolower(IDVal[i]));
1311 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1312 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1315 // Dump the parsed representation, if requested.
1316 if (getShowParsedOperands()) {
1317 SmallString<256> Str;
1318 raw_svector_ostream OS(Str);
1319 OS << "parsed instruction: [";
1320 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1323 ParsedOperands[i]->print(OS);
1327 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1330 // If we are generating dwarf for assembly source files and the current
1331 // section is the initial text section then generate a .loc directive for
1333 if (!HadError && getContext().getGenDwarfForAssembly() &&
1334 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1335 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1336 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1337 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1338 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1342 // If parsing succeeded, match the instruction.
1344 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1347 // Free any parsed operands.
1348 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1349 delete ParsedOperands[i];
1351 // Don't skip the rest of the line, the instruction parser is responsible for
1356 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1357 /// since they may not be able to be tokenized to get to the end of line token.
1358 void AsmParser::EatToEndOfLine() {
1359 if (!Lexer.is(AsmToken::EndOfStatement))
1360 Lexer.LexUntilEndOfLine();
1365 /// ParseCppHashLineFilenameComment as this:
1366 /// ::= # number "filename"
1367 /// or just as a full line comment if it doesn't have a number and a string.
1368 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1369 Lex(); // Eat the hash token.
1371 if (getLexer().isNot(AsmToken::Integer)) {
1372 // Consume the line since in cases it is not a well-formed line directive,
1373 // as if were simply a full line comment.
1378 int64_t LineNumber = getTok().getIntVal();
1381 if (getLexer().isNot(AsmToken::String)) {
1386 StringRef Filename = getTok().getString();
1387 // Get rid of the enclosing quotes.
1388 Filename = Filename.substr(1, Filename.size()-2);
1390 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1392 CppHashFilename = Filename;
1393 CppHashLineNumber = LineNumber;
1395 // Ignore any trailing characters, they're just comment.
1400 /// DiagHandler - will use the last parsed cpp hash line filename comment
1401 /// for the Filename and LineNo if any in the diagnostic.
1402 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1403 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1404 raw_ostream &OS = errs();
1406 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1407 const SMLoc &DiagLoc = Diag.getLoc();
1408 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1409 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1411 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1412 // before printing the message.
1413 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1414 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1415 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1416 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1419 // If we have not parsed a cpp hash line filename comment or the source
1420 // manager changed or buffer changed (like in a nested include) then just
1421 // print the normal diagnostic using its Filename and LineNo.
1422 if (!Parser->CppHashLineNumber ||
1423 &DiagSrcMgr != &Parser->SrcMgr ||
1424 DiagBuf != CppHashBuf) {
1425 if (Parser->SavedDiagHandler)
1426 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1432 // Use the CppHashFilename and calculate a line number based on the
1433 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1435 const std::string Filename = Parser->CppHashFilename;
1437 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1438 int CppHashLocLineNo =
1439 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1440 int LineNo = Parser->CppHashLineNumber - 1 +
1441 (DiagLocLineNo - CppHashLocLineNo);
1443 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1444 Filename, LineNo, Diag.getColumnNo(),
1445 Diag.getKind(), Diag.getMessage(),
1446 Diag.getLineContents(), Diag.getRanges());
1448 if (Parser->SavedDiagHandler)
1449 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1451 NewDiag.print(0, OS);
1454 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1455 const std::vector<StringRef> &Parameters,
1456 const std::vector<MacroArgument> &A,
1458 unsigned NParameters = Parameters.size();
1459 if (NParameters != 0 && NParameters != A.size())
1460 return Error(L, "Wrong number of arguments");
1462 while (!Body.empty()) {
1463 // Scan for the next substitution.
1464 std::size_t End = Body.size(), Pos = 0;
1465 for (; Pos != End; ++Pos) {
1466 // Check for a substitution or escape.
1468 // This macro has no parameters, look for $0, $1, etc.
1469 if (Body[Pos] != '$' || Pos + 1 == End)
1472 char Next = Body[Pos + 1];
1473 if (Next == '$' || Next == 'n' || isdigit(Next))
1476 // This macro has parameters, look for \foo, \bar, etc.
1477 if (Body[Pos] == '\\' && Pos + 1 != End)
1483 OS << Body.slice(0, Pos);
1485 // Check if we reached the end.
1490 switch (Body[Pos+1]) {
1496 // $n => number of arguments
1501 // $[0-9] => argument
1503 // Missing arguments are ignored.
1504 unsigned Index = Body[Pos+1] - '0';
1505 if (Index >= A.size())
1508 // Otherwise substitute with the token values, with spaces eliminated.
1509 for (MacroArgument::const_iterator it = A[Index].begin(),
1510 ie = A[Index].end(); it != ie; ++it)
1511 OS << it->getString();
1517 unsigned I = Pos + 1;
1518 while (isalnum(Body[I]) && I + 1 != End)
1521 const char *Begin = Body.data() + Pos +1;
1522 StringRef Argument(Begin, I - (Pos +1));
1524 for (; Index < NParameters; ++Index)
1525 if (Parameters[Index] == Argument)
1528 // FIXME: We should error at the macro definition.
1529 if (Index == NParameters)
1530 return Error(L, "Parameter not found");
1532 for (MacroArgument::const_iterator it = A[Index].begin(),
1533 ie = A[Index].end(); it != ie; ++it)
1534 OS << it->getString();
1536 Pos += 1 + Argument.size();
1538 // Update the scan point.
1539 Body = Body.substr(Pos);
1545 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1547 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1551 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1552 /// This is used for both default macro parameter values and the
1553 /// arguments in macro invocations
1554 bool AsmParser::ParseMacroArgument(MacroArgument &MA) {
1555 unsigned ParenLevel = 0;
1560 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1561 return TokError("unexpected token in macro instantiation");
1563 // HandleMacroEntry relies on not advancing the lexer here
1564 // to be able to fill in the remaining default parameter values
1565 if (Lexer.is(AsmToken::EndOfStatement))
1567 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1570 // Adjust the current parentheses level.
1571 if (Lexer.is(AsmToken::LParen))
1573 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1576 // Append the token to the current argument list.
1577 MA.push_back(getTok());
1580 if (ParenLevel != 0)
1581 return TokError("unbalanced parenthesises in macro argument");
1585 // Parse the macro instantiation arguments.
1586 bool AsmParser::ParseMacroArguments(const Macro *M,
1587 std::vector<MacroArgument> &A) {
1588 const unsigned NParameters = M ? M->Parameters.size() : 0;
1590 // Parse two kinds of macro invocations:
1591 // - macros defined without any parameters accept an arbitrary number of them
1592 // - macros defined with parameters accept at most that many of them
1593 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1597 if (ParseMacroArgument(MA))
1602 if (Lexer.is(AsmToken::EndOfStatement))
1605 if (Lexer.is(AsmToken::Comma))
1608 return TokError("Too many arguments");
1611 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1613 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1614 // this, although we should protect against infinite loops.
1615 if (ActiveMacros.size() == 20)
1616 return TokError("macros cannot be nested more than 20 levels deep");
1618 std::vector<MacroArgument> MacroArguments;
1619 if (ParseMacroArguments(M, MacroArguments))
1622 // Remove any trailing empty arguments. Do this after-the-fact as we have
1623 // to keep empty arguments in the middle of the list or positionality
1624 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1625 while (!MacroArguments.empty() && MacroArguments.back().empty())
1626 MacroArguments.pop_back();
1628 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1629 // to hold the macro body with substitutions.
1630 SmallString<256> Buf;
1631 StringRef Body = M->Body;
1632 raw_svector_ostream OS(Buf);
1634 if (expandMacro(OS, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1637 // We include the .endmacro in the buffer as our queue to exit the macro
1639 OS << ".endmacro\n";
1641 MemoryBuffer *Instantiation =
1642 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1644 // Create the macro instantiation object and add to the current macro
1645 // instantiation stack.
1646 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1649 ActiveMacros.push_back(MI);
1651 // Jump to the macro instantiation and prime the lexer.
1652 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1653 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1659 void AsmParser::HandleMacroExit() {
1660 // Jump to the EndOfStatement we should return to, and consume it.
1661 JumpToLoc(ActiveMacros.back()->ExitLoc);
1664 // Pop the instantiation entry.
1665 delete ActiveMacros.back();
1666 ActiveMacros.pop_back();
1669 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1670 switch (Value->getKind()) {
1671 case MCExpr::Binary: {
1672 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1673 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1676 case MCExpr::Target:
1677 case MCExpr::Constant:
1679 case MCExpr::SymbolRef: {
1680 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1682 return IsUsedIn(Sym, S.getVariableValue());
1686 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1689 llvm_unreachable("Unknown expr kind!");
1692 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1693 // FIXME: Use better location, we should use proper tokens.
1694 SMLoc EqualLoc = Lexer.getLoc();
1696 const MCExpr *Value;
1697 if (ParseExpression(Value))
1700 // Note: we don't count b as used in "a = b". This is to allow
1704 if (Lexer.isNot(AsmToken::EndOfStatement))
1705 return TokError("unexpected token in assignment");
1707 // Error on assignment to '.'.
1709 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1710 "(use '.space' or '.org').)"));
1713 // Eat the end of statement marker.
1716 // Validate that the LHS is allowed to be a variable (either it has not been
1717 // used as a symbol, or it is an absolute symbol).
1718 MCSymbol *Sym = getContext().LookupSymbol(Name);
1720 // Diagnose assignment to a label.
1722 // FIXME: Diagnostics. Note the location of the definition as a label.
1723 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1724 if (IsUsedIn(Sym, Value))
1725 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1726 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1727 ; // Allow redefinitions of undefined symbols only used in directives.
1728 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1729 ; // Allow redefinitions of variables that haven't yet been used.
1730 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1731 return Error(EqualLoc, "redefinition of '" + Name + "'");
1732 else if (!Sym->isVariable())
1733 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1734 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1735 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1738 // Don't count these checks as uses.
1739 Sym->setUsed(false);
1741 Sym = getContext().GetOrCreateSymbol(Name);
1743 // FIXME: Handle '.'.
1745 // Do the assignment.
1746 Out.EmitAssignment(Sym, Value);
1751 /// ParseIdentifier:
1754 bool AsmParser::ParseIdentifier(StringRef &Res) {
1755 // The assembler has relaxed rules for accepting identifiers, in particular we
1756 // allow things like '.globl $foo', which would normally be separate
1757 // tokens. At this level, we have already lexed so we cannot (currently)
1758 // handle this as a context dependent token, instead we detect adjacent tokens
1759 // and return the combined identifier.
1760 if (Lexer.is(AsmToken::Dollar)) {
1761 SMLoc DollarLoc = getLexer().getLoc();
1763 // Consume the dollar sign, and check for a following identifier.
1765 if (Lexer.isNot(AsmToken::Identifier))
1768 // We have a '$' followed by an identifier, make sure they are adjacent.
1769 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1772 // Construct the joined identifier and consume the token.
1773 Res = StringRef(DollarLoc.getPointer(),
1774 getTok().getIdentifier().size() + 1);
1779 if (Lexer.isNot(AsmToken::Identifier) &&
1780 Lexer.isNot(AsmToken::String))
1783 Res = getTok().getIdentifier();
1785 Lex(); // Consume the identifier token.
1790 /// ParseDirectiveSet:
1791 /// ::= .equ identifier ',' expression
1792 /// ::= .equiv identifier ',' expression
1793 /// ::= .set identifier ',' expression
1794 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1797 if (ParseIdentifier(Name))
1798 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1800 if (getLexer().isNot(AsmToken::Comma))
1801 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1804 return ParseAssignment(Name, allow_redef);
1807 bool AsmParser::ParseEscapedString(std::string &Data) {
1808 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1811 StringRef Str = getTok().getStringContents();
1812 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1813 if (Str[i] != '\\') {
1818 // Recognize escaped characters. Note that this escape semantics currently
1819 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1822 return TokError("unexpected backslash at end of string");
1824 // Recognize octal sequences.
1825 if ((unsigned) (Str[i] - '0') <= 7) {
1826 // Consume up to three octal characters.
1827 unsigned Value = Str[i] - '0';
1829 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1831 Value = Value * 8 + (Str[i] - '0');
1833 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1835 Value = Value * 8 + (Str[i] - '0');
1840 return TokError("invalid octal escape sequence (out of range)");
1842 Data += (unsigned char) Value;
1846 // Otherwise recognize individual escapes.
1849 // Just reject invalid escape sequences for now.
1850 return TokError("invalid escape sequence (unrecognized character)");
1852 case 'b': Data += '\b'; break;
1853 case 'f': Data += '\f'; break;
1854 case 'n': Data += '\n'; break;
1855 case 'r': Data += '\r'; break;
1856 case 't': Data += '\t'; break;
1857 case '"': Data += '"'; break;
1858 case '\\': Data += '\\'; break;
1865 /// ParseDirectiveAscii:
1866 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1867 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1868 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1869 CheckForValidSection();
1872 if (getLexer().isNot(AsmToken::String))
1873 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1876 if (ParseEscapedString(Data))
1879 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1881 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1885 if (getLexer().is(AsmToken::EndOfStatement))
1888 if (getLexer().isNot(AsmToken::Comma))
1889 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1898 /// ParseDirectiveValue
1899 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1900 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1901 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1902 CheckForValidSection();
1905 const MCExpr *Value;
1906 SMLoc ExprLoc = getLexer().getLoc();
1907 if (ParseExpression(Value))
1910 // Special case constant expressions to match code generator.
1911 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1912 assert(Size <= 8 && "Invalid size");
1913 uint64_t IntValue = MCE->getValue();
1914 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1915 return Error(ExprLoc, "literal value out of range for directive");
1916 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1918 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1920 if (getLexer().is(AsmToken::EndOfStatement))
1923 // FIXME: Improve diagnostic.
1924 if (getLexer().isNot(AsmToken::Comma))
1925 return TokError("unexpected token in directive");
1934 /// ParseDirectiveRealValue
1935 /// ::= (.single | .double) [ expression (, expression)* ]
1936 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1937 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1938 CheckForValidSection();
1941 // We don't truly support arithmetic on floating point expressions, so we
1942 // have to manually parse unary prefixes.
1944 if (getLexer().is(AsmToken::Minus)) {
1947 } else if (getLexer().is(AsmToken::Plus))
1950 if (getLexer().isNot(AsmToken::Integer) &&
1951 getLexer().isNot(AsmToken::Real) &&
1952 getLexer().isNot(AsmToken::Identifier))
1953 return TokError("unexpected token in directive");
1955 // Convert to an APFloat.
1956 APFloat Value(Semantics);
1957 StringRef IDVal = getTok().getString();
1958 if (getLexer().is(AsmToken::Identifier)) {
1959 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1960 Value = APFloat::getInf(Semantics);
1961 else if (!IDVal.compare_lower("nan"))
1962 Value = APFloat::getNaN(Semantics, false, ~0);
1964 return TokError("invalid floating point literal");
1965 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1966 APFloat::opInvalidOp)
1967 return TokError("invalid floating point literal");
1971 // Consume the numeric token.
1974 // Emit the value as an integer.
1975 APInt AsInt = Value.bitcastToAPInt();
1976 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1977 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1979 if (getLexer().is(AsmToken::EndOfStatement))
1982 if (getLexer().isNot(AsmToken::Comma))
1983 return TokError("unexpected token in directive");
1992 /// ParseDirectiveSpace
1993 /// ::= .space expression [ , expression ]
1994 bool AsmParser::ParseDirectiveSpace() {
1995 CheckForValidSection();
1998 if (ParseAbsoluteExpression(NumBytes))
2001 int64_t FillExpr = 0;
2002 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2003 if (getLexer().isNot(AsmToken::Comma))
2004 return TokError("unexpected token in '.space' directive");
2007 if (ParseAbsoluteExpression(FillExpr))
2010 if (getLexer().isNot(AsmToken::EndOfStatement))
2011 return TokError("unexpected token in '.space' directive");
2017 return TokError("invalid number of bytes in '.space' directive");
2019 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2020 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2025 /// ParseDirectiveZero
2026 /// ::= .zero expression
2027 bool AsmParser::ParseDirectiveZero() {
2028 CheckForValidSection();
2031 if (ParseAbsoluteExpression(NumBytes))
2035 if (getLexer().is(AsmToken::Comma)) {
2037 if (ParseAbsoluteExpression(Val))
2041 if (getLexer().isNot(AsmToken::EndOfStatement))
2042 return TokError("unexpected token in '.zero' directive");
2046 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2051 /// ParseDirectiveFill
2052 /// ::= .fill expression , expression , expression
2053 bool AsmParser::ParseDirectiveFill() {
2054 CheckForValidSection();
2057 if (ParseAbsoluteExpression(NumValues))
2060 if (getLexer().isNot(AsmToken::Comma))
2061 return TokError("unexpected token in '.fill' directive");
2065 if (ParseAbsoluteExpression(FillSize))
2068 if (getLexer().isNot(AsmToken::Comma))
2069 return TokError("unexpected token in '.fill' directive");
2073 if (ParseAbsoluteExpression(FillExpr))
2076 if (getLexer().isNot(AsmToken::EndOfStatement))
2077 return TokError("unexpected token in '.fill' directive");
2081 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2082 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2084 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2085 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2090 /// ParseDirectiveOrg
2091 /// ::= .org expression [ , expression ]
2092 bool AsmParser::ParseDirectiveOrg() {
2093 CheckForValidSection();
2095 const MCExpr *Offset;
2096 SMLoc Loc = getTok().getLoc();
2097 if (ParseExpression(Offset))
2100 // Parse optional fill expression.
2101 int64_t FillExpr = 0;
2102 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2103 if (getLexer().isNot(AsmToken::Comma))
2104 return TokError("unexpected token in '.org' directive");
2107 if (ParseAbsoluteExpression(FillExpr))
2110 if (getLexer().isNot(AsmToken::EndOfStatement))
2111 return TokError("unexpected token in '.org' directive");
2116 // Only limited forms of relocatable expressions are accepted here, it
2117 // has to be relative to the current section. The streamer will return
2118 // 'true' if the expression wasn't evaluatable.
2119 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2120 return Error(Loc, "expected assembly-time absolute expression");
2125 /// ParseDirectiveAlign
2126 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2127 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2128 CheckForValidSection();
2130 SMLoc AlignmentLoc = getLexer().getLoc();
2132 if (ParseAbsoluteExpression(Alignment))
2136 bool HasFillExpr = false;
2137 int64_t FillExpr = 0;
2138 int64_t MaxBytesToFill = 0;
2139 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2140 if (getLexer().isNot(AsmToken::Comma))
2141 return TokError("unexpected token in directive");
2144 // The fill expression can be omitted while specifying a maximum number of
2145 // alignment bytes, e.g:
2147 if (getLexer().isNot(AsmToken::Comma)) {
2149 if (ParseAbsoluteExpression(FillExpr))
2153 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2154 if (getLexer().isNot(AsmToken::Comma))
2155 return TokError("unexpected token in directive");
2158 MaxBytesLoc = getLexer().getLoc();
2159 if (ParseAbsoluteExpression(MaxBytesToFill))
2162 if (getLexer().isNot(AsmToken::EndOfStatement))
2163 return TokError("unexpected token in directive");
2172 // Compute alignment in bytes.
2174 // FIXME: Diagnose overflow.
2175 if (Alignment >= 32) {
2176 Error(AlignmentLoc, "invalid alignment value");
2180 Alignment = 1ULL << Alignment;
2183 // Diagnose non-sensical max bytes to align.
2184 if (MaxBytesLoc.isValid()) {
2185 if (MaxBytesToFill < 1) {
2186 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2187 "many bytes, ignoring maximum bytes expression");
2191 if (MaxBytesToFill >= Alignment) {
2192 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2198 // Check whether we should use optimal code alignment for this .align
2200 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2201 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2202 ValueSize == 1 && UseCodeAlign) {
2203 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2205 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2206 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2213 /// ParseDirectiveSymbolAttribute
2214 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2215 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2216 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2219 SMLoc Loc = getTok().getLoc();
2221 if (ParseIdentifier(Name))
2222 return Error(Loc, "expected identifier in directive");
2224 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2226 // Assembler local symbols don't make any sense here. Complain loudly.
2227 if (Sym->isTemporary())
2228 return Error(Loc, "non-local symbol required in directive");
2230 getStreamer().EmitSymbolAttribute(Sym, Attr);
2232 if (getLexer().is(AsmToken::EndOfStatement))
2235 if (getLexer().isNot(AsmToken::Comma))
2236 return TokError("unexpected token in directive");
2245 /// ParseDirectiveComm
2246 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2247 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2248 CheckForValidSection();
2250 SMLoc IDLoc = getLexer().getLoc();
2252 if (ParseIdentifier(Name))
2253 return TokError("expected identifier in directive");
2255 // Handle the identifier as the key symbol.
2256 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2258 if (getLexer().isNot(AsmToken::Comma))
2259 return TokError("unexpected token in directive");
2263 SMLoc SizeLoc = getLexer().getLoc();
2264 if (ParseAbsoluteExpression(Size))
2267 int64_t Pow2Alignment = 0;
2268 SMLoc Pow2AlignmentLoc;
2269 if (getLexer().is(AsmToken::Comma)) {
2271 Pow2AlignmentLoc = getLexer().getLoc();
2272 if (ParseAbsoluteExpression(Pow2Alignment))
2275 // If this target takes alignments in bytes (not log) validate and convert.
2276 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2277 if (!isPowerOf2_64(Pow2Alignment))
2278 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2279 Pow2Alignment = Log2_64(Pow2Alignment);
2283 if (getLexer().isNot(AsmToken::EndOfStatement))
2284 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2288 // NOTE: a size of zero for a .comm should create a undefined symbol
2289 // but a size of .lcomm creates a bss symbol of size zero.
2291 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2292 "be less than zero");
2294 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2295 // may internally end up wanting an alignment in bytes.
2296 // FIXME: Diagnose overflow.
2297 if (Pow2Alignment < 0)
2298 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2299 "alignment, can't be less than zero");
2301 if (!Sym->isUndefined())
2302 return Error(IDLoc, "invalid symbol redefinition");
2304 // '.lcomm' is equivalent to '.zerofill'.
2305 // Create the Symbol as a common or local common with Size and Pow2Alignment
2307 getStreamer().EmitZerofill(Ctx.getMachOSection(
2308 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2309 0, SectionKind::getBSS()),
2310 Sym, Size, 1 << Pow2Alignment);
2314 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2318 /// ParseDirectiveAbort
2319 /// ::= .abort [... message ...]
2320 bool AsmParser::ParseDirectiveAbort() {
2321 // FIXME: Use loc from directive.
2322 SMLoc Loc = getLexer().getLoc();
2324 StringRef Str = ParseStringToEndOfStatement();
2325 if (getLexer().isNot(AsmToken::EndOfStatement))
2326 return TokError("unexpected token in '.abort' directive");
2331 Error(Loc, ".abort detected. Assembly stopping.");
2333 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2334 // FIXME: Actually abort assembly here.
2339 /// ParseDirectiveInclude
2340 /// ::= .include "filename"
2341 bool AsmParser::ParseDirectiveInclude() {
2342 if (getLexer().isNot(AsmToken::String))
2343 return TokError("expected string in '.include' directive");
2345 std::string Filename = getTok().getString();
2346 SMLoc IncludeLoc = getLexer().getLoc();
2349 if (getLexer().isNot(AsmToken::EndOfStatement))
2350 return TokError("unexpected token in '.include' directive");
2352 // Strip the quotes.
2353 Filename = Filename.substr(1, Filename.size()-2);
2355 // Attempt to switch the lexer to the included file before consuming the end
2356 // of statement to avoid losing it when we switch.
2357 if (EnterIncludeFile(Filename)) {
2358 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2365 /// ParseDirectiveIncbin
2366 /// ::= .incbin "filename"
2367 bool AsmParser::ParseDirectiveIncbin() {
2368 if (getLexer().isNot(AsmToken::String))
2369 return TokError("expected string in '.incbin' directive");
2371 std::string Filename = getTok().getString();
2372 SMLoc IncbinLoc = getLexer().getLoc();
2375 if (getLexer().isNot(AsmToken::EndOfStatement))
2376 return TokError("unexpected token in '.incbin' directive");
2378 // Strip the quotes.
2379 Filename = Filename.substr(1, Filename.size()-2);
2381 // Attempt to process the included file.
2382 if (ProcessIncbinFile(Filename)) {
2383 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2390 /// ParseDirectiveIf
2391 /// ::= .if expression
2392 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2393 TheCondStack.push_back(TheCondState);
2394 TheCondState.TheCond = AsmCond::IfCond;
2395 if (TheCondState.Ignore) {
2396 EatToEndOfStatement();
2399 if (ParseAbsoluteExpression(ExprValue))
2402 if (getLexer().isNot(AsmToken::EndOfStatement))
2403 return TokError("unexpected token in '.if' directive");
2407 TheCondState.CondMet = ExprValue;
2408 TheCondState.Ignore = !TheCondState.CondMet;
2414 /// ParseDirectiveIfb
2416 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2417 TheCondStack.push_back(TheCondState);
2418 TheCondState.TheCond = AsmCond::IfCond;
2420 if (TheCondState.Ignore) {
2421 EatToEndOfStatement();
2423 StringRef Str = ParseStringToEndOfStatement();
2425 if (getLexer().isNot(AsmToken::EndOfStatement))
2426 return TokError("unexpected token in '.ifb' directive");
2430 TheCondState.CondMet = ExpectBlank == Str.empty();
2431 TheCondState.Ignore = !TheCondState.CondMet;
2437 /// ParseDirectiveIfc
2438 /// ::= .ifc string1, string2
2439 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2440 TheCondStack.push_back(TheCondState);
2441 TheCondState.TheCond = AsmCond::IfCond;
2443 if (TheCondState.Ignore) {
2444 EatToEndOfStatement();
2446 StringRef Str1 = ParseStringToComma();
2448 if (getLexer().isNot(AsmToken::Comma))
2449 return TokError("unexpected token in '.ifc' directive");
2453 StringRef Str2 = ParseStringToEndOfStatement();
2455 if (getLexer().isNot(AsmToken::EndOfStatement))
2456 return TokError("unexpected token in '.ifc' directive");
2460 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2461 TheCondState.Ignore = !TheCondState.CondMet;
2467 /// ParseDirectiveIfdef
2468 /// ::= .ifdef symbol
2469 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2471 TheCondStack.push_back(TheCondState);
2472 TheCondState.TheCond = AsmCond::IfCond;
2474 if (TheCondState.Ignore) {
2475 EatToEndOfStatement();
2477 if (ParseIdentifier(Name))
2478 return TokError("expected identifier after '.ifdef'");
2482 MCSymbol *Sym = getContext().LookupSymbol(Name);
2485 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2487 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2488 TheCondState.Ignore = !TheCondState.CondMet;
2494 /// ParseDirectiveElseIf
2495 /// ::= .elseif expression
2496 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2497 if (TheCondState.TheCond != AsmCond::IfCond &&
2498 TheCondState.TheCond != AsmCond::ElseIfCond)
2499 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2501 TheCondState.TheCond = AsmCond::ElseIfCond;
2503 bool LastIgnoreState = false;
2504 if (!TheCondStack.empty())
2505 LastIgnoreState = TheCondStack.back().Ignore;
2506 if (LastIgnoreState || TheCondState.CondMet) {
2507 TheCondState.Ignore = true;
2508 EatToEndOfStatement();
2512 if (ParseAbsoluteExpression(ExprValue))
2515 if (getLexer().isNot(AsmToken::EndOfStatement))
2516 return TokError("unexpected token in '.elseif' directive");
2519 TheCondState.CondMet = ExprValue;
2520 TheCondState.Ignore = !TheCondState.CondMet;
2526 /// ParseDirectiveElse
2528 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2529 if (getLexer().isNot(AsmToken::EndOfStatement))
2530 return TokError("unexpected token in '.else' directive");
2534 if (TheCondState.TheCond != AsmCond::IfCond &&
2535 TheCondState.TheCond != AsmCond::ElseIfCond)
2536 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2538 TheCondState.TheCond = AsmCond::ElseCond;
2539 bool LastIgnoreState = false;
2540 if (!TheCondStack.empty())
2541 LastIgnoreState = TheCondStack.back().Ignore;
2542 if (LastIgnoreState || TheCondState.CondMet)
2543 TheCondState.Ignore = true;
2545 TheCondState.Ignore = false;
2550 /// ParseDirectiveEndIf
2552 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2553 if (getLexer().isNot(AsmToken::EndOfStatement))
2554 return TokError("unexpected token in '.endif' directive");
2558 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2559 TheCondStack.empty())
2560 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2562 if (!TheCondStack.empty()) {
2563 TheCondState = TheCondStack.back();
2564 TheCondStack.pop_back();
2570 /// ParseDirectiveFile
2571 /// ::= .file [number] filename
2572 /// ::= .file number directory filename
2573 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2574 // FIXME: I'm not sure what this is.
2575 int64_t FileNumber = -1;
2576 SMLoc FileNumberLoc = getLexer().getLoc();
2577 if (getLexer().is(AsmToken::Integer)) {
2578 FileNumber = getTok().getIntVal();
2582 return TokError("file number less than one");
2585 if (getLexer().isNot(AsmToken::String))
2586 return TokError("unexpected token in '.file' directive");
2588 // Usually the directory and filename together, otherwise just the directory.
2589 StringRef Path = getTok().getString();
2590 Path = Path.substr(1, Path.size()-2);
2593 StringRef Directory;
2595 if (getLexer().is(AsmToken::String)) {
2596 if (FileNumber == -1)
2597 return TokError("explicit path specified, but no file number");
2598 Filename = getTok().getString();
2599 Filename = Filename.substr(1, Filename.size()-2);
2606 if (getLexer().isNot(AsmToken::EndOfStatement))
2607 return TokError("unexpected token in '.file' directive");
2609 if (FileNumber == -1)
2610 getStreamer().EmitFileDirective(Filename);
2612 if (getContext().getGenDwarfForAssembly() == true)
2613 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2614 "used to generate dwarf debug info for assembly code");
2616 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2617 Error(FileNumberLoc, "file number already allocated");
2623 /// ParseDirectiveLine
2624 /// ::= .line [number]
2625 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2626 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2627 if (getLexer().isNot(AsmToken::Integer))
2628 return TokError("unexpected token in '.line' directive");
2630 int64_t LineNumber = getTok().getIntVal();
2634 // FIXME: Do something with the .line.
2637 if (getLexer().isNot(AsmToken::EndOfStatement))
2638 return TokError("unexpected token in '.line' directive");
2644 /// ParseDirectiveLoc
2645 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2646 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2647 /// The first number is a file number, must have been previously assigned with
2648 /// a .file directive, the second number is the line number and optionally the
2649 /// third number is a column position (zero if not specified). The remaining
2650 /// optional items are .loc sub-directives.
2651 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2653 if (getLexer().isNot(AsmToken::Integer))
2654 return TokError("unexpected token in '.loc' directive");
2655 int64_t FileNumber = getTok().getIntVal();
2657 return TokError("file number less than one in '.loc' directive");
2658 if (!getContext().isValidDwarfFileNumber(FileNumber))
2659 return TokError("unassigned file number in '.loc' directive");
2662 int64_t LineNumber = 0;
2663 if (getLexer().is(AsmToken::Integer)) {
2664 LineNumber = getTok().getIntVal();
2666 return TokError("line number less than one in '.loc' directive");
2670 int64_t ColumnPos = 0;
2671 if (getLexer().is(AsmToken::Integer)) {
2672 ColumnPos = getTok().getIntVal();
2674 return TokError("column position less than zero in '.loc' directive");
2678 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2680 int64_t Discriminator = 0;
2681 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2683 if (getLexer().is(AsmToken::EndOfStatement))
2687 SMLoc Loc = getTok().getLoc();
2688 if (getParser().ParseIdentifier(Name))
2689 return TokError("unexpected token in '.loc' directive");
2691 if (Name == "basic_block")
2692 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2693 else if (Name == "prologue_end")
2694 Flags |= DWARF2_FLAG_PROLOGUE_END;
2695 else if (Name == "epilogue_begin")
2696 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2697 else if (Name == "is_stmt") {
2698 SMLoc Loc = getTok().getLoc();
2699 const MCExpr *Value;
2700 if (getParser().ParseExpression(Value))
2702 // The expression must be the constant 0 or 1.
2703 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2704 int Value = MCE->getValue();
2706 Flags &= ~DWARF2_FLAG_IS_STMT;
2707 else if (Value == 1)
2708 Flags |= DWARF2_FLAG_IS_STMT;
2710 return Error(Loc, "is_stmt value not 0 or 1");
2713 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2716 else if (Name == "isa") {
2717 SMLoc Loc = getTok().getLoc();
2718 const MCExpr *Value;
2719 if (getParser().ParseExpression(Value))
2721 // The expression must be a constant greater or equal to 0.
2722 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2723 int Value = MCE->getValue();
2725 return Error(Loc, "isa number less than zero");
2729 return Error(Loc, "isa number not a constant value");
2732 else if (Name == "discriminator") {
2733 if (getParser().ParseAbsoluteExpression(Discriminator))
2737 return Error(Loc, "unknown sub-directive in '.loc' directive");
2740 if (getLexer().is(AsmToken::EndOfStatement))
2745 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2746 Isa, Discriminator, StringRef());
2751 /// ParseDirectiveStabs
2752 /// ::= .stabs string, number, number, number
2753 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2754 SMLoc DirectiveLoc) {
2755 return TokError("unsupported directive '" + Directive + "'");
2758 /// ParseDirectiveCFISections
2759 /// ::= .cfi_sections section [, section]
2760 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2761 SMLoc DirectiveLoc) {
2766 if (getParser().ParseIdentifier(Name))
2767 return TokError("Expected an identifier");
2769 if (Name == ".eh_frame")
2771 else if (Name == ".debug_frame")
2774 if (getLexer().is(AsmToken::Comma)) {
2777 if (getParser().ParseIdentifier(Name))
2778 return TokError("Expected an identifier");
2780 if (Name == ".eh_frame")
2782 else if (Name == ".debug_frame")
2786 getStreamer().EmitCFISections(EH, Debug);
2791 /// ParseDirectiveCFIStartProc
2792 /// ::= .cfi_startproc
2793 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2794 SMLoc DirectiveLoc) {
2795 getStreamer().EmitCFIStartProc();
2799 /// ParseDirectiveCFIEndProc
2800 /// ::= .cfi_endproc
2801 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2802 getStreamer().EmitCFIEndProc();
2806 /// ParseRegisterOrRegisterNumber - parse register name or number.
2807 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2808 SMLoc DirectiveLoc) {
2811 if (getLexer().isNot(AsmToken::Integer)) {
2812 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2815 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2817 return getParser().ParseAbsoluteExpression(Register);
2822 /// ParseDirectiveCFIDefCfa
2823 /// ::= .cfi_def_cfa register, offset
2824 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2825 SMLoc DirectiveLoc) {
2826 int64_t Register = 0;
2827 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2830 if (getLexer().isNot(AsmToken::Comma))
2831 return TokError("unexpected token in directive");
2835 if (getParser().ParseAbsoluteExpression(Offset))
2838 getStreamer().EmitCFIDefCfa(Register, Offset);
2842 /// ParseDirectiveCFIDefCfaOffset
2843 /// ::= .cfi_def_cfa_offset offset
2844 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2845 SMLoc DirectiveLoc) {
2847 if (getParser().ParseAbsoluteExpression(Offset))
2850 getStreamer().EmitCFIDefCfaOffset(Offset);
2854 /// ParseDirectiveCFIAdjustCfaOffset
2855 /// ::= .cfi_adjust_cfa_offset adjustment
2856 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2857 SMLoc DirectiveLoc) {
2858 int64_t Adjustment = 0;
2859 if (getParser().ParseAbsoluteExpression(Adjustment))
2862 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2866 /// ParseDirectiveCFIDefCfaRegister
2867 /// ::= .cfi_def_cfa_register register
2868 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2869 SMLoc DirectiveLoc) {
2870 int64_t Register = 0;
2871 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2874 getStreamer().EmitCFIDefCfaRegister(Register);
2878 /// ParseDirectiveCFIOffset
2879 /// ::= .cfi_offset register, offset
2880 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2881 int64_t Register = 0;
2884 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2887 if (getLexer().isNot(AsmToken::Comma))
2888 return TokError("unexpected token in directive");
2891 if (getParser().ParseAbsoluteExpression(Offset))
2894 getStreamer().EmitCFIOffset(Register, Offset);
2898 /// ParseDirectiveCFIRelOffset
2899 /// ::= .cfi_rel_offset register, offset
2900 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2901 SMLoc DirectiveLoc) {
2902 int64_t Register = 0;
2904 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2907 if (getLexer().isNot(AsmToken::Comma))
2908 return TokError("unexpected token in directive");
2912 if (getParser().ParseAbsoluteExpression(Offset))
2915 getStreamer().EmitCFIRelOffset(Register, Offset);
2919 static bool isValidEncoding(int64_t Encoding) {
2920 if (Encoding & ~0xff)
2923 if (Encoding == dwarf::DW_EH_PE_omit)
2926 const unsigned Format = Encoding & 0xf;
2927 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2928 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2929 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2930 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2933 const unsigned Application = Encoding & 0x70;
2934 if (Application != dwarf::DW_EH_PE_absptr &&
2935 Application != dwarf::DW_EH_PE_pcrel)
2941 /// ParseDirectiveCFIPersonalityOrLsda
2942 /// ::= .cfi_personality encoding, [symbol_name]
2943 /// ::= .cfi_lsda encoding, [symbol_name]
2944 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2945 SMLoc DirectiveLoc) {
2946 int64_t Encoding = 0;
2947 if (getParser().ParseAbsoluteExpression(Encoding))
2949 if (Encoding == dwarf::DW_EH_PE_omit)
2952 if (!isValidEncoding(Encoding))
2953 return TokError("unsupported encoding.");
2955 if (getLexer().isNot(AsmToken::Comma))
2956 return TokError("unexpected token in directive");
2960 if (getParser().ParseIdentifier(Name))
2961 return TokError("expected identifier in directive");
2963 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2965 if (IDVal == ".cfi_personality")
2966 getStreamer().EmitCFIPersonality(Sym, Encoding);
2968 assert(IDVal == ".cfi_lsda");
2969 getStreamer().EmitCFILsda(Sym, Encoding);
2974 /// ParseDirectiveCFIRememberState
2975 /// ::= .cfi_remember_state
2976 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2977 SMLoc DirectiveLoc) {
2978 getStreamer().EmitCFIRememberState();
2982 /// ParseDirectiveCFIRestoreState
2983 /// ::= .cfi_remember_state
2984 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2985 SMLoc DirectiveLoc) {
2986 getStreamer().EmitCFIRestoreState();
2990 /// ParseDirectiveCFISameValue
2991 /// ::= .cfi_same_value register
2992 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2993 SMLoc DirectiveLoc) {
2994 int64_t Register = 0;
2996 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2999 getStreamer().EmitCFISameValue(Register);
3004 /// ParseDirectiveCFIRestore
3005 /// ::= .cfi_restore register
3006 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3007 SMLoc DirectiveLoc) {
3008 int64_t Register = 0;
3009 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3012 getStreamer().EmitCFIRestore(Register);
3017 /// ParseDirectiveCFIEscape
3018 /// ::= .cfi_escape expression[,...]
3019 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3020 SMLoc DirectiveLoc) {
3023 if (getParser().ParseAbsoluteExpression(CurrValue))
3026 Values.push_back((uint8_t)CurrValue);
3028 while (getLexer().is(AsmToken::Comma)) {
3031 if (getParser().ParseAbsoluteExpression(CurrValue))
3034 Values.push_back((uint8_t)CurrValue);
3037 getStreamer().EmitCFIEscape(Values);
3041 /// ParseDirectiveCFISignalFrame
3042 /// ::= .cfi_signal_frame
3043 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3044 SMLoc DirectiveLoc) {
3045 if (getLexer().isNot(AsmToken::EndOfStatement))
3046 return Error(getLexer().getLoc(),
3047 "unexpected token in '" + Directive + "' directive");
3049 getStreamer().EmitCFISignalFrame();
3054 /// ParseDirectiveMacrosOnOff
3057 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3058 SMLoc DirectiveLoc) {
3059 if (getLexer().isNot(AsmToken::EndOfStatement))
3060 return Error(getLexer().getLoc(),
3061 "unexpected token in '" + Directive + "' directive");
3063 getParser().MacrosEnabled = Directive == ".macros_on";
3068 /// ParseDirectiveMacro
3069 /// ::= .macro name [parameters]
3070 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3071 SMLoc DirectiveLoc) {
3073 if (getParser().ParseIdentifier(Name))
3074 return TokError("expected identifier in directive");
3076 std::vector<StringRef> Parameters;
3077 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3079 StringRef Parameter;
3080 if (getParser().ParseIdentifier(Parameter))
3081 return TokError("expected identifier in directive");
3082 Parameters.push_back(Parameter);
3084 if (getLexer().isNot(AsmToken::Comma))
3090 if (getLexer().isNot(AsmToken::EndOfStatement))
3091 return TokError("unexpected token in '.macro' directive");
3093 // Eat the end of statement.
3096 AsmToken EndToken, StartToken = getTok();
3098 // Lex the macro definition.
3100 // Check whether we have reached the end of the file.
3101 if (getLexer().is(AsmToken::Eof))
3102 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3104 // Otherwise, check whether we have reach the .endmacro.
3105 if (getLexer().is(AsmToken::Identifier) &&
3106 (getTok().getIdentifier() == ".endm" ||
3107 getTok().getIdentifier() == ".endmacro")) {
3108 EndToken = getTok();
3110 if (getLexer().isNot(AsmToken::EndOfStatement))
3111 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3116 // Otherwise, scan til the end of the statement.
3117 getParser().EatToEndOfStatement();
3120 if (getParser().MacroMap.lookup(Name)) {
3121 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3124 const char *BodyStart = StartToken.getLoc().getPointer();
3125 const char *BodyEnd = EndToken.getLoc().getPointer();
3126 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3127 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3131 /// ParseDirectiveEndMacro
3134 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3135 SMLoc DirectiveLoc) {
3136 if (getLexer().isNot(AsmToken::EndOfStatement))
3137 return TokError("unexpected token in '" + Directive + "' directive");
3139 // If we are inside a macro instantiation, terminate the current
3141 if (!getParser().ActiveMacros.empty()) {
3142 getParser().HandleMacroExit();
3146 // Otherwise, this .endmacro is a stray entry in the file; well formed
3147 // .endmacro directives are handled during the macro definition parsing.
3148 return TokError("unexpected '" + Directive + "' in file, "
3149 "no current macro definition");
3152 /// ParseDirectivePurgeMacro
3154 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3155 SMLoc DirectiveLoc) {
3157 if (getParser().ParseIdentifier(Name))
3158 return TokError("expected identifier in '.purgem' directive");
3160 if (getLexer().isNot(AsmToken::EndOfStatement))
3161 return TokError("unexpected token in '.purgem' directive");
3163 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3164 if (I == getParser().MacroMap.end())
3165 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3167 // Undefine the macro.
3168 delete I->getValue();
3169 getParser().MacroMap.erase(I);
3173 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3174 getParser().CheckForValidSection();
3176 const MCExpr *Value;
3178 if (getParser().ParseExpression(Value))
3181 if (getLexer().isNot(AsmToken::EndOfStatement))
3182 return TokError("unexpected token in directive");
3184 if (DirName[1] == 's')
3185 getStreamer().EmitSLEB128Value(Value);
3187 getStreamer().EmitULEB128Value(Value);
3192 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3193 AsmToken EndToken, StartToken = getTok();
3195 unsigned NestLevel = 0;
3197 // Check whether we have reached the end of the file.
3198 if (getLexer().is(AsmToken::Eof)) {
3199 Error(DirectiveLoc, "no matching '.endr' in definition");
3203 if (Lexer.is(AsmToken::Identifier) &&
3204 (getTok().getIdentifier() == ".rept")) {
3208 // Otherwise, check whether we have reached the .endr.
3209 if (Lexer.is(AsmToken::Identifier) &&
3210 getTok().getIdentifier() == ".endr") {
3211 if (NestLevel == 0) {
3212 EndToken = getTok();
3214 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3215 TokError("unexpected token in '.endr' directive");
3223 // Otherwise, scan till the end of the statement.
3224 EatToEndOfStatement();
3227 const char *BodyStart = StartToken.getLoc().getPointer();
3228 const char *BodyEnd = EndToken.getLoc().getPointer();
3229 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3231 // We Are Anonymous.
3233 std::vector<StringRef> Parameters;
3234 return new Macro(Name, Body, Parameters);
3237 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3238 raw_svector_ostream &OS) {
3241 MemoryBuffer *Instantiation =
3242 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3244 // Create the macro instantiation object and add to the current macro
3245 // instantiation stack.
3246 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3249 ActiveMacros.push_back(MI);
3251 // Jump to the macro instantiation and prime the lexer.
3252 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3253 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3257 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3259 if (ParseAbsoluteExpression(Count))
3260 return TokError("unexpected token in '.rept' directive");
3263 return TokError("Count is negative");
3265 if (Lexer.isNot(AsmToken::EndOfStatement))
3266 return TokError("unexpected token in '.rept' directive");
3268 // Eat the end of statement.
3271 // Lex the rept definition.
3272 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3276 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3277 // to hold the macro body with substitutions.
3278 SmallString<256> Buf;
3279 std::vector<StringRef> Parameters;
3280 const std::vector<MacroArgument> A;
3281 raw_svector_ostream OS(Buf);
3283 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3286 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3291 /// ParseDirectiveIrp
3292 /// ::= .irp symbol,values
3293 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3294 std::vector<StringRef> Parameters;
3295 StringRef Parameter;
3297 if (ParseIdentifier(Parameter))
3298 return TokError("expected identifier in '.irp' directive");
3300 Parameters.push_back(Parameter);
3302 if (Lexer.isNot(AsmToken::Comma))
3303 return TokError("expected comma in '.irp' directive");
3307 std::vector<MacroArgument> A;
3308 if (ParseMacroArguments(0, A))
3311 // Eat the end of statement.
3314 // Lex the irp definition.
3315 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3319 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3320 // to hold the macro body with substitutions.
3321 SmallString<256> Buf;
3322 raw_svector_ostream OS(Buf);
3324 for (std::vector<MacroArgument>::iterator i = A.begin(), e = A.end(); i != e;
3326 std::vector<MacroArgument> Args;
3329 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3333 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3338 /// ParseDirectiveIrpc
3339 /// ::= .irpc symbol,values
3340 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3341 std::vector<StringRef> Parameters;
3342 StringRef Parameter;
3344 if (ParseIdentifier(Parameter))
3345 return TokError("expected identifier in '.irpc' directive");
3347 Parameters.push_back(Parameter);
3349 if (Lexer.isNot(AsmToken::Comma))
3350 return TokError("expected comma in '.irpc' directive");
3354 std::vector<MacroArgument> A;
3355 if (ParseMacroArguments(0, A))
3358 if (A.size() != 1 || A.front().size() != 1)
3359 return TokError("unexpected token in '.irpc' directive");
3361 // Eat the end of statement.
3364 // Lex the irpc definition.
3365 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3369 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3370 // to hold the macro body with substitutions.
3371 SmallString<256> Buf;
3372 raw_svector_ostream OS(Buf);
3374 StringRef Values = A.front().front().getString();
3375 std::size_t I, End = Values.size();
3376 for (I = 0; I < End; ++I) {
3378 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3380 std::vector<MacroArgument> Args;
3381 Args.push_back(Arg);
3383 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3387 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3392 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3393 if (ActiveMacros.empty())
3394 return TokError("unexpected '.endr' directive, no current .rept");
3396 // The only .repl that should get here are the ones created by
3397 // InstantiateMacroLikeBody.
3398 assert(getLexer().is(AsmToken::EndOfStatement));
3404 /// \brief Create an MCAsmParser instance.
3405 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3406 MCContext &C, MCStreamer &Out,
3407 const MCAsmInfo &MAI) {
3408 return new AsmParser(SM, C, Out, MAI);