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 ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
283 /// \brief Generic implementations of directive handling, etc. which is shared
284 /// (or the default, at least) for all assembler parser.
285 class GenericAsmParser : public MCAsmParserExtension {
286 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
287 void AddDirectiveHandler(StringRef Directive) {
288 getParser().AddDirectiveHandler(this, Directive,
289 HandleDirective<GenericAsmParser, Handler>);
292 GenericAsmParser() {}
294 AsmParser &getParser() {
295 return (AsmParser&) this->MCAsmParserExtension::getParser();
298 virtual void Initialize(MCAsmParser &Parser) {
299 // Call the base implementation.
300 this->MCAsmParserExtension::Initialize(Parser);
302 // Debugging directives.
303 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
305 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
309 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
311 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
313 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
315 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
317 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
318 ".cfi_def_cfa_offset");
319 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
320 ".cfi_adjust_cfa_offset");
321 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
322 ".cfi_def_cfa_register");
323 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
325 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
328 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
330 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
332 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
334 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
336 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
338 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
340 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
342 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
345 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
347 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
349 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
350 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
351 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
352 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
354 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
355 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
358 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
360 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
361 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
362 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
363 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
364 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
365 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
366 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
367 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
368 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
369 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
370 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
371 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
372 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
373 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
374 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
375 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
376 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
377 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
378 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
379 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
381 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
382 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
383 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
384 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
386 bool ParseDirectiveLEB128(StringRef, SMLoc);
393 extern MCAsmParserExtension *createDarwinAsmParser();
394 extern MCAsmParserExtension *createELFAsmParser();
395 extern MCAsmParserExtension *createCOFFAsmParser();
399 enum { DEFAULT_ADDRSPACE = 0 };
401 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
402 MCStreamer &_Out, const MCAsmInfo &_MAI)
403 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
404 GenericParser(new GenericAsmParser), PlatformParser(0),
405 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
406 AssemblerDialect(~0U) {
407 // Save the old handler.
408 SavedDiagHandler = SrcMgr.getDiagHandler();
409 SavedDiagContext = SrcMgr.getDiagContext();
410 // Set our own handler which calls the saved handler.
411 SrcMgr.setDiagHandler(DiagHandler, this);
412 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
414 // Initialize the generic parser.
415 GenericParser->Initialize(*this);
417 // Initialize the platform / file format parser.
419 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
421 if (_MAI.hasMicrosoftFastStdCallMangling()) {
422 PlatformParser = createCOFFAsmParser();
423 PlatformParser->Initialize(*this);
424 } else if (_MAI.hasSubsectionsViaSymbols()) {
425 PlatformParser = createDarwinAsmParser();
426 PlatformParser->Initialize(*this);
428 PlatformParser = createELFAsmParser();
429 PlatformParser->Initialize(*this);
433 AsmParser::~AsmParser() {
434 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
436 // Destroy any macros.
437 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
438 ie = MacroMap.end(); it != ie; ++it)
439 delete it->getValue();
441 delete PlatformParser;
442 delete GenericParser;
445 void AsmParser::PrintMacroInstantiations() {
446 // Print the active macro instantiation stack.
447 for (std::vector<MacroInstantiation*>::const_reverse_iterator
448 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
449 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
450 "while in macro instantiation");
453 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
454 if (FatalAssemblerWarnings)
455 return Error(L, Msg, Ranges);
456 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
457 PrintMacroInstantiations();
461 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
463 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
464 PrintMacroInstantiations();
468 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
469 std::string IncludedFile;
470 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
476 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
481 /// Process the specified .incbin file by seaching for it in the include paths
482 /// then just emitting the byte contents of the file to the streamer. This
483 /// returns true on failure.
484 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
485 std::string IncludedFile;
486 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
490 // Pick up the bytes from the file and emit them.
491 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
496 void AsmParser::JumpToLoc(SMLoc Loc) {
497 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
498 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
501 const AsmToken &AsmParser::Lex() {
502 const AsmToken *tok = &Lexer.Lex();
504 if (tok->is(AsmToken::Eof)) {
505 // If this is the end of an included file, pop the parent file off the
507 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
508 if (ParentIncludeLoc != SMLoc()) {
509 JumpToLoc(ParentIncludeLoc);
514 if (tok->is(AsmToken::Error))
515 Error(Lexer.getErrLoc(), Lexer.getErr());
520 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
521 // Create the initial section, if requested.
522 if (!NoInitialTextSection)
529 AsmCond StartingCondState = TheCondState;
531 // If we are generating dwarf for assembly source files save the initial text
532 // section and generate a .file directive.
533 if (getContext().getGenDwarfForAssembly()) {
534 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
535 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
536 getStreamer().EmitLabel(SectionStartSym);
537 getContext().setGenDwarfSectionStartSym(SectionStartSym);
538 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
539 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
542 // While we have input, parse each statement.
543 while (Lexer.isNot(AsmToken::Eof)) {
544 if (!ParseStatement()) continue;
546 // We had an error, validate that one was emitted and recover by skipping to
548 assert(HadError && "Parse statement returned an error, but none emitted!");
549 EatToEndOfStatement();
552 if (TheCondState.TheCond != StartingCondState.TheCond ||
553 TheCondState.Ignore != StartingCondState.Ignore)
554 return TokError("unmatched .ifs or .elses");
556 // Check to see there are no empty DwarfFile slots.
557 const std::vector<MCDwarfFile *> &MCDwarfFiles =
558 getContext().getMCDwarfFiles();
559 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
560 if (!MCDwarfFiles[i])
561 TokError("unassigned file number: " + Twine(i) + " for .file directives");
564 // Check to see that all assembler local symbols were actually defined.
565 // Targets that don't do subsections via symbols may not want this, though,
566 // so conservatively exclude them. Only do this if we're finalizing, though,
567 // as otherwise we won't necessarilly have seen everything yet.
568 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
569 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
570 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
573 MCSymbol *Sym = i->getValue();
574 // Variable symbols may not be marked as defined, so check those
575 // explicitly. If we know it's a variable, we have a definition for
576 // the purposes of this check.
577 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
578 // FIXME: We would really like to refer back to where the symbol was
579 // first referenced for a source location. We need to add something
580 // to track that. Currently, we just point to the end of the file.
581 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
582 "assembler local symbol '" + Sym->getName() +
588 // Finalize the output stream if there are no errors and if the client wants
590 if (!HadError && !NoFinalize)
596 void AsmParser::CheckForValidSection() {
597 if (!getStreamer().getCurrentSection()) {
598 TokError("expected section directive before assembly directive");
599 Out.SwitchSection(Ctx.getMachOSection(
601 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
602 0, SectionKind::getText()));
606 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
607 void AsmParser::EatToEndOfStatement() {
608 while (Lexer.isNot(AsmToken::EndOfStatement) &&
609 Lexer.isNot(AsmToken::Eof))
613 if (Lexer.is(AsmToken::EndOfStatement))
617 StringRef AsmParser::ParseStringToEndOfStatement() {
618 const char *Start = getTok().getLoc().getPointer();
620 while (Lexer.isNot(AsmToken::EndOfStatement) &&
621 Lexer.isNot(AsmToken::Eof))
624 const char *End = getTok().getLoc().getPointer();
625 return StringRef(Start, End - Start);
628 StringRef AsmParser::ParseStringToComma() {
629 const char *Start = getTok().getLoc().getPointer();
631 while (Lexer.isNot(AsmToken::EndOfStatement) &&
632 Lexer.isNot(AsmToken::Comma) &&
633 Lexer.isNot(AsmToken::Eof))
636 const char *End = getTok().getLoc().getPointer();
637 return StringRef(Start, End - Start);
640 /// ParseParenExpr - Parse a paren expression and return it.
641 /// NOTE: This assumes the leading '(' has already been consumed.
643 /// parenexpr ::= expr)
645 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
646 if (ParseExpression(Res)) return true;
647 if (Lexer.isNot(AsmToken::RParen))
648 return TokError("expected ')' in parentheses expression");
649 EndLoc = Lexer.getLoc();
654 /// ParseBracketExpr - Parse a bracket expression and return it.
655 /// NOTE: This assumes the leading '[' has already been consumed.
657 /// bracketexpr ::= expr]
659 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
660 if (ParseExpression(Res)) return true;
661 if (Lexer.isNot(AsmToken::RBrac))
662 return TokError("expected ']' in brackets expression");
663 EndLoc = Lexer.getLoc();
668 /// ParsePrimaryExpr - Parse a primary expression and return it.
669 /// primaryexpr ::= (parenexpr
670 /// primaryexpr ::= symbol
671 /// primaryexpr ::= number
672 /// primaryexpr ::= '.'
673 /// primaryexpr ::= ~,+,- primaryexpr
674 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
675 switch (Lexer.getKind()) {
677 return TokError("unknown token in expression");
678 // If we have an error assume that we've already handled it.
679 case AsmToken::Error:
681 case AsmToken::Exclaim:
682 Lex(); // Eat the operator.
683 if (ParsePrimaryExpr(Res, EndLoc))
685 Res = MCUnaryExpr::CreateLNot(Res, getContext());
687 case AsmToken::Dollar:
688 case AsmToken::String:
689 case AsmToken::Identifier: {
690 EndLoc = Lexer.getLoc();
692 StringRef Identifier;
693 if (ParseIdentifier(Identifier))
696 // This is a symbol reference.
697 std::pair<StringRef, StringRef> Split = Identifier.split('@');
698 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
700 // Lookup the symbol variant if used.
701 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
702 if (Split.first.size() != Identifier.size()) {
703 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
704 if (Variant == MCSymbolRefExpr::VK_Invalid) {
705 Variant = MCSymbolRefExpr::VK_None;
706 return TokError("invalid variant '" + Split.second + "'");
710 // If this is an absolute variable reference, substitute it now to preserve
711 // semantics in the face of reassignment.
712 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
714 return Error(EndLoc, "unexpected modifier on variable reference");
716 Res = Sym->getVariableValue();
720 // Otherwise create a symbol ref.
721 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
724 case AsmToken::Integer: {
725 SMLoc Loc = getTok().getLoc();
726 int64_t IntVal = getTok().getIntVal();
727 Res = MCConstantExpr::Create(IntVal, getContext());
728 EndLoc = Lexer.getLoc();
730 // Look for 'b' or 'f' following an Integer as a directional label
731 if (Lexer.getKind() == AsmToken::Identifier) {
732 StringRef IDVal = getTok().getString();
733 if (IDVal == "f" || IDVal == "b"){
734 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
735 IDVal == "f" ? 1 : 0);
736 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
738 if (IDVal == "b" && Sym->isUndefined())
739 return Error(Loc, "invalid reference to undefined symbol");
740 EndLoc = Lexer.getLoc();
741 Lex(); // Eat identifier.
746 case AsmToken::Real: {
747 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
748 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
749 Res = MCConstantExpr::Create(IntVal, getContext());
753 case AsmToken::Dot: {
754 // This is a '.' reference, which references the current PC. Emit a
755 // temporary label to the streamer and refer to it.
756 MCSymbol *Sym = Ctx.CreateTempSymbol();
758 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
759 EndLoc = Lexer.getLoc();
760 Lex(); // Eat identifier.
763 case AsmToken::LParen:
764 Lex(); // Eat the '('.
765 return ParseParenExpr(Res, EndLoc);
766 case AsmToken::LBrac:
767 if (!PlatformParser->HasBracketExpressions())
768 return TokError("brackets expression not supported on this target");
769 Lex(); // Eat the '['.
770 return ParseBracketExpr(Res, EndLoc);
771 case AsmToken::Minus:
772 Lex(); // Eat the operator.
773 if (ParsePrimaryExpr(Res, EndLoc))
775 Res = MCUnaryExpr::CreateMinus(Res, getContext());
778 Lex(); // Eat the operator.
779 if (ParsePrimaryExpr(Res, EndLoc))
781 Res = MCUnaryExpr::CreatePlus(Res, getContext());
783 case AsmToken::Tilde:
784 Lex(); // Eat the operator.
785 if (ParsePrimaryExpr(Res, EndLoc))
787 Res = MCUnaryExpr::CreateNot(Res, getContext());
792 bool AsmParser::ParseExpression(const MCExpr *&Res) {
794 return ParseExpression(Res, EndLoc);
798 AsmParser::ApplyModifierToExpr(const MCExpr *E,
799 MCSymbolRefExpr::VariantKind Variant) {
800 // Recurse over the given expression, rebuilding it to apply the given variant
801 // if there is exactly one symbol.
802 switch (E->getKind()) {
804 case MCExpr::Constant:
807 case MCExpr::SymbolRef: {
808 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
810 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
811 TokError("invalid variant on expression '" +
812 getTok().getIdentifier() + "' (already modified)");
816 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
819 case MCExpr::Unary: {
820 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
821 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
824 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
827 case MCExpr::Binary: {
828 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
829 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
830 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
835 if (!LHS) LHS = BE->getLHS();
836 if (!RHS) RHS = BE->getRHS();
838 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
842 llvm_unreachable("Invalid expression kind!");
845 /// ParseExpression - Parse an expression and return it.
847 /// expr ::= expr &&,|| expr -> lowest.
848 /// expr ::= expr |,^,&,! expr
849 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
850 /// expr ::= expr <<,>> expr
851 /// expr ::= expr +,- expr
852 /// expr ::= expr *,/,% expr -> highest.
853 /// expr ::= primaryexpr
855 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
856 // Parse the expression.
858 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
861 // As a special case, we support 'a op b @ modifier' by rewriting the
862 // expression to include the modifier. This is inefficient, but in general we
863 // expect users to use 'a@modifier op b'.
864 if (Lexer.getKind() == AsmToken::At) {
867 if (Lexer.isNot(AsmToken::Identifier))
868 return TokError("unexpected symbol modifier following '@'");
870 MCSymbolRefExpr::VariantKind Variant =
871 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
872 if (Variant == MCSymbolRefExpr::VK_Invalid)
873 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
875 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
877 return TokError("invalid modifier '" + getTok().getIdentifier() +
878 "' (no symbols present)");
885 // Try to constant fold it up front, if possible.
887 if (Res->EvaluateAsAbsolute(Value))
888 Res = MCConstantExpr::Create(Value, getContext());
893 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
895 return ParseParenExpr(Res, EndLoc) ||
896 ParseBinOpRHS(1, Res, EndLoc);
899 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
902 SMLoc StartLoc = Lexer.getLoc();
903 if (ParseExpression(Expr))
906 if (!Expr->EvaluateAsAbsolute(Res))
907 return Error(StartLoc, "expected absolute expression");
912 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
913 MCBinaryExpr::Opcode &Kind) {
916 return 0; // not a binop.
918 // Lowest Precedence: &&, ||
919 case AsmToken::AmpAmp:
920 Kind = MCBinaryExpr::LAnd;
922 case AsmToken::PipePipe:
923 Kind = MCBinaryExpr::LOr;
927 // Low Precedence: |, &, ^
929 // FIXME: gas seems to support '!' as an infix operator?
931 Kind = MCBinaryExpr::Or;
933 case AsmToken::Caret:
934 Kind = MCBinaryExpr::Xor;
937 Kind = MCBinaryExpr::And;
940 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
941 case AsmToken::EqualEqual:
942 Kind = MCBinaryExpr::EQ;
944 case AsmToken::ExclaimEqual:
945 case AsmToken::LessGreater:
946 Kind = MCBinaryExpr::NE;
949 Kind = MCBinaryExpr::LT;
951 case AsmToken::LessEqual:
952 Kind = MCBinaryExpr::LTE;
954 case AsmToken::Greater:
955 Kind = MCBinaryExpr::GT;
957 case AsmToken::GreaterEqual:
958 Kind = MCBinaryExpr::GTE;
961 // Intermediate Precedence: <<, >>
962 case AsmToken::LessLess:
963 Kind = MCBinaryExpr::Shl;
965 case AsmToken::GreaterGreater:
966 Kind = MCBinaryExpr::Shr;
969 // High Intermediate Precedence: +, -
971 Kind = MCBinaryExpr::Add;
973 case AsmToken::Minus:
974 Kind = MCBinaryExpr::Sub;
977 // Highest Precedence: *, /, %
979 Kind = MCBinaryExpr::Mul;
981 case AsmToken::Slash:
982 Kind = MCBinaryExpr::Div;
984 case AsmToken::Percent:
985 Kind = MCBinaryExpr::Mod;
991 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
992 /// Res contains the LHS of the expression on input.
993 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
996 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
997 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
999 // If the next token is lower precedence than we are allowed to eat, return
1000 // successfully with what we ate already.
1001 if (TokPrec < Precedence)
1006 // Eat the next primary expression.
1008 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1010 // If BinOp binds less tightly with RHS than the operator after RHS, let
1011 // the pending operator take RHS as its LHS.
1012 MCBinaryExpr::Opcode Dummy;
1013 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1014 if (TokPrec < NextTokPrec) {
1015 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1018 // Merge LHS and RHS according to operator.
1019 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1027 /// ::= EndOfStatement
1028 /// ::= Label* Directive ...Operands... EndOfStatement
1029 /// ::= Label* Identifier OperandList* EndOfStatement
1030 bool AsmParser::ParseStatement() {
1031 if (Lexer.is(AsmToken::EndOfStatement)) {
1037 // Statements always start with an identifier or are a full line comment.
1038 AsmToken ID = getTok();
1039 SMLoc IDLoc = ID.getLoc();
1041 int64_t LocalLabelVal = -1;
1042 // A full line comment is a '#' as the first token.
1043 if (Lexer.is(AsmToken::Hash))
1044 return ParseCppHashLineFilenameComment(IDLoc);
1046 // Allow an integer followed by a ':' as a directional local label.
1047 if (Lexer.is(AsmToken::Integer)) {
1048 LocalLabelVal = getTok().getIntVal();
1049 if (LocalLabelVal < 0) {
1050 if (!TheCondState.Ignore)
1051 return TokError("unexpected token at start of statement");
1055 IDVal = getTok().getString();
1056 Lex(); // Consume the integer token to be used as an identifier token.
1057 if (Lexer.getKind() != AsmToken::Colon) {
1058 if (!TheCondState.Ignore)
1059 return TokError("unexpected token at start of statement");
1063 } else if (Lexer.is(AsmToken::Dot)) {
1064 // Treat '.' as a valid identifier in this context.
1068 } else if (ParseIdentifier(IDVal)) {
1069 if (!TheCondState.Ignore)
1070 return TokError("unexpected token at start of statement");
1075 // Handle conditional assembly here before checking for skipping. We
1076 // have to do this so that .endif isn't skipped in a ".if 0" block for
1079 return ParseDirectiveIf(IDLoc);
1080 if (IDVal == ".ifb")
1081 return ParseDirectiveIfb(IDLoc, true);
1082 if (IDVal == ".ifnb")
1083 return ParseDirectiveIfb(IDLoc, false);
1084 if (IDVal == ".ifc")
1085 return ParseDirectiveIfc(IDLoc, true);
1086 if (IDVal == ".ifnc")
1087 return ParseDirectiveIfc(IDLoc, false);
1088 if (IDVal == ".ifdef")
1089 return ParseDirectiveIfdef(IDLoc, true);
1090 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1091 return ParseDirectiveIfdef(IDLoc, false);
1092 if (IDVal == ".elseif")
1093 return ParseDirectiveElseIf(IDLoc);
1094 if (IDVal == ".else")
1095 return ParseDirectiveElse(IDLoc);
1096 if (IDVal == ".endif")
1097 return ParseDirectiveEndIf(IDLoc);
1099 // If we are in a ".if 0" block, ignore this statement.
1100 if (TheCondState.Ignore) {
1101 EatToEndOfStatement();
1105 // FIXME: Recurse on local labels?
1107 // See what kind of statement we have.
1108 switch (Lexer.getKind()) {
1109 case AsmToken::Colon: {
1110 CheckForValidSection();
1112 // identifier ':' -> Label.
1115 // Diagnose attempt to use '.' as a label.
1117 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1119 // Diagnose attempt to use a variable as a label.
1121 // FIXME: Diagnostics. Note the location of the definition as a label.
1122 // FIXME: This doesn't diagnose assignment to a symbol which has been
1123 // implicitly marked as external.
1125 if (LocalLabelVal == -1)
1126 Sym = getContext().GetOrCreateSymbol(IDVal);
1128 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1129 if (!Sym->isUndefined() || Sym->isVariable())
1130 return Error(IDLoc, "invalid symbol redefinition");
1135 // If we are generating dwarf for assembly source files then gather the
1136 // info to make a dwarf label entry for this label if needed.
1137 if (getContext().getGenDwarfForAssembly())
1138 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1141 // Consume any end of statement token, if present, to avoid spurious
1142 // AddBlankLine calls().
1143 if (Lexer.is(AsmToken::EndOfStatement)) {
1145 if (Lexer.is(AsmToken::Eof))
1149 return ParseStatement();
1152 case AsmToken::Equal:
1153 // identifier '=' ... -> assignment statement
1156 return ParseAssignment(IDVal, true);
1158 default: // Normal instruction or directive.
1162 // If macros are enabled, check to see if this is a macro instantiation.
1164 if (const Macro *M = MacroMap.lookup(IDVal))
1165 return HandleMacroEntry(IDVal, IDLoc, M);
1167 // Otherwise, we have a normal instruction or directive.
1168 if (IDVal[0] == '.' && IDVal != ".") {
1169 // Assembler features
1170 if (IDVal == ".set" || IDVal == ".equ")
1171 return ParseDirectiveSet(IDVal, true);
1172 if (IDVal == ".equiv")
1173 return ParseDirectiveSet(IDVal, false);
1177 if (IDVal == ".ascii")
1178 return ParseDirectiveAscii(IDVal, false);
1179 if (IDVal == ".asciz" || IDVal == ".string")
1180 return ParseDirectiveAscii(IDVal, true);
1182 if (IDVal == ".byte")
1183 return ParseDirectiveValue(1);
1184 if (IDVal == ".short")
1185 return ParseDirectiveValue(2);
1186 if (IDVal == ".value")
1187 return ParseDirectiveValue(2);
1188 if (IDVal == ".2byte")
1189 return ParseDirectiveValue(2);
1190 if (IDVal == ".long")
1191 return ParseDirectiveValue(4);
1192 if (IDVal == ".int")
1193 return ParseDirectiveValue(4);
1194 if (IDVal == ".4byte")
1195 return ParseDirectiveValue(4);
1196 if (IDVal == ".quad")
1197 return ParseDirectiveValue(8);
1198 if (IDVal == ".8byte")
1199 return ParseDirectiveValue(8);
1200 if (IDVal == ".single" || IDVal == ".float")
1201 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1202 if (IDVal == ".double")
1203 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1205 if (IDVal == ".align") {
1206 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1207 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1209 if (IDVal == ".align32") {
1210 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1211 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1213 if (IDVal == ".balign")
1214 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1215 if (IDVal == ".balignw")
1216 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1217 if (IDVal == ".balignl")
1218 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1219 if (IDVal == ".p2align")
1220 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1221 if (IDVal == ".p2alignw")
1222 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1223 if (IDVal == ".p2alignl")
1224 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1226 if (IDVal == ".org")
1227 return ParseDirectiveOrg();
1229 if (IDVal == ".fill")
1230 return ParseDirectiveFill();
1231 if (IDVal == ".space" || IDVal == ".skip")
1232 return ParseDirectiveSpace();
1233 if (IDVal == ".zero")
1234 return ParseDirectiveZero();
1236 // Symbol attribute directives
1238 if (IDVal == ".extern") {
1239 EatToEndOfStatement(); // .extern is the default, ignore it.
1242 if (IDVal == ".globl" || IDVal == ".global")
1243 return ParseDirectiveSymbolAttribute(MCSA_Global);
1244 if (IDVal == ".indirect_symbol")
1245 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1246 if (IDVal == ".lazy_reference")
1247 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1248 if (IDVal == ".no_dead_strip")
1249 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1250 if (IDVal == ".symbol_resolver")
1251 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1252 if (IDVal == ".private_extern")
1253 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1254 if (IDVal == ".reference")
1255 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1256 if (IDVal == ".weak_definition")
1257 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1258 if (IDVal == ".weak_reference")
1259 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1260 if (IDVal == ".weak_def_can_be_hidden")
1261 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1263 if (IDVal == ".comm" || IDVal == ".common")
1264 return ParseDirectiveComm(/*IsLocal=*/false);
1265 if (IDVal == ".lcomm")
1266 return ParseDirectiveComm(/*IsLocal=*/true);
1268 if (IDVal == ".abort")
1269 return ParseDirectiveAbort();
1270 if (IDVal == ".include")
1271 return ParseDirectiveInclude();
1272 if (IDVal == ".incbin")
1273 return ParseDirectiveIncbin();
1275 if (IDVal == ".code16" || IDVal == ".code16gcc")
1276 return TokError(Twine(IDVal) + " not supported yet");
1278 // Macro-like directives
1279 if (IDVal == ".rept")
1280 return ParseDirectiveRept(IDLoc);
1281 if (IDVal == ".irp")
1282 return ParseDirectiveIrp(IDLoc);
1283 if (IDVal == ".endr")
1284 return ParseDirectiveEndr(IDLoc);
1286 // Look up the handler in the handler table.
1287 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1288 DirectiveMap.lookup(IDVal);
1290 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1292 // Target hook for parsing target specific directives.
1293 if (!getTargetParser().ParseDirective(ID))
1296 return Error(IDLoc, "unknown directive");
1299 CheckForValidSection();
1301 // Canonicalize the opcode to lower case.
1302 SmallString<128> Opcode;
1303 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1304 Opcode.push_back(tolower(IDVal[i]));
1306 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1307 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1310 // Dump the parsed representation, if requested.
1311 if (getShowParsedOperands()) {
1312 SmallString<256> Str;
1313 raw_svector_ostream OS(Str);
1314 OS << "parsed instruction: [";
1315 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1318 ParsedOperands[i]->print(OS);
1322 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1325 // If we are generating dwarf for assembly source files and the current
1326 // section is the initial text section then generate a .loc directive for
1328 if (!HadError && getContext().getGenDwarfForAssembly() &&
1329 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1330 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1331 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1332 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1333 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1337 // If parsing succeeded, match the instruction.
1339 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1342 // Free any parsed operands.
1343 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1344 delete ParsedOperands[i];
1346 // Don't skip the rest of the line, the instruction parser is responsible for
1351 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1352 /// since they may not be able to be tokenized to get to the end of line token.
1353 void AsmParser::EatToEndOfLine() {
1354 if (!Lexer.is(AsmToken::EndOfStatement))
1355 Lexer.LexUntilEndOfLine();
1360 /// ParseCppHashLineFilenameComment as this:
1361 /// ::= # number "filename"
1362 /// or just as a full line comment if it doesn't have a number and a string.
1363 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1364 Lex(); // Eat the hash token.
1366 if (getLexer().isNot(AsmToken::Integer)) {
1367 // Consume the line since in cases it is not a well-formed line directive,
1368 // as if were simply a full line comment.
1373 int64_t LineNumber = getTok().getIntVal();
1376 if (getLexer().isNot(AsmToken::String)) {
1381 StringRef Filename = getTok().getString();
1382 // Get rid of the enclosing quotes.
1383 Filename = Filename.substr(1, Filename.size()-2);
1385 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1387 CppHashFilename = Filename;
1388 CppHashLineNumber = LineNumber;
1390 // Ignore any trailing characters, they're just comment.
1395 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1396 /// for the Filename and LineNo if any in the diagnostic.
1397 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1398 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1399 raw_ostream &OS = errs();
1401 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1402 const SMLoc &DiagLoc = Diag.getLoc();
1403 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1404 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1406 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1407 // before printing the message.
1408 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1409 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1410 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1411 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1414 // If we have not parsed a cpp hash line filename comment or the source
1415 // manager changed or buffer changed (like in a nested include) then just
1416 // print the normal diagnostic using its Filename and LineNo.
1417 if (!Parser->CppHashLineNumber ||
1418 &DiagSrcMgr != &Parser->SrcMgr ||
1419 DiagBuf != CppHashBuf) {
1420 if (Parser->SavedDiagHandler)
1421 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1427 // Use the CppHashFilename and calculate a line number based on the
1428 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1430 const std::string Filename = Parser->CppHashFilename;
1432 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1433 int CppHashLocLineNo =
1434 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1435 int LineNo = Parser->CppHashLineNumber - 1 +
1436 (DiagLocLineNo - CppHashLocLineNo);
1438 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1439 Filename, LineNo, Diag.getColumnNo(),
1440 Diag.getKind(), Diag.getMessage(),
1441 Diag.getLineContents(), Diag.getRanges());
1443 if (Parser->SavedDiagHandler)
1444 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1446 NewDiag.print(0, OS);
1449 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1450 const std::vector<StringRef> &Parameters,
1451 const std::vector<MacroArgument> &A,
1453 unsigned NParameters = Parameters.size();
1454 if (NParameters != 0 && NParameters != A.size())
1455 return Error(L, "Wrong number of arguments");
1457 while (!Body.empty()) {
1458 // Scan for the next substitution.
1459 std::size_t End = Body.size(), Pos = 0;
1460 for (; Pos != End; ++Pos) {
1461 // Check for a substitution or escape.
1463 // This macro has no parameters, look for $0, $1, etc.
1464 if (Body[Pos] != '$' || Pos + 1 == End)
1467 char Next = Body[Pos + 1];
1468 if (Next == '$' || Next == 'n' || isdigit(Next))
1471 // This macro has parameters, look for \foo, \bar, etc.
1472 if (Body[Pos] == '\\' && Pos + 1 != End)
1478 OS << Body.slice(0, Pos);
1480 // Check if we reached the end.
1485 switch (Body[Pos+1]) {
1491 // $n => number of arguments
1496 // $[0-9] => argument
1498 // Missing arguments are ignored.
1499 unsigned Index = Body[Pos+1] - '0';
1500 if (Index >= A.size())
1503 // Otherwise substitute with the token values, with spaces eliminated.
1504 for (MacroArgument::const_iterator it = A[Index].begin(),
1505 ie = A[Index].end(); it != ie; ++it)
1506 OS << it->getString();
1512 unsigned I = Pos + 1;
1513 while (isalnum(Body[I]) && I + 1 != End)
1516 const char *Begin = Body.data() + Pos +1;
1517 StringRef Argument(Begin, I - (Pos +1));
1519 for (; Index < NParameters; ++Index)
1520 if (Parameters[Index] == Argument)
1523 // FIXME: We should error at the macro definition.
1524 if (Index == NParameters)
1525 return Error(L, "Parameter not found");
1527 for (MacroArgument::const_iterator it = A[Index].begin(),
1528 ie = A[Index].end(); it != ie; ++it)
1529 OS << it->getString();
1531 Pos += 1 + Argument.size();
1533 // Update the scan point.
1534 Body = Body.substr(Pos);
1540 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1542 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1546 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1547 /// This is used for both default macro parameter values and the
1548 /// arguments in macro invocations
1549 bool AsmParser::ParseMacroArgument(MacroArgument &MA) {
1550 unsigned ParenLevel = 0;
1555 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1556 return TokError("unexpected token in macro instantiation");
1558 // HandleMacroEntry relies on not advancing the lexer here
1559 // to be able to fill in the remaining default parameter values
1560 if (Lexer.is(AsmToken::EndOfStatement))
1562 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1565 // Adjust the current parentheses level.
1566 if (Lexer.is(AsmToken::LParen))
1568 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1571 // Append the token to the current argument list.
1572 MA.push_back(getTok());
1575 if (ParenLevel != 0)
1576 return TokError("unbalanced parenthesises in macro argument");
1580 // Parse the macro instantiation arguments.
1581 bool AsmParser::ParseMacroArguments(const Macro *M,
1582 std::vector<MacroArgument> &A) {
1583 const unsigned NParameters = M ? M->Parameters.size() : 0;
1585 // Parse two kinds of macro invocations:
1586 // - macros defined without any parameters accept an arbitrary number of them
1587 // - macros defined with parameters accept at most that many of them
1588 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1592 if (ParseMacroArgument(MA))
1597 if (Lexer.is(AsmToken::EndOfStatement))
1600 if (Lexer.is(AsmToken::Comma))
1603 return TokError("Too many arguments");
1606 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1608 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1609 // this, although we should protect against infinite loops.
1610 if (ActiveMacros.size() == 20)
1611 return TokError("macros cannot be nested more than 20 levels deep");
1613 std::vector<MacroArgument> MacroArguments;
1614 if (ParseMacroArguments(M, MacroArguments))
1617 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1618 // to hold the macro body with substitutions.
1619 SmallString<256> Buf;
1620 StringRef Body = M->Body;
1621 raw_svector_ostream OS(Buf);
1623 if (expandMacro(OS, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1626 // We include the .endmacro in the buffer as our queue to exit the macro
1628 OS << ".endmacro\n";
1630 MemoryBuffer *Instantiation =
1631 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1633 // Create the macro instantiation object and add to the current macro
1634 // instantiation stack.
1635 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1638 ActiveMacros.push_back(MI);
1640 // Jump to the macro instantiation and prime the lexer.
1641 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1642 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1648 void AsmParser::HandleMacroExit() {
1649 // Jump to the EndOfStatement we should return to, and consume it.
1650 JumpToLoc(ActiveMacros.back()->ExitLoc);
1653 // Pop the instantiation entry.
1654 delete ActiveMacros.back();
1655 ActiveMacros.pop_back();
1658 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1659 switch (Value->getKind()) {
1660 case MCExpr::Binary: {
1661 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1662 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1665 case MCExpr::Target:
1666 case MCExpr::Constant:
1668 case MCExpr::SymbolRef: {
1669 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1671 return IsUsedIn(Sym, S.getVariableValue());
1675 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1678 llvm_unreachable("Unknown expr kind!");
1681 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1682 // FIXME: Use better location, we should use proper tokens.
1683 SMLoc EqualLoc = Lexer.getLoc();
1685 const MCExpr *Value;
1686 if (ParseExpression(Value))
1689 // Note: we don't count b as used in "a = b". This is to allow
1693 if (Lexer.isNot(AsmToken::EndOfStatement))
1694 return TokError("unexpected token in assignment");
1696 // Error on assignment to '.'.
1698 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1699 "(use '.space' or '.org').)"));
1702 // Eat the end of statement marker.
1705 // Validate that the LHS is allowed to be a variable (either it has not been
1706 // used as a symbol, or it is an absolute symbol).
1707 MCSymbol *Sym = getContext().LookupSymbol(Name);
1709 // Diagnose assignment to a label.
1711 // FIXME: Diagnostics. Note the location of the definition as a label.
1712 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1713 if (IsUsedIn(Sym, Value))
1714 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1715 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1716 ; // Allow redefinitions of undefined symbols only used in directives.
1717 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1718 ; // Allow redefinitions of variables that haven't yet been used.
1719 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1720 return Error(EqualLoc, "redefinition of '" + Name + "'");
1721 else if (!Sym->isVariable())
1722 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1723 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1724 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1727 // Don't count these checks as uses.
1728 Sym->setUsed(false);
1730 Sym = getContext().GetOrCreateSymbol(Name);
1732 // FIXME: Handle '.'.
1734 // Do the assignment.
1735 Out.EmitAssignment(Sym, Value);
1740 /// ParseIdentifier:
1743 bool AsmParser::ParseIdentifier(StringRef &Res) {
1744 // The assembler has relaxed rules for accepting identifiers, in particular we
1745 // allow things like '.globl $foo', which would normally be separate
1746 // tokens. At this level, we have already lexed so we cannot (currently)
1747 // handle this as a context dependent token, instead we detect adjacent tokens
1748 // and return the combined identifier.
1749 if (Lexer.is(AsmToken::Dollar)) {
1750 SMLoc DollarLoc = getLexer().getLoc();
1752 // Consume the dollar sign, and check for a following identifier.
1754 if (Lexer.isNot(AsmToken::Identifier))
1757 // We have a '$' followed by an identifier, make sure they are adjacent.
1758 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1761 // Construct the joined identifier and consume the token.
1762 Res = StringRef(DollarLoc.getPointer(),
1763 getTok().getIdentifier().size() + 1);
1768 if (Lexer.isNot(AsmToken::Identifier) &&
1769 Lexer.isNot(AsmToken::String))
1772 Res = getTok().getIdentifier();
1774 Lex(); // Consume the identifier token.
1779 /// ParseDirectiveSet:
1780 /// ::= .equ identifier ',' expression
1781 /// ::= .equiv identifier ',' expression
1782 /// ::= .set identifier ',' expression
1783 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1786 if (ParseIdentifier(Name))
1787 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1789 if (getLexer().isNot(AsmToken::Comma))
1790 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1793 return ParseAssignment(Name, allow_redef);
1796 bool AsmParser::ParseEscapedString(std::string &Data) {
1797 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1800 StringRef Str = getTok().getStringContents();
1801 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1802 if (Str[i] != '\\') {
1807 // Recognize escaped characters. Note that this escape semantics currently
1808 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1811 return TokError("unexpected backslash at end of string");
1813 // Recognize octal sequences.
1814 if ((unsigned) (Str[i] - '0') <= 7) {
1815 // Consume up to three octal characters.
1816 unsigned Value = Str[i] - '0';
1818 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1820 Value = Value * 8 + (Str[i] - '0');
1822 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1824 Value = Value * 8 + (Str[i] - '0');
1829 return TokError("invalid octal escape sequence (out of range)");
1831 Data += (unsigned char) Value;
1835 // Otherwise recognize individual escapes.
1838 // Just reject invalid escape sequences for now.
1839 return TokError("invalid escape sequence (unrecognized character)");
1841 case 'b': Data += '\b'; break;
1842 case 'f': Data += '\f'; break;
1843 case 'n': Data += '\n'; break;
1844 case 'r': Data += '\r'; break;
1845 case 't': Data += '\t'; break;
1846 case '"': Data += '"'; break;
1847 case '\\': Data += '\\'; break;
1854 /// ParseDirectiveAscii:
1855 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1856 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1857 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1858 CheckForValidSection();
1861 if (getLexer().isNot(AsmToken::String))
1862 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1865 if (ParseEscapedString(Data))
1868 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1870 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1874 if (getLexer().is(AsmToken::EndOfStatement))
1877 if (getLexer().isNot(AsmToken::Comma))
1878 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1887 /// ParseDirectiveValue
1888 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1889 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1890 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1891 CheckForValidSection();
1894 const MCExpr *Value;
1895 SMLoc ExprLoc = getLexer().getLoc();
1896 if (ParseExpression(Value))
1899 // Special case constant expressions to match code generator.
1900 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1901 assert(Size <= 8 && "Invalid size");
1902 uint64_t IntValue = MCE->getValue();
1903 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1904 return Error(ExprLoc, "literal value out of range for directive");
1905 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1907 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1909 if (getLexer().is(AsmToken::EndOfStatement))
1912 // FIXME: Improve diagnostic.
1913 if (getLexer().isNot(AsmToken::Comma))
1914 return TokError("unexpected token in directive");
1923 /// ParseDirectiveRealValue
1924 /// ::= (.single | .double) [ expression (, expression)* ]
1925 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1926 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1927 CheckForValidSection();
1930 // We don't truly support arithmetic on floating point expressions, so we
1931 // have to manually parse unary prefixes.
1933 if (getLexer().is(AsmToken::Minus)) {
1936 } else if (getLexer().is(AsmToken::Plus))
1939 if (getLexer().isNot(AsmToken::Integer) &&
1940 getLexer().isNot(AsmToken::Real) &&
1941 getLexer().isNot(AsmToken::Identifier))
1942 return TokError("unexpected token in directive");
1944 // Convert to an APFloat.
1945 APFloat Value(Semantics);
1946 StringRef IDVal = getTok().getString();
1947 if (getLexer().is(AsmToken::Identifier)) {
1948 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1949 Value = APFloat::getInf(Semantics);
1950 else if (!IDVal.compare_lower("nan"))
1951 Value = APFloat::getNaN(Semantics, false, ~0);
1953 return TokError("invalid floating point literal");
1954 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1955 APFloat::opInvalidOp)
1956 return TokError("invalid floating point literal");
1960 // Consume the numeric token.
1963 // Emit the value as an integer.
1964 APInt AsInt = Value.bitcastToAPInt();
1965 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1966 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1968 if (getLexer().is(AsmToken::EndOfStatement))
1971 if (getLexer().isNot(AsmToken::Comma))
1972 return TokError("unexpected token in directive");
1981 /// ParseDirectiveSpace
1982 /// ::= .space expression [ , expression ]
1983 bool AsmParser::ParseDirectiveSpace() {
1984 CheckForValidSection();
1987 if (ParseAbsoluteExpression(NumBytes))
1990 int64_t FillExpr = 0;
1991 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1992 if (getLexer().isNot(AsmToken::Comma))
1993 return TokError("unexpected token in '.space' directive");
1996 if (ParseAbsoluteExpression(FillExpr))
1999 if (getLexer().isNot(AsmToken::EndOfStatement))
2000 return TokError("unexpected token in '.space' directive");
2006 return TokError("invalid number of bytes in '.space' directive");
2008 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2009 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2014 /// ParseDirectiveZero
2015 /// ::= .zero expression
2016 bool AsmParser::ParseDirectiveZero() {
2017 CheckForValidSection();
2020 if (ParseAbsoluteExpression(NumBytes))
2024 if (getLexer().is(AsmToken::Comma)) {
2026 if (ParseAbsoluteExpression(Val))
2030 if (getLexer().isNot(AsmToken::EndOfStatement))
2031 return TokError("unexpected token in '.zero' directive");
2035 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2040 /// ParseDirectiveFill
2041 /// ::= .fill expression , expression , expression
2042 bool AsmParser::ParseDirectiveFill() {
2043 CheckForValidSection();
2046 if (ParseAbsoluteExpression(NumValues))
2049 if (getLexer().isNot(AsmToken::Comma))
2050 return TokError("unexpected token in '.fill' directive");
2054 if (ParseAbsoluteExpression(FillSize))
2057 if (getLexer().isNot(AsmToken::Comma))
2058 return TokError("unexpected token in '.fill' directive");
2062 if (ParseAbsoluteExpression(FillExpr))
2065 if (getLexer().isNot(AsmToken::EndOfStatement))
2066 return TokError("unexpected token in '.fill' directive");
2070 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2071 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2073 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2074 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2079 /// ParseDirectiveOrg
2080 /// ::= .org expression [ , expression ]
2081 bool AsmParser::ParseDirectiveOrg() {
2082 CheckForValidSection();
2084 const MCExpr *Offset;
2085 SMLoc Loc = getTok().getLoc();
2086 if (ParseExpression(Offset))
2089 // Parse optional fill expression.
2090 int64_t FillExpr = 0;
2091 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2092 if (getLexer().isNot(AsmToken::Comma))
2093 return TokError("unexpected token in '.org' directive");
2096 if (ParseAbsoluteExpression(FillExpr))
2099 if (getLexer().isNot(AsmToken::EndOfStatement))
2100 return TokError("unexpected token in '.org' directive");
2105 // Only limited forms of relocatable expressions are accepted here, it
2106 // has to be relative to the current section. The streamer will return
2107 // 'true' if the expression wasn't evaluatable.
2108 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2109 return Error(Loc, "expected assembly-time absolute expression");
2114 /// ParseDirectiveAlign
2115 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2116 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2117 CheckForValidSection();
2119 SMLoc AlignmentLoc = getLexer().getLoc();
2121 if (ParseAbsoluteExpression(Alignment))
2125 bool HasFillExpr = false;
2126 int64_t FillExpr = 0;
2127 int64_t MaxBytesToFill = 0;
2128 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2129 if (getLexer().isNot(AsmToken::Comma))
2130 return TokError("unexpected token in directive");
2133 // The fill expression can be omitted while specifying a maximum number of
2134 // alignment bytes, e.g:
2136 if (getLexer().isNot(AsmToken::Comma)) {
2138 if (ParseAbsoluteExpression(FillExpr))
2142 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2143 if (getLexer().isNot(AsmToken::Comma))
2144 return TokError("unexpected token in directive");
2147 MaxBytesLoc = getLexer().getLoc();
2148 if (ParseAbsoluteExpression(MaxBytesToFill))
2151 if (getLexer().isNot(AsmToken::EndOfStatement))
2152 return TokError("unexpected token in directive");
2161 // Compute alignment in bytes.
2163 // FIXME: Diagnose overflow.
2164 if (Alignment >= 32) {
2165 Error(AlignmentLoc, "invalid alignment value");
2169 Alignment = 1ULL << Alignment;
2172 // Diagnose non-sensical max bytes to align.
2173 if (MaxBytesLoc.isValid()) {
2174 if (MaxBytesToFill < 1) {
2175 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2176 "many bytes, ignoring maximum bytes expression");
2180 if (MaxBytesToFill >= Alignment) {
2181 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2187 // Check whether we should use optimal code alignment for this .align
2189 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2190 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2191 ValueSize == 1 && UseCodeAlign) {
2192 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2194 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2195 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2202 /// ParseDirectiveSymbolAttribute
2203 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2204 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2205 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2208 SMLoc Loc = getTok().getLoc();
2210 if (ParseIdentifier(Name))
2211 return Error(Loc, "expected identifier in directive");
2213 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2215 // Assembler local symbols don't make any sense here. Complain loudly.
2216 if (Sym->isTemporary())
2217 return Error(Loc, "non-local symbol required in directive");
2219 getStreamer().EmitSymbolAttribute(Sym, Attr);
2221 if (getLexer().is(AsmToken::EndOfStatement))
2224 if (getLexer().isNot(AsmToken::Comma))
2225 return TokError("unexpected token in directive");
2234 /// ParseDirectiveComm
2235 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2236 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2237 CheckForValidSection();
2239 SMLoc IDLoc = getLexer().getLoc();
2241 if (ParseIdentifier(Name))
2242 return TokError("expected identifier in directive");
2244 // Handle the identifier as the key symbol.
2245 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2247 if (getLexer().isNot(AsmToken::Comma))
2248 return TokError("unexpected token in directive");
2252 SMLoc SizeLoc = getLexer().getLoc();
2253 if (ParseAbsoluteExpression(Size))
2256 int64_t Pow2Alignment = 0;
2257 SMLoc Pow2AlignmentLoc;
2258 if (getLexer().is(AsmToken::Comma)) {
2260 Pow2AlignmentLoc = getLexer().getLoc();
2261 if (ParseAbsoluteExpression(Pow2Alignment))
2264 // If this target takes alignments in bytes (not log) validate and convert.
2265 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2266 if (!isPowerOf2_64(Pow2Alignment))
2267 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2268 Pow2Alignment = Log2_64(Pow2Alignment);
2272 if (getLexer().isNot(AsmToken::EndOfStatement))
2273 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2277 // NOTE: a size of zero for a .comm should create a undefined symbol
2278 // but a size of .lcomm creates a bss symbol of size zero.
2280 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2281 "be less than zero");
2283 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2284 // may internally end up wanting an alignment in bytes.
2285 // FIXME: Diagnose overflow.
2286 if (Pow2Alignment < 0)
2287 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2288 "alignment, can't be less than zero");
2290 if (!Sym->isUndefined())
2291 return Error(IDLoc, "invalid symbol redefinition");
2293 // '.lcomm' is equivalent to '.zerofill'.
2294 // Create the Symbol as a common or local common with Size and Pow2Alignment
2296 getStreamer().EmitZerofill(Ctx.getMachOSection(
2297 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2298 0, SectionKind::getBSS()),
2299 Sym, Size, 1 << Pow2Alignment);
2303 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2307 /// ParseDirectiveAbort
2308 /// ::= .abort [... message ...]
2309 bool AsmParser::ParseDirectiveAbort() {
2310 // FIXME: Use loc from directive.
2311 SMLoc Loc = getLexer().getLoc();
2313 StringRef Str = ParseStringToEndOfStatement();
2314 if (getLexer().isNot(AsmToken::EndOfStatement))
2315 return TokError("unexpected token in '.abort' directive");
2320 Error(Loc, ".abort detected. Assembly stopping.");
2322 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2323 // FIXME: Actually abort assembly here.
2328 /// ParseDirectiveInclude
2329 /// ::= .include "filename"
2330 bool AsmParser::ParseDirectiveInclude() {
2331 if (getLexer().isNot(AsmToken::String))
2332 return TokError("expected string in '.include' directive");
2334 std::string Filename = getTok().getString();
2335 SMLoc IncludeLoc = getLexer().getLoc();
2338 if (getLexer().isNot(AsmToken::EndOfStatement))
2339 return TokError("unexpected token in '.include' directive");
2341 // Strip the quotes.
2342 Filename = Filename.substr(1, Filename.size()-2);
2344 // Attempt to switch the lexer to the included file before consuming the end
2345 // of statement to avoid losing it when we switch.
2346 if (EnterIncludeFile(Filename)) {
2347 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2354 /// ParseDirectiveIncbin
2355 /// ::= .incbin "filename"
2356 bool AsmParser::ParseDirectiveIncbin() {
2357 if (getLexer().isNot(AsmToken::String))
2358 return TokError("expected string in '.incbin' directive");
2360 std::string Filename = getTok().getString();
2361 SMLoc IncbinLoc = getLexer().getLoc();
2364 if (getLexer().isNot(AsmToken::EndOfStatement))
2365 return TokError("unexpected token in '.incbin' directive");
2367 // Strip the quotes.
2368 Filename = Filename.substr(1, Filename.size()-2);
2370 // Attempt to process the included file.
2371 if (ProcessIncbinFile(Filename)) {
2372 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2379 /// ParseDirectiveIf
2380 /// ::= .if expression
2381 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2382 TheCondStack.push_back(TheCondState);
2383 TheCondState.TheCond = AsmCond::IfCond;
2384 if (TheCondState.Ignore) {
2385 EatToEndOfStatement();
2388 if (ParseAbsoluteExpression(ExprValue))
2391 if (getLexer().isNot(AsmToken::EndOfStatement))
2392 return TokError("unexpected token in '.if' directive");
2396 TheCondState.CondMet = ExprValue;
2397 TheCondState.Ignore = !TheCondState.CondMet;
2403 /// ParseDirectiveIfb
2405 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2406 TheCondStack.push_back(TheCondState);
2407 TheCondState.TheCond = AsmCond::IfCond;
2409 if (TheCondState.Ignore) {
2410 EatToEndOfStatement();
2412 StringRef Str = ParseStringToEndOfStatement();
2414 if (getLexer().isNot(AsmToken::EndOfStatement))
2415 return TokError("unexpected token in '.ifb' directive");
2419 TheCondState.CondMet = ExpectBlank == Str.empty();
2420 TheCondState.Ignore = !TheCondState.CondMet;
2426 /// ParseDirectiveIfc
2427 /// ::= .ifc string1, string2
2428 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2429 TheCondStack.push_back(TheCondState);
2430 TheCondState.TheCond = AsmCond::IfCond;
2432 if (TheCondState.Ignore) {
2433 EatToEndOfStatement();
2435 StringRef Str1 = ParseStringToComma();
2437 if (getLexer().isNot(AsmToken::Comma))
2438 return TokError("unexpected token in '.ifc' directive");
2442 StringRef Str2 = ParseStringToEndOfStatement();
2444 if (getLexer().isNot(AsmToken::EndOfStatement))
2445 return TokError("unexpected token in '.ifc' directive");
2449 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2450 TheCondState.Ignore = !TheCondState.CondMet;
2456 /// ParseDirectiveIfdef
2457 /// ::= .ifdef symbol
2458 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2460 TheCondStack.push_back(TheCondState);
2461 TheCondState.TheCond = AsmCond::IfCond;
2463 if (TheCondState.Ignore) {
2464 EatToEndOfStatement();
2466 if (ParseIdentifier(Name))
2467 return TokError("expected identifier after '.ifdef'");
2471 MCSymbol *Sym = getContext().LookupSymbol(Name);
2474 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2476 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2477 TheCondState.Ignore = !TheCondState.CondMet;
2483 /// ParseDirectiveElseIf
2484 /// ::= .elseif expression
2485 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2486 if (TheCondState.TheCond != AsmCond::IfCond &&
2487 TheCondState.TheCond != AsmCond::ElseIfCond)
2488 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2490 TheCondState.TheCond = AsmCond::ElseIfCond;
2492 bool LastIgnoreState = false;
2493 if (!TheCondStack.empty())
2494 LastIgnoreState = TheCondStack.back().Ignore;
2495 if (LastIgnoreState || TheCondState.CondMet) {
2496 TheCondState.Ignore = true;
2497 EatToEndOfStatement();
2501 if (ParseAbsoluteExpression(ExprValue))
2504 if (getLexer().isNot(AsmToken::EndOfStatement))
2505 return TokError("unexpected token in '.elseif' directive");
2508 TheCondState.CondMet = ExprValue;
2509 TheCondState.Ignore = !TheCondState.CondMet;
2515 /// ParseDirectiveElse
2517 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2518 if (getLexer().isNot(AsmToken::EndOfStatement))
2519 return TokError("unexpected token in '.else' directive");
2523 if (TheCondState.TheCond != AsmCond::IfCond &&
2524 TheCondState.TheCond != AsmCond::ElseIfCond)
2525 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2527 TheCondState.TheCond = AsmCond::ElseCond;
2528 bool LastIgnoreState = false;
2529 if (!TheCondStack.empty())
2530 LastIgnoreState = TheCondStack.back().Ignore;
2531 if (LastIgnoreState || TheCondState.CondMet)
2532 TheCondState.Ignore = true;
2534 TheCondState.Ignore = false;
2539 /// ParseDirectiveEndIf
2541 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2542 if (getLexer().isNot(AsmToken::EndOfStatement))
2543 return TokError("unexpected token in '.endif' directive");
2547 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2548 TheCondStack.empty())
2549 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2551 if (!TheCondStack.empty()) {
2552 TheCondState = TheCondStack.back();
2553 TheCondStack.pop_back();
2559 /// ParseDirectiveFile
2560 /// ::= .file [number] filename
2561 /// ::= .file number directory filename
2562 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2563 // FIXME: I'm not sure what this is.
2564 int64_t FileNumber = -1;
2565 SMLoc FileNumberLoc = getLexer().getLoc();
2566 if (getLexer().is(AsmToken::Integer)) {
2567 FileNumber = getTok().getIntVal();
2571 return TokError("file number less than one");
2574 if (getLexer().isNot(AsmToken::String))
2575 return TokError("unexpected token in '.file' directive");
2577 // Usually the directory and filename together, otherwise just the directory.
2578 StringRef Path = getTok().getString();
2579 Path = Path.substr(1, Path.size()-2);
2582 StringRef Directory;
2584 if (getLexer().is(AsmToken::String)) {
2585 if (FileNumber == -1)
2586 return TokError("explicit path specified, but no file number");
2587 Filename = getTok().getString();
2588 Filename = Filename.substr(1, Filename.size()-2);
2595 if (getLexer().isNot(AsmToken::EndOfStatement))
2596 return TokError("unexpected token in '.file' directive");
2598 if (FileNumber == -1)
2599 getStreamer().EmitFileDirective(Filename);
2601 if (getContext().getGenDwarfForAssembly() == true)
2602 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2603 "used to generate dwarf debug info for assembly code");
2605 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2606 Error(FileNumberLoc, "file number already allocated");
2612 /// ParseDirectiveLine
2613 /// ::= .line [number]
2614 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2615 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2616 if (getLexer().isNot(AsmToken::Integer))
2617 return TokError("unexpected token in '.line' directive");
2619 int64_t LineNumber = getTok().getIntVal();
2623 // FIXME: Do something with the .line.
2626 if (getLexer().isNot(AsmToken::EndOfStatement))
2627 return TokError("unexpected token in '.line' directive");
2633 /// ParseDirectiveLoc
2634 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2635 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2636 /// The first number is a file number, must have been previously assigned with
2637 /// a .file directive, the second number is the line number and optionally the
2638 /// third number is a column position (zero if not specified). The remaining
2639 /// optional items are .loc sub-directives.
2640 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2642 if (getLexer().isNot(AsmToken::Integer))
2643 return TokError("unexpected token in '.loc' directive");
2644 int64_t FileNumber = getTok().getIntVal();
2646 return TokError("file number less than one in '.loc' directive");
2647 if (!getContext().isValidDwarfFileNumber(FileNumber))
2648 return TokError("unassigned file number in '.loc' directive");
2651 int64_t LineNumber = 0;
2652 if (getLexer().is(AsmToken::Integer)) {
2653 LineNumber = getTok().getIntVal();
2655 return TokError("line number less than one in '.loc' directive");
2659 int64_t ColumnPos = 0;
2660 if (getLexer().is(AsmToken::Integer)) {
2661 ColumnPos = getTok().getIntVal();
2663 return TokError("column position less than zero in '.loc' directive");
2667 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2669 int64_t Discriminator = 0;
2670 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2672 if (getLexer().is(AsmToken::EndOfStatement))
2676 SMLoc Loc = getTok().getLoc();
2677 if (getParser().ParseIdentifier(Name))
2678 return TokError("unexpected token in '.loc' directive");
2680 if (Name == "basic_block")
2681 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2682 else if (Name == "prologue_end")
2683 Flags |= DWARF2_FLAG_PROLOGUE_END;
2684 else if (Name == "epilogue_begin")
2685 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2686 else if (Name == "is_stmt") {
2687 SMLoc Loc = getTok().getLoc();
2688 const MCExpr *Value;
2689 if (getParser().ParseExpression(Value))
2691 // The expression must be the constant 0 or 1.
2692 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2693 int Value = MCE->getValue();
2695 Flags &= ~DWARF2_FLAG_IS_STMT;
2696 else if (Value == 1)
2697 Flags |= DWARF2_FLAG_IS_STMT;
2699 return Error(Loc, "is_stmt value not 0 or 1");
2702 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2705 else if (Name == "isa") {
2706 SMLoc Loc = getTok().getLoc();
2707 const MCExpr *Value;
2708 if (getParser().ParseExpression(Value))
2710 // The expression must be a constant greater or equal to 0.
2711 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2712 int Value = MCE->getValue();
2714 return Error(Loc, "isa number less than zero");
2718 return Error(Loc, "isa number not a constant value");
2721 else if (Name == "discriminator") {
2722 if (getParser().ParseAbsoluteExpression(Discriminator))
2726 return Error(Loc, "unknown sub-directive in '.loc' directive");
2729 if (getLexer().is(AsmToken::EndOfStatement))
2734 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2735 Isa, Discriminator, StringRef());
2740 /// ParseDirectiveStabs
2741 /// ::= .stabs string, number, number, number
2742 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2743 SMLoc DirectiveLoc) {
2744 return TokError("unsupported directive '" + Directive + "'");
2747 /// ParseDirectiveCFISections
2748 /// ::= .cfi_sections section [, section]
2749 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2750 SMLoc DirectiveLoc) {
2755 if (getParser().ParseIdentifier(Name))
2756 return TokError("Expected an identifier");
2758 if (Name == ".eh_frame")
2760 else if (Name == ".debug_frame")
2763 if (getLexer().is(AsmToken::Comma)) {
2766 if (getParser().ParseIdentifier(Name))
2767 return TokError("Expected an identifier");
2769 if (Name == ".eh_frame")
2771 else if (Name == ".debug_frame")
2775 getStreamer().EmitCFISections(EH, Debug);
2780 /// ParseDirectiveCFIStartProc
2781 /// ::= .cfi_startproc
2782 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2783 SMLoc DirectiveLoc) {
2784 getStreamer().EmitCFIStartProc();
2788 /// ParseDirectiveCFIEndProc
2789 /// ::= .cfi_endproc
2790 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2791 getStreamer().EmitCFIEndProc();
2795 /// ParseRegisterOrRegisterNumber - parse register name or number.
2796 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2797 SMLoc DirectiveLoc) {
2800 if (getLexer().isNot(AsmToken::Integer)) {
2801 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2804 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2806 return getParser().ParseAbsoluteExpression(Register);
2811 /// ParseDirectiveCFIDefCfa
2812 /// ::= .cfi_def_cfa register, offset
2813 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2814 SMLoc DirectiveLoc) {
2815 int64_t Register = 0;
2816 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2819 if (getLexer().isNot(AsmToken::Comma))
2820 return TokError("unexpected token in directive");
2824 if (getParser().ParseAbsoluteExpression(Offset))
2827 getStreamer().EmitCFIDefCfa(Register, Offset);
2831 /// ParseDirectiveCFIDefCfaOffset
2832 /// ::= .cfi_def_cfa_offset offset
2833 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2834 SMLoc DirectiveLoc) {
2836 if (getParser().ParseAbsoluteExpression(Offset))
2839 getStreamer().EmitCFIDefCfaOffset(Offset);
2843 /// ParseDirectiveCFIAdjustCfaOffset
2844 /// ::= .cfi_adjust_cfa_offset adjustment
2845 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2846 SMLoc DirectiveLoc) {
2847 int64_t Adjustment = 0;
2848 if (getParser().ParseAbsoluteExpression(Adjustment))
2851 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2855 /// ParseDirectiveCFIDefCfaRegister
2856 /// ::= .cfi_def_cfa_register register
2857 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2858 SMLoc DirectiveLoc) {
2859 int64_t Register = 0;
2860 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2863 getStreamer().EmitCFIDefCfaRegister(Register);
2867 /// ParseDirectiveCFIOffset
2868 /// ::= .cfi_offset register, offset
2869 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2870 int64_t Register = 0;
2873 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2876 if (getLexer().isNot(AsmToken::Comma))
2877 return TokError("unexpected token in directive");
2880 if (getParser().ParseAbsoluteExpression(Offset))
2883 getStreamer().EmitCFIOffset(Register, Offset);
2887 /// ParseDirectiveCFIRelOffset
2888 /// ::= .cfi_rel_offset register, offset
2889 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2890 SMLoc DirectiveLoc) {
2891 int64_t Register = 0;
2893 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2896 if (getLexer().isNot(AsmToken::Comma))
2897 return TokError("unexpected token in directive");
2901 if (getParser().ParseAbsoluteExpression(Offset))
2904 getStreamer().EmitCFIRelOffset(Register, Offset);
2908 static bool isValidEncoding(int64_t Encoding) {
2909 if (Encoding & ~0xff)
2912 if (Encoding == dwarf::DW_EH_PE_omit)
2915 const unsigned Format = Encoding & 0xf;
2916 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2917 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2918 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2919 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2922 const unsigned Application = Encoding & 0x70;
2923 if (Application != dwarf::DW_EH_PE_absptr &&
2924 Application != dwarf::DW_EH_PE_pcrel)
2930 /// ParseDirectiveCFIPersonalityOrLsda
2931 /// ::= .cfi_personality encoding, [symbol_name]
2932 /// ::= .cfi_lsda encoding, [symbol_name]
2933 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2934 SMLoc DirectiveLoc) {
2935 int64_t Encoding = 0;
2936 if (getParser().ParseAbsoluteExpression(Encoding))
2938 if (Encoding == dwarf::DW_EH_PE_omit)
2941 if (!isValidEncoding(Encoding))
2942 return TokError("unsupported encoding.");
2944 if (getLexer().isNot(AsmToken::Comma))
2945 return TokError("unexpected token in directive");
2949 if (getParser().ParseIdentifier(Name))
2950 return TokError("expected identifier in directive");
2952 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2954 if (IDVal == ".cfi_personality")
2955 getStreamer().EmitCFIPersonality(Sym, Encoding);
2957 assert(IDVal == ".cfi_lsda");
2958 getStreamer().EmitCFILsda(Sym, Encoding);
2963 /// ParseDirectiveCFIRememberState
2964 /// ::= .cfi_remember_state
2965 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2966 SMLoc DirectiveLoc) {
2967 getStreamer().EmitCFIRememberState();
2971 /// ParseDirectiveCFIRestoreState
2972 /// ::= .cfi_remember_state
2973 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2974 SMLoc DirectiveLoc) {
2975 getStreamer().EmitCFIRestoreState();
2979 /// ParseDirectiveCFISameValue
2980 /// ::= .cfi_same_value register
2981 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2982 SMLoc DirectiveLoc) {
2983 int64_t Register = 0;
2985 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2988 getStreamer().EmitCFISameValue(Register);
2993 /// ParseDirectiveCFIRestore
2994 /// ::= .cfi_restore register
2995 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2996 SMLoc DirectiveLoc) {
2997 int64_t Register = 0;
2998 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3001 getStreamer().EmitCFIRestore(Register);
3006 /// ParseDirectiveCFIEscape
3007 /// ::= .cfi_escape expression[,...]
3008 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3009 SMLoc DirectiveLoc) {
3012 if (getParser().ParseAbsoluteExpression(CurrValue))
3015 Values.push_back((uint8_t)CurrValue);
3017 while (getLexer().is(AsmToken::Comma)) {
3020 if (getParser().ParseAbsoluteExpression(CurrValue))
3023 Values.push_back((uint8_t)CurrValue);
3026 getStreamer().EmitCFIEscape(Values);
3030 /// ParseDirectiveCFISignalFrame
3031 /// ::= .cfi_signal_frame
3032 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3033 SMLoc DirectiveLoc) {
3034 if (getLexer().isNot(AsmToken::EndOfStatement))
3035 return Error(getLexer().getLoc(),
3036 "unexpected token in '" + Directive + "' directive");
3038 getStreamer().EmitCFISignalFrame();
3043 /// ParseDirectiveMacrosOnOff
3046 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3047 SMLoc DirectiveLoc) {
3048 if (getLexer().isNot(AsmToken::EndOfStatement))
3049 return Error(getLexer().getLoc(),
3050 "unexpected token in '" + Directive + "' directive");
3052 getParser().MacrosEnabled = Directive == ".macros_on";
3057 /// ParseDirectiveMacro
3058 /// ::= .macro name [parameters]
3059 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3060 SMLoc DirectiveLoc) {
3062 if (getParser().ParseIdentifier(Name))
3063 return TokError("expected identifier in directive");
3065 std::vector<StringRef> Parameters;
3066 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3068 StringRef Parameter;
3069 if (getParser().ParseIdentifier(Parameter))
3070 return TokError("expected identifier in directive");
3071 Parameters.push_back(Parameter);
3073 if (getLexer().isNot(AsmToken::Comma))
3079 if (getLexer().isNot(AsmToken::EndOfStatement))
3080 return TokError("unexpected token in '.macro' directive");
3082 // Eat the end of statement.
3085 AsmToken EndToken, StartToken = getTok();
3087 // Lex the macro definition.
3089 // Check whether we have reached the end of the file.
3090 if (getLexer().is(AsmToken::Eof))
3091 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3093 // Otherwise, check whether we have reach the .endmacro.
3094 if (getLexer().is(AsmToken::Identifier) &&
3095 (getTok().getIdentifier() == ".endm" ||
3096 getTok().getIdentifier() == ".endmacro")) {
3097 EndToken = getTok();
3099 if (getLexer().isNot(AsmToken::EndOfStatement))
3100 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3105 // Otherwise, scan til the end of the statement.
3106 getParser().EatToEndOfStatement();
3109 if (getParser().MacroMap.lookup(Name)) {
3110 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3113 const char *BodyStart = StartToken.getLoc().getPointer();
3114 const char *BodyEnd = EndToken.getLoc().getPointer();
3115 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3116 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3120 /// ParseDirectiveEndMacro
3123 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3124 SMLoc DirectiveLoc) {
3125 if (getLexer().isNot(AsmToken::EndOfStatement))
3126 return TokError("unexpected token in '" + Directive + "' directive");
3128 // If we are inside a macro instantiation, terminate the current
3130 if (!getParser().ActiveMacros.empty()) {
3131 getParser().HandleMacroExit();
3135 // Otherwise, this .endmacro is a stray entry in the file; well formed
3136 // .endmacro directives are handled during the macro definition parsing.
3137 return TokError("unexpected '" + Directive + "' in file, "
3138 "no current macro definition");
3141 /// ParseDirectivePurgeMacro
3143 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3144 SMLoc DirectiveLoc) {
3146 if (getParser().ParseIdentifier(Name))
3147 return TokError("expected identifier in '.purgem' directive");
3149 if (getLexer().isNot(AsmToken::EndOfStatement))
3150 return TokError("unexpected token in '.purgem' directive");
3152 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3153 if (I == getParser().MacroMap.end())
3154 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3156 // Undefine the macro.
3157 delete I->getValue();
3158 getParser().MacroMap.erase(I);
3162 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3163 getParser().CheckForValidSection();
3165 const MCExpr *Value;
3167 if (getParser().ParseExpression(Value))
3170 if (getLexer().isNot(AsmToken::EndOfStatement))
3171 return TokError("unexpected token in directive");
3173 if (DirName[1] == 's')
3174 getStreamer().EmitSLEB128Value(Value);
3176 getStreamer().EmitULEB128Value(Value);
3181 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3182 AsmToken EndToken, StartToken = getTok();
3184 unsigned NestLevel = 0;
3186 // Check whether we have reached the end of the file.
3187 if (getLexer().is(AsmToken::Eof)) {
3188 Error(DirectiveLoc, "no matching '.endr' in definition");
3192 if (Lexer.is(AsmToken::Identifier) &&
3193 (getTok().getIdentifier() == ".rept")) {
3197 // Otherwise, check whether we have reached the .endr.
3198 if (Lexer.is(AsmToken::Identifier) &&
3199 getTok().getIdentifier() == ".endr") {
3200 if (NestLevel == 0) {
3201 EndToken = getTok();
3203 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3204 TokError("unexpected token in '.endr' directive");
3212 // Otherwise, scan till the end of the statement.
3213 EatToEndOfStatement();
3216 const char *BodyStart = StartToken.getLoc().getPointer();
3217 const char *BodyEnd = EndToken.getLoc().getPointer();
3218 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3220 // We Are Anonymous.
3222 std::vector<StringRef> Parameters;
3223 return new Macro(Name, Body, Parameters);
3226 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3227 raw_svector_ostream &OS) {
3230 MemoryBuffer *Instantiation =
3231 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3233 // Create the macro instantiation object and add to the current macro
3234 // instantiation stack.
3235 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3238 ActiveMacros.push_back(MI);
3240 // Jump to the macro instantiation and prime the lexer.
3241 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3242 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3246 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3248 if (ParseAbsoluteExpression(Count))
3249 return TokError("unexpected token in '.rept' directive");
3252 return TokError("Count is negative");
3254 if (Lexer.isNot(AsmToken::EndOfStatement))
3255 return TokError("unexpected token in '.rept' directive");
3257 // Eat the end of statement.
3260 // Lex the rept definition.
3261 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3265 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3266 // to hold the macro body with substitutions.
3267 SmallString<256> Buf;
3268 std::vector<StringRef> Parameters;
3269 const std::vector<MacroArgument> A;
3270 raw_svector_ostream OS(Buf);
3272 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3275 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3280 /// ParseDirectiveIrp
3281 /// ::= .irp symbol,values
3282 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3283 std::vector<StringRef> Parameters;
3284 StringRef Parameter;
3286 if (ParseIdentifier(Parameter))
3287 return TokError("expected identifier in '.irp' directive");
3289 Parameters.push_back(Parameter);
3291 if (Lexer.isNot(AsmToken::Comma))
3292 return TokError("expected comma in '.irp' directive");
3296 std::vector<MacroArgument> A;
3297 if (ParseMacroArguments(0, A))
3300 // Eat the end of statement.
3303 // Lex the irp definition.
3304 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3308 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3309 // to hold the macro body with substitutions.
3310 SmallString<256> Buf;
3311 raw_svector_ostream OS(Buf);
3313 for (std::vector<MacroArgument>::iterator i = A.begin(), e = A.end(); i != e;
3315 std::vector<MacroArgument> Args;
3318 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3322 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3327 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3328 if (ActiveMacros.empty())
3329 return TokError("unexpected '.endr' directive, no current .rept");
3331 // The only .repl that should get here are the ones created by
3332 // InstantiateMacroLikeBody.
3333 assert(getLexer().is(AsmToken::EndOfStatement));
3339 /// \brief Create an MCAsmParser instance.
3340 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3341 MCContext &C, MCStreamer &Out,
3342 const MCAsmInfo &MAI) {
3343 return new AsmParser(SM, C, Out, MAI);