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/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/AsmCond.h"
25 #include "llvm/MC/MCParser/AsmLexer.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCTargetAsmParser.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/raw_ostream.h"
46 FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
49 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
53 /// \brief Helper types for tracking macro definitions.
54 typedef std::vector<AsmToken> MCAsmMacroArgument;
55 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
56 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
57 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
62 MCAsmMacroParameters Parameters;
65 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
66 Name(N), Body(B), Parameters(P) {}
68 MCAsmMacro(const MCAsmMacro& Other)
69 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
72 /// \brief Helper class for storing information about an active macro
74 struct MacroInstantiation {
75 /// The macro being instantiated.
76 const MCAsmMacro *TheMacro;
78 /// The macro instantiation with substitutions.
79 MemoryBuffer *Instantiation;
81 /// The location of the instantiation.
82 SMLoc InstantiationLoc;
84 /// The buffer where parsing should resume upon instantiation completion.
87 /// The location where parsing should resume upon instantiation completion.
91 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
95 struct ParseStatementInfo {
96 /// ParsedOperands - The parsed operands from the last parsed statement.
97 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
99 /// Opcode - The opcode from the last parsed instruction.
102 /// Error - Was there an error parsing the inline assembly?
105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
111 ~ParseStatementInfo() {
112 // Free any parsed operands.
113 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
114 delete ParsedOperands[i];
115 ParsedOperands.clear();
119 /// \brief The concrete assembly parser instance.
120 class AsmParser : public MCAsmParser {
121 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
122 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
127 const MCAsmInfo &MAI;
129 SourceMgr::DiagHandlerTy SavedDiagHandler;
130 void *SavedDiagContext;
131 MCAsmParserExtension *PlatformParser;
133 /// This is the current buffer index we're lexing from as managed by the
134 /// SourceMgr object.
137 AsmCond TheCondState;
138 std::vector<AsmCond> TheCondStack;
140 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
141 /// extensions. Extensions register themselves in this map by calling
142 /// AddDirectiveHandler.
143 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
145 /// MacroMap - Map of currently defined macros.
146 StringMap<MCAsmMacro*> MacroMap;
148 /// ActiveMacros - Stack of active macro instantiations.
149 std::vector<MacroInstantiation*> ActiveMacros;
151 /// Boolean tracking whether macro substitution is enabled.
152 unsigned MacrosEnabledFlag : 1;
154 /// Flag tracking whether any errors have been encountered.
155 unsigned HadError : 1;
157 /// The values from the last parsed cpp hash file line comment if any.
158 StringRef CppHashFilename;
159 int64_t CppHashLineNumber;
163 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
164 unsigned AssemblerDialect;
166 /// IsDarwin - is Darwin compatibility enabled?
169 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
170 bool ParsingInlineAsm;
173 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
174 const MCAsmInfo &MAI);
175 virtual ~AsmParser();
177 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
179 virtual void AddDirectiveHandler(StringRef Directive,
180 ExtensionDirectiveHandler Handler) {
181 ExtensionDirectiveMap[Directive] = Handler;
185 /// @name MCAsmParser Interface
188 virtual SourceMgr &getSourceManager() { return SrcMgr; }
189 virtual MCAsmLexer &getLexer() { return Lexer; }
190 virtual MCContext &getContext() { return Ctx; }
191 virtual MCStreamer &getStreamer() { return Out; }
192 virtual unsigned getAssemblerDialect() {
193 if (AssemblerDialect == ~0U)
194 return MAI.getAssemblerDialect();
196 return AssemblerDialect;
198 virtual void setAssemblerDialect(unsigned i) {
199 AssemblerDialect = i;
202 virtual bool Warning(SMLoc L, const Twine &Msg,
203 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
204 virtual bool Error(SMLoc L, const Twine &Msg,
205 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
207 virtual const AsmToken &Lex();
209 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
210 bool isParsingInlineAsm() { return ParsingInlineAsm; }
212 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
213 unsigned &NumOutputs, unsigned &NumInputs,
214 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
215 SmallVectorImpl<std::string> &Constraints,
216 SmallVectorImpl<std::string> &Clobbers,
217 const MCInstrInfo *MII,
218 const MCInstPrinter *IP,
219 MCAsmParserSemaCallback &SI);
221 bool ParseExpression(const MCExpr *&Res);
222 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
223 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
224 virtual bool ParseAbsoluteExpression(int64_t &Res);
226 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
227 /// and set \p Res to the identifier contents.
228 virtual bool ParseIdentifier(StringRef &Res);
229 virtual void EatToEndOfStatement();
231 virtual void CheckForValidSection();
236 bool ParseStatement(ParseStatementInfo &Info);
237 void EatToEndOfLine();
238 bool ParseCppHashLineFilenameComment(const SMLoc &L);
240 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
241 const MCAsmMacroParameters &Parameters,
242 const MCAsmMacroArguments &A,
245 /// \brief Are macros enabled in the parser?
246 bool MacrosEnabled() {return MacrosEnabledFlag;}
248 /// \brief Control a flag in the parser that enables or disables macros.
249 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
251 /// \brief Lookup a previously defined macro.
252 /// \param Name Macro name.
253 /// \returns Pointer to macro. NULL if no such macro was defined.
254 const MCAsmMacro* LookupMacro(StringRef Name);
256 /// \brief Define a new macro with the given name and information.
257 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
259 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
260 void UndefineMacro(StringRef Name);
262 /// \brief Are we inside a macro instantiation?
263 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
265 /// \brief Handle entry to macro instantiation.
267 /// \param M The macro.
268 /// \param NameLoc Instantiation location.
269 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
271 /// \brief Handle exit from macro instantiation.
272 void HandleMacroExit();
274 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
275 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
276 /// correct delimiter by the method.
277 bool ParseMacroArgument(MCAsmMacroArgument &MA,
278 AsmToken::TokenKind &ArgumentDelimiter);
280 /// \brief Parse all macro arguments for a given macro.
281 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
283 void PrintMacroInstantiations();
284 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
285 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
286 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
288 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
290 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
291 bool EnterIncludeFile(const std::string &Filename);
292 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
293 /// This returns true on failure.
294 bool ProcessIncbinFile(const std::string &Filename);
296 /// \brief Reset the current lexer position to that given by \p Loc. The
297 /// current token is not set; clients should ensure Lex() is called
300 /// \param InBuffer If not -1, should be the known buffer id that contains the
302 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
304 /// \brief Parse up to the end of statement and a return the contents from the
305 /// current token until the end of the statement; the current token on exit
306 /// will be either the EndOfStatement or EOF.
307 virtual StringRef ParseStringToEndOfStatement();
309 /// \brief Parse until the end of a statement or a comma is encountered,
310 /// return the contents from the current token up to the end or comma.
311 StringRef ParseStringToComma();
313 bool ParseAssignment(StringRef Name, bool allow_redef,
314 bool NoDeadStrip = false);
316 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
317 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
318 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
319 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
321 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
323 // Generic (target and platform independent) directive parsing.
325 DK_NO_DIRECTIVE, // Placeholder
326 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
327 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
328 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
329 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
330 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
331 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
332 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
333 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
334 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
335 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
336 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
337 DK_ELSEIF, DK_ELSE, DK_ENDIF,
338 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
339 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
340 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
341 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
342 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
343 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
345 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
346 DK_SLEB128, DK_ULEB128
349 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
350 /// directives parsed by this class.
351 StringMap<DirectiveKind> DirectiveKindMap;
353 // ".ascii", ".asciz", ".string"
354 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
355 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
356 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
357 bool ParseDirectiveFill(); // ".fill"
358 bool ParseDirectiveZero(); // ".zero"
359 // ".set", ".equ", ".equiv"
360 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
361 bool ParseDirectiveOrg(); // ".org"
362 // ".align{,32}", ".p2align{,w,l}"
363 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
365 // ".file", ".line", ".loc", ".stabs"
366 bool ParseDirectiveFile(SMLoc DirectiveLoc);
367 bool ParseDirectiveLine();
368 bool ParseDirectiveLoc();
369 bool ParseDirectiveStabs();
372 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
373 bool ParseDirectiveCFISections();
374 bool ParseDirectiveCFIStartProc();
375 bool ParseDirectiveCFIEndProc();
376 bool ParseDirectiveCFIDefCfaOffset();
377 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
378 bool ParseDirectiveCFIAdjustCfaOffset();
379 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
380 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
381 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
383 bool ParseDirectiveCFIRememberState();
384 bool ParseDirectiveCFIRestoreState();
385 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
386 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
387 bool ParseDirectiveCFIEscape();
388 bool ParseDirectiveCFISignalFrame();
389 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
392 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
393 bool ParseDirectiveEndMacro(StringRef Directive);
394 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
395 bool ParseDirectiveMacrosOnOff(StringRef Directive);
397 // ".bundle_align_mode"
398 bool ParseDirectiveBundleAlignMode();
400 bool ParseDirectiveBundleLock();
402 bool ParseDirectiveBundleUnlock();
405 bool ParseDirectiveSpace(StringRef IDVal);
407 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
408 bool ParseDirectiveLEB128(bool Signed);
410 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
411 /// accepts a single symbol (which should be a label or an external).
412 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
414 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
416 bool ParseDirectiveAbort(); // ".abort"
417 bool ParseDirectiveInclude(); // ".include"
418 bool ParseDirectiveIncbin(); // ".incbin"
420 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
421 // ".ifb" or ".ifnb", depending on ExpectBlank.
422 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
423 // ".ifc" or ".ifnc", depending on ExpectEqual.
424 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
425 // ".ifdef" or ".ifndef", depending on expect_defined
426 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
427 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
428 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
429 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
431 /// ParseEscapedString - Parse the current token as a string which may include
432 /// escaped characters and return the string contents.
433 bool ParseEscapedString(std::string &Data);
435 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
436 MCSymbolRefExpr::VariantKind Variant);
438 // Macro-like directives
439 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
440 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
441 raw_svector_ostream &OS);
442 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
443 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
444 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
445 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
448 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
450 void initializeDirectiveKindMap();
456 extern MCAsmParserExtension *createDarwinAsmParser();
457 extern MCAsmParserExtension *createELFAsmParser();
458 extern MCAsmParserExtension *createCOFFAsmParser();
462 enum { DEFAULT_ADDRSPACE = 0 };
464 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
465 MCStreamer &_Out, const MCAsmInfo &_MAI)
466 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
468 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
469 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
470 // Save the old handler.
471 SavedDiagHandler = SrcMgr.getDiagHandler();
472 SavedDiagContext = SrcMgr.getDiagContext();
473 // Set our own handler which calls the saved handler.
474 SrcMgr.setDiagHandler(DiagHandler, this);
475 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
477 // Initialize the platform / file format parser.
479 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
481 if (_MAI.hasMicrosoftFastStdCallMangling()) {
482 PlatformParser = createCOFFAsmParser();
483 PlatformParser->Initialize(*this);
484 } else if (_MAI.hasSubsectionsViaSymbols()) {
485 PlatformParser = createDarwinAsmParser();
486 PlatformParser->Initialize(*this);
489 PlatformParser = createELFAsmParser();
490 PlatformParser->Initialize(*this);
493 initializeDirectiveKindMap();
496 AsmParser::~AsmParser() {
497 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
499 // Destroy any macros.
500 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
501 ie = MacroMap.end(); it != ie; ++it)
502 delete it->getValue();
504 delete PlatformParser;
507 void AsmParser::PrintMacroInstantiations() {
508 // Print the active macro instantiation stack.
509 for (std::vector<MacroInstantiation*>::const_reverse_iterator
510 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
511 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
512 "while in macro instantiation");
515 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
516 if (FatalAssemblerWarnings)
517 return Error(L, Msg, Ranges);
518 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
519 PrintMacroInstantiations();
523 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
525 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
526 PrintMacroInstantiations();
530 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
531 std::string IncludedFile;
532 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
538 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
543 /// Process the specified .incbin file by seaching for it in the include paths
544 /// then just emitting the byte contents of the file to the streamer. This
545 /// returns true on failure.
546 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
547 std::string IncludedFile;
548 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
552 // Pick up the bytes from the file and emit them.
553 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
558 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
559 if (InBuffer != -1) {
560 CurBuffer = InBuffer;
562 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
564 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
567 const AsmToken &AsmParser::Lex() {
568 const AsmToken *tok = &Lexer.Lex();
570 if (tok->is(AsmToken::Eof)) {
571 // If this is the end of an included file, pop the parent file off the
573 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
574 if (ParentIncludeLoc != SMLoc()) {
575 JumpToLoc(ParentIncludeLoc);
580 if (tok->is(AsmToken::Error))
581 Error(Lexer.getErrLoc(), Lexer.getErr());
586 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
587 // Create the initial section, if requested.
588 if (!NoInitialTextSection)
595 AsmCond StartingCondState = TheCondState;
597 // If we are generating dwarf for assembly source files save the initial text
598 // section and generate a .file directive.
599 if (getContext().getGenDwarfForAssembly()) {
600 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
601 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
602 getStreamer().EmitLabel(SectionStartSym);
603 getContext().setGenDwarfSectionStartSym(SectionStartSym);
604 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
606 getContext().getMainFileName());
609 // While we have input, parse each statement.
610 while (Lexer.isNot(AsmToken::Eof)) {
611 ParseStatementInfo Info;
612 if (!ParseStatement(Info)) continue;
614 // We had an error, validate that one was emitted and recover by skipping to
616 assert(HadError && "Parse statement returned an error, but none emitted!");
617 EatToEndOfStatement();
620 if (TheCondState.TheCond != StartingCondState.TheCond ||
621 TheCondState.Ignore != StartingCondState.Ignore)
622 return TokError("unmatched .ifs or .elses");
624 // Check to see there are no empty DwarfFile slots.
625 const std::vector<MCDwarfFile *> &MCDwarfFiles =
626 getContext().getMCDwarfFiles();
627 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
628 if (!MCDwarfFiles[i])
629 TokError("unassigned file number: " + Twine(i) + " for .file directives");
632 // Check to see that all assembler local symbols were actually defined.
633 // Targets that don't do subsections via symbols may not want this, though,
634 // so conservatively exclude them. Only do this if we're finalizing, though,
635 // as otherwise we won't necessarilly have seen everything yet.
636 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
637 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
638 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
641 MCSymbol *Sym = i->getValue();
642 // Variable symbols may not be marked as defined, so check those
643 // explicitly. If we know it's a variable, we have a definition for
644 // the purposes of this check.
645 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
646 // FIXME: We would really like to refer back to where the symbol was
647 // first referenced for a source location. We need to add something
648 // to track that. Currently, we just point to the end of the file.
649 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
650 "assembler local symbol '" + Sym->getName() +
656 // Finalize the output stream if there are no errors and if the client wants
658 if (!HadError && !NoFinalize)
664 void AsmParser::CheckForValidSection() {
665 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
666 TokError("expected section directive before assembly directive");
667 Out.InitToTextSection();
671 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
672 void AsmParser::EatToEndOfStatement() {
673 while (Lexer.isNot(AsmToken::EndOfStatement) &&
674 Lexer.isNot(AsmToken::Eof))
678 if (Lexer.is(AsmToken::EndOfStatement))
682 StringRef AsmParser::ParseStringToEndOfStatement() {
683 const char *Start = getTok().getLoc().getPointer();
685 while (Lexer.isNot(AsmToken::EndOfStatement) &&
686 Lexer.isNot(AsmToken::Eof))
689 const char *End = getTok().getLoc().getPointer();
690 return StringRef(Start, End - Start);
693 StringRef AsmParser::ParseStringToComma() {
694 const char *Start = getTok().getLoc().getPointer();
696 while (Lexer.isNot(AsmToken::EndOfStatement) &&
697 Lexer.isNot(AsmToken::Comma) &&
698 Lexer.isNot(AsmToken::Eof))
701 const char *End = getTok().getLoc().getPointer();
702 return StringRef(Start, End - Start);
705 /// ParseParenExpr - Parse a paren expression and return it.
706 /// NOTE: This assumes the leading '(' has already been consumed.
708 /// parenexpr ::= expr)
710 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
711 if (ParseExpression(Res)) return true;
712 if (Lexer.isNot(AsmToken::RParen))
713 return TokError("expected ')' in parentheses expression");
714 EndLoc = Lexer.getTok().getEndLoc();
719 /// ParseBracketExpr - Parse a bracket expression and return it.
720 /// NOTE: This assumes the leading '[' has already been consumed.
722 /// bracketexpr ::= expr]
724 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
725 if (ParseExpression(Res)) return true;
726 if (Lexer.isNot(AsmToken::RBrac))
727 return TokError("expected ']' in brackets expression");
728 EndLoc = Lexer.getTok().getEndLoc();
733 /// ParsePrimaryExpr - Parse a primary expression and return it.
734 /// primaryexpr ::= (parenexpr
735 /// primaryexpr ::= symbol
736 /// primaryexpr ::= number
737 /// primaryexpr ::= '.'
738 /// primaryexpr ::= ~,+,- primaryexpr
739 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
740 switch (Lexer.getKind()) {
742 return TokError("unknown token in expression");
743 // If we have an error assume that we've already handled it.
744 case AsmToken::Error:
746 case AsmToken::Exclaim:
747 Lex(); // Eat the operator.
748 if (ParsePrimaryExpr(Res, EndLoc))
750 Res = MCUnaryExpr::CreateLNot(Res, getContext());
752 case AsmToken::Dollar:
753 case AsmToken::String:
754 case AsmToken::Identifier: {
755 StringRef Identifier;
756 if (ParseIdentifier(Identifier))
759 EndLoc = SMLoc::getFromPointer(Identifier.end());
761 // This is a symbol reference.
762 std::pair<StringRef, StringRef> Split = Identifier.split('@');
763 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
765 // Lookup the symbol variant if used.
766 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
767 if (Split.first.size() != Identifier.size()) {
768 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
769 if (Variant == MCSymbolRefExpr::VK_Invalid) {
770 Variant = MCSymbolRefExpr::VK_None;
771 return TokError("invalid variant '" + Split.second + "'");
775 // If this is an absolute variable reference, substitute it now to preserve
776 // semantics in the face of reassignment.
777 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
779 return Error(EndLoc, "unexpected modifier on variable reference");
781 Res = Sym->getVariableValue();
785 // Otherwise create a symbol ref.
786 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
789 case AsmToken::Integer: {
790 SMLoc Loc = getTok().getLoc();
791 int64_t IntVal = getTok().getIntVal();
792 Res = MCConstantExpr::Create(IntVal, getContext());
793 EndLoc = Lexer.getTok().getEndLoc();
795 // Look for 'b' or 'f' following an Integer as a directional label
796 if (Lexer.getKind() == AsmToken::Identifier) {
797 StringRef IDVal = getTok().getString();
798 if (IDVal == "f" || IDVal == "b"){
799 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
800 IDVal == "f" ? 1 : 0);
801 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
803 if (IDVal == "b" && Sym->isUndefined())
804 return Error(Loc, "invalid reference to undefined symbol");
805 EndLoc = Lexer.getTok().getEndLoc();
806 Lex(); // Eat identifier.
811 case AsmToken::Real: {
812 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
813 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
814 Res = MCConstantExpr::Create(IntVal, getContext());
815 EndLoc = Lexer.getTok().getEndLoc();
819 case AsmToken::Dot: {
820 // This is a '.' reference, which references the current PC. Emit a
821 // temporary label to the streamer and refer to it.
822 MCSymbol *Sym = Ctx.CreateTempSymbol();
824 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
825 EndLoc = Lexer.getTok().getEndLoc();
826 Lex(); // Eat identifier.
829 case AsmToken::LParen:
830 Lex(); // Eat the '('.
831 return ParseParenExpr(Res, EndLoc);
832 case AsmToken::LBrac:
833 if (!PlatformParser->HasBracketExpressions())
834 return TokError("brackets expression not supported on this target");
835 Lex(); // Eat the '['.
836 return ParseBracketExpr(Res, EndLoc);
837 case AsmToken::Minus:
838 Lex(); // Eat the operator.
839 if (ParsePrimaryExpr(Res, EndLoc))
841 Res = MCUnaryExpr::CreateMinus(Res, getContext());
844 Lex(); // Eat the operator.
845 if (ParsePrimaryExpr(Res, EndLoc))
847 Res = MCUnaryExpr::CreatePlus(Res, getContext());
849 case AsmToken::Tilde:
850 Lex(); // Eat the operator.
851 if (ParsePrimaryExpr(Res, EndLoc))
853 Res = MCUnaryExpr::CreateNot(Res, getContext());
858 bool AsmParser::ParseExpression(const MCExpr *&Res) {
860 return ParseExpression(Res, EndLoc);
864 AsmParser::ApplyModifierToExpr(const MCExpr *E,
865 MCSymbolRefExpr::VariantKind Variant) {
866 // Recurse over the given expression, rebuilding it to apply the given variant
867 // if there is exactly one symbol.
868 switch (E->getKind()) {
870 case MCExpr::Constant:
873 case MCExpr::SymbolRef: {
874 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
876 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
877 TokError("invalid variant on expression '" +
878 getTok().getIdentifier() + "' (already modified)");
882 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
885 case MCExpr::Unary: {
886 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
887 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
890 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
893 case MCExpr::Binary: {
894 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
895 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
896 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
901 if (!LHS) LHS = BE->getLHS();
902 if (!RHS) RHS = BE->getRHS();
904 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
908 llvm_unreachable("Invalid expression kind!");
911 /// ParseExpression - Parse an expression and return it.
913 /// expr ::= expr &&,|| expr -> lowest.
914 /// expr ::= expr |,^,&,! expr
915 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
916 /// expr ::= expr <<,>> expr
917 /// expr ::= expr +,- expr
918 /// expr ::= expr *,/,% expr -> highest.
919 /// expr ::= primaryexpr
921 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
922 // Parse the expression.
924 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
927 // As a special case, we support 'a op b @ modifier' by rewriting the
928 // expression to include the modifier. This is inefficient, but in general we
929 // expect users to use 'a@modifier op b'.
930 if (Lexer.getKind() == AsmToken::At) {
933 if (Lexer.isNot(AsmToken::Identifier))
934 return TokError("unexpected symbol modifier following '@'");
936 MCSymbolRefExpr::VariantKind Variant =
937 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
938 if (Variant == MCSymbolRefExpr::VK_Invalid)
939 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
941 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
943 return TokError("invalid modifier '" + getTok().getIdentifier() +
944 "' (no symbols present)");
951 // Try to constant fold it up front, if possible.
953 if (Res->EvaluateAsAbsolute(Value))
954 Res = MCConstantExpr::Create(Value, getContext());
959 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
961 return ParseParenExpr(Res, EndLoc) ||
962 ParseBinOpRHS(1, Res, EndLoc);
965 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
968 SMLoc StartLoc = Lexer.getLoc();
969 if (ParseExpression(Expr))
972 if (!Expr->EvaluateAsAbsolute(Res))
973 return Error(StartLoc, "expected absolute expression");
978 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
979 MCBinaryExpr::Opcode &Kind) {
982 return 0; // not a binop.
984 // Lowest Precedence: &&, ||
985 case AsmToken::AmpAmp:
986 Kind = MCBinaryExpr::LAnd;
988 case AsmToken::PipePipe:
989 Kind = MCBinaryExpr::LOr;
993 // Low Precedence: |, &, ^
995 // FIXME: gas seems to support '!' as an infix operator?
997 Kind = MCBinaryExpr::Or;
999 case AsmToken::Caret:
1000 Kind = MCBinaryExpr::Xor;
1003 Kind = MCBinaryExpr::And;
1006 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1007 case AsmToken::EqualEqual:
1008 Kind = MCBinaryExpr::EQ;
1010 case AsmToken::ExclaimEqual:
1011 case AsmToken::LessGreater:
1012 Kind = MCBinaryExpr::NE;
1014 case AsmToken::Less:
1015 Kind = MCBinaryExpr::LT;
1017 case AsmToken::LessEqual:
1018 Kind = MCBinaryExpr::LTE;
1020 case AsmToken::Greater:
1021 Kind = MCBinaryExpr::GT;
1023 case AsmToken::GreaterEqual:
1024 Kind = MCBinaryExpr::GTE;
1027 // Intermediate Precedence: <<, >>
1028 case AsmToken::LessLess:
1029 Kind = MCBinaryExpr::Shl;
1031 case AsmToken::GreaterGreater:
1032 Kind = MCBinaryExpr::Shr;
1035 // High Intermediate Precedence: +, -
1036 case AsmToken::Plus:
1037 Kind = MCBinaryExpr::Add;
1039 case AsmToken::Minus:
1040 Kind = MCBinaryExpr::Sub;
1043 // Highest Precedence: *, /, %
1044 case AsmToken::Star:
1045 Kind = MCBinaryExpr::Mul;
1047 case AsmToken::Slash:
1048 Kind = MCBinaryExpr::Div;
1050 case AsmToken::Percent:
1051 Kind = MCBinaryExpr::Mod;
1057 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1058 /// Res contains the LHS of the expression on input.
1059 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1062 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1063 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1065 // If the next token is lower precedence than we are allowed to eat, return
1066 // successfully with what we ate already.
1067 if (TokPrec < Precedence)
1072 // Eat the next primary expression.
1074 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1076 // If BinOp binds less tightly with RHS than the operator after RHS, let
1077 // the pending operator take RHS as its LHS.
1078 MCBinaryExpr::Opcode Dummy;
1079 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1080 if (TokPrec < NextTokPrec) {
1081 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1084 // Merge LHS and RHS according to operator.
1085 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1090 /// ::= EndOfStatement
1091 /// ::= Label* Directive ...Operands... EndOfStatement
1092 /// ::= Label* Identifier OperandList* EndOfStatement
1093 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1094 if (Lexer.is(AsmToken::EndOfStatement)) {
1100 // Statements always start with an identifier or are a full line comment.
1101 AsmToken ID = getTok();
1102 SMLoc IDLoc = ID.getLoc();
1104 int64_t LocalLabelVal = -1;
1105 // A full line comment is a '#' as the first token.
1106 if (Lexer.is(AsmToken::Hash))
1107 return ParseCppHashLineFilenameComment(IDLoc);
1109 // Allow an integer followed by a ':' as a directional local label.
1110 if (Lexer.is(AsmToken::Integer)) {
1111 LocalLabelVal = getTok().getIntVal();
1112 if (LocalLabelVal < 0) {
1113 if (!TheCondState.Ignore)
1114 return TokError("unexpected token at start of statement");
1118 IDVal = getTok().getString();
1119 Lex(); // Consume the integer token to be used as an identifier token.
1120 if (Lexer.getKind() != AsmToken::Colon) {
1121 if (!TheCondState.Ignore)
1122 return TokError("unexpected token at start of statement");
1126 } else if (Lexer.is(AsmToken::Dot)) {
1127 // Treat '.' as a valid identifier in this context.
1131 } else if (ParseIdentifier(IDVal)) {
1132 if (!TheCondState.Ignore)
1133 return TokError("unexpected token at start of statement");
1137 // Handle conditional assembly here before checking for skipping. We
1138 // have to do this so that .endif isn't skipped in a ".if 0" block for
1140 StringMap<DirectiveKind>::const_iterator DirKindIt =
1141 DirectiveKindMap.find(IDVal);
1142 DirectiveKind DirKind =
1143 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1144 DirKindIt->getValue();
1149 return ParseDirectiveIf(IDLoc);
1151 return ParseDirectiveIfb(IDLoc, true);
1153 return ParseDirectiveIfb(IDLoc, false);
1155 return ParseDirectiveIfc(IDLoc, true);
1157 return ParseDirectiveIfc(IDLoc, false);
1159 return ParseDirectiveIfdef(IDLoc, true);
1162 return ParseDirectiveIfdef(IDLoc, false);
1164 return ParseDirectiveElseIf(IDLoc);
1166 return ParseDirectiveElse(IDLoc);
1168 return ParseDirectiveEndIf(IDLoc);
1171 // If we are in a ".if 0" block, ignore this statement.
1172 if (TheCondState.Ignore) {
1173 EatToEndOfStatement();
1177 // FIXME: Recurse on local labels?
1179 // See what kind of statement we have.
1180 switch (Lexer.getKind()) {
1181 case AsmToken::Colon: {
1182 CheckForValidSection();
1184 // identifier ':' -> Label.
1187 // Diagnose attempt to use '.' as a label.
1189 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1191 // Diagnose attempt to use a variable as a label.
1193 // FIXME: Diagnostics. Note the location of the definition as a label.
1194 // FIXME: This doesn't diagnose assignment to a symbol which has been
1195 // implicitly marked as external.
1197 if (LocalLabelVal == -1)
1198 Sym = getContext().GetOrCreateSymbol(IDVal);
1200 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1201 if (!Sym->isUndefined() || Sym->isVariable())
1202 return Error(IDLoc, "invalid symbol redefinition");
1205 if (!ParsingInlineAsm)
1208 // If we are generating dwarf for assembly source files then gather the
1209 // info to make a dwarf label entry for this label if needed.
1210 if (getContext().getGenDwarfForAssembly())
1211 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1214 // Consume any end of statement token, if present, to avoid spurious
1215 // AddBlankLine calls().
1216 if (Lexer.is(AsmToken::EndOfStatement)) {
1218 if (Lexer.is(AsmToken::Eof))
1225 case AsmToken::Equal:
1226 // identifier '=' ... -> assignment statement
1229 return ParseAssignment(IDVal, true);
1231 default: // Normal instruction or directive.
1235 // If macros are enabled, check to see if this is a macro instantiation.
1236 if (MacrosEnabled())
1237 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1238 return HandleMacroEntry(M, IDLoc);
1241 // Otherwise, we have a normal instruction or directive.
1243 // Directives start with "."
1244 if (IDVal[0] == '.' && IDVal != ".") {
1245 // There are several entities interested in parsing directives:
1247 // 1. The target-specific assembly parser. Some directives are target
1248 // specific or may potentially behave differently on certain targets.
1249 // 2. Asm parser extensions. For example, platform-specific parsers
1250 // (like the ELF parser) register themselves as extensions.
1251 // 3. The generic directive parser implemented by this class. These are
1252 // all the directives that behave in a target and platform independent
1253 // manner, or at least have a default behavior that's shared between
1254 // all targets and platforms.
1256 // First query the target-specific parser. It will return 'true' if it
1257 // isn't interested in this directive.
1258 if (!getTargetParser().ParseDirective(ID))
1261 // Next, check the extention directive map to see if any extension has
1262 // registered itself to parse this directive.
1263 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1264 ExtensionDirectiveMap.lookup(IDVal);
1266 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1268 // Finally, if no one else is interested in this directive, it must be
1269 // generic and familiar to this class.
1275 return ParseDirectiveSet(IDVal, true);
1277 return ParseDirectiveSet(IDVal, false);
1279 return ParseDirectiveAscii(IDVal, false);
1282 return ParseDirectiveAscii(IDVal, true);
1284 return ParseDirectiveValue(1);
1288 return ParseDirectiveValue(2);
1292 return ParseDirectiveValue(4);
1295 return ParseDirectiveValue(8);
1298 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1300 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1302 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1303 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1306 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1307 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1310 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1312 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1314 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1316 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1318 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1320 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1322 return ParseDirectiveOrg();
1324 return ParseDirectiveFill();
1326 return ParseDirectiveZero();
1328 EatToEndOfStatement(); // .extern is the default, ignore it.
1332 return ParseDirectiveSymbolAttribute(MCSA_Global);
1333 case DK_INDIRECT_SYMBOL:
1334 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1335 case DK_LAZY_REFERENCE:
1336 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1337 case DK_NO_DEAD_STRIP:
1338 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1339 case DK_SYMBOL_RESOLVER:
1340 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1341 case DK_PRIVATE_EXTERN:
1342 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1344 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1345 case DK_WEAK_DEFINITION:
1346 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1347 case DK_WEAK_REFERENCE:
1348 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1349 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1350 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1353 return ParseDirectiveComm(/*IsLocal=*/false);
1355 return ParseDirectiveComm(/*IsLocal=*/true);
1357 return ParseDirectiveAbort();
1359 return ParseDirectiveInclude();
1361 return ParseDirectiveIncbin();
1364 return TokError(Twine(IDVal) + " not supported yet");
1366 return ParseDirectiveRept(IDLoc);
1368 return ParseDirectiveIrp(IDLoc);
1370 return ParseDirectiveIrpc(IDLoc);
1372 return ParseDirectiveEndr(IDLoc);
1373 case DK_BUNDLE_ALIGN_MODE:
1374 return ParseDirectiveBundleAlignMode();
1375 case DK_BUNDLE_LOCK:
1376 return ParseDirectiveBundleLock();
1377 case DK_BUNDLE_UNLOCK:
1378 return ParseDirectiveBundleUnlock();
1380 return ParseDirectiveLEB128(true);
1382 return ParseDirectiveLEB128(false);
1385 return ParseDirectiveSpace(IDVal);
1387 return ParseDirectiveFile(IDLoc);
1389 return ParseDirectiveLine();
1391 return ParseDirectiveLoc();
1393 return ParseDirectiveStabs();
1394 case DK_CFI_SECTIONS:
1395 return ParseDirectiveCFISections();
1396 case DK_CFI_STARTPROC:
1397 return ParseDirectiveCFIStartProc();
1398 case DK_CFI_ENDPROC:
1399 return ParseDirectiveCFIEndProc();
1400 case DK_CFI_DEF_CFA:
1401 return ParseDirectiveCFIDefCfa(IDLoc);
1402 case DK_CFI_DEF_CFA_OFFSET:
1403 return ParseDirectiveCFIDefCfaOffset();
1404 case DK_CFI_ADJUST_CFA_OFFSET:
1405 return ParseDirectiveCFIAdjustCfaOffset();
1406 case DK_CFI_DEF_CFA_REGISTER:
1407 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1409 return ParseDirectiveCFIOffset(IDLoc);
1410 case DK_CFI_REL_OFFSET:
1411 return ParseDirectiveCFIRelOffset(IDLoc);
1412 case DK_CFI_PERSONALITY:
1413 return ParseDirectiveCFIPersonalityOrLsda(true);
1415 return ParseDirectiveCFIPersonalityOrLsda(false);
1416 case DK_CFI_REMEMBER_STATE:
1417 return ParseDirectiveCFIRememberState();
1418 case DK_CFI_RESTORE_STATE:
1419 return ParseDirectiveCFIRestoreState();
1420 case DK_CFI_SAME_VALUE:
1421 return ParseDirectiveCFISameValue(IDLoc);
1422 case DK_CFI_RESTORE:
1423 return ParseDirectiveCFIRestore(IDLoc);
1425 return ParseDirectiveCFIEscape();
1426 case DK_CFI_SIGNAL_FRAME:
1427 return ParseDirectiveCFISignalFrame();
1428 case DK_CFI_UNDEFINED:
1429 return ParseDirectiveCFIUndefined(IDLoc);
1430 case DK_CFI_REGISTER:
1431 return ParseDirectiveCFIRegister(IDLoc);
1434 return ParseDirectiveMacrosOnOff(IDVal);
1436 return ParseDirectiveMacro(IDLoc);
1439 return ParseDirectiveEndMacro(IDVal);
1441 return ParseDirectivePurgeMacro(IDLoc);
1444 return Error(IDLoc, "unknown directive");
1448 if (ParsingInlineAsm && IDVal == "_emit")
1449 return ParseDirectiveEmit(IDLoc, Info);
1451 CheckForValidSection();
1453 // Canonicalize the opcode to lower case.
1454 SmallString<128> OpcodeStr;
1455 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1456 OpcodeStr.push_back(tolower(IDVal[i]));
1458 ParseInstructionInfo IInfo(Info.AsmRewrites);
1459 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1460 IDLoc,Info.ParsedOperands);
1461 Info.ParseError = HadError;
1463 // Dump the parsed representation, if requested.
1464 if (getShowParsedOperands()) {
1465 SmallString<256> Str;
1466 raw_svector_ostream OS(Str);
1467 OS << "parsed instruction: [";
1468 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1471 Info.ParsedOperands[i]->print(OS);
1475 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1478 // If we are generating dwarf for assembly source files and the current
1479 // section is the initial text section then generate a .loc directive for
1481 if (!HadError && getContext().getGenDwarfForAssembly() &&
1482 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1484 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1486 // If we previously parsed a cpp hash file line comment then make sure the
1487 // current Dwarf File is for the CppHashFilename if not then emit the
1488 // Dwarf File table for it and adjust the line number for the .loc.
1489 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1490 getContext().getMCDwarfFiles();
1491 if (CppHashFilename.size() != 0) {
1492 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1494 getStreamer().EmitDwarfFileDirective(
1495 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1497 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1498 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1501 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1502 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1503 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1507 // If parsing succeeded, match the instruction.
1510 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1511 Info.ParsedOperands,
1516 // Don't skip the rest of the line, the instruction parser is responsible for
1521 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1522 /// since they may not be able to be tokenized to get to the end of line token.
1523 void AsmParser::EatToEndOfLine() {
1524 if (!Lexer.is(AsmToken::EndOfStatement))
1525 Lexer.LexUntilEndOfLine();
1530 /// ParseCppHashLineFilenameComment as this:
1531 /// ::= # number "filename"
1532 /// or just as a full line comment if it doesn't have a number and a string.
1533 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1534 Lex(); // Eat the hash token.
1536 if (getLexer().isNot(AsmToken::Integer)) {
1537 // Consume the line since in cases it is not a well-formed line directive,
1538 // as if were simply a full line comment.
1543 int64_t LineNumber = getTok().getIntVal();
1546 if (getLexer().isNot(AsmToken::String)) {
1551 StringRef Filename = getTok().getString();
1552 // Get rid of the enclosing quotes.
1553 Filename = Filename.substr(1, Filename.size()-2);
1555 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1557 CppHashFilename = Filename;
1558 CppHashLineNumber = LineNumber;
1559 CppHashBuf = CurBuffer;
1561 // Ignore any trailing characters, they're just comment.
1566 /// DiagHandler - will use the last parsed cpp hash line filename comment
1567 /// for the Filename and LineNo if any in the diagnostic.
1568 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1569 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1570 raw_ostream &OS = errs();
1572 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1573 const SMLoc &DiagLoc = Diag.getLoc();
1574 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1575 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1577 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1578 // before printing the message.
1579 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1580 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1581 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1582 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1585 // If we have not parsed a cpp hash line filename comment or the source
1586 // manager changed or buffer changed (like in a nested include) then just
1587 // print the normal diagnostic using its Filename and LineNo.
1588 if (!Parser->CppHashLineNumber ||
1589 &DiagSrcMgr != &Parser->SrcMgr ||
1590 DiagBuf != CppHashBuf) {
1591 if (Parser->SavedDiagHandler)
1592 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1598 // Use the CppHashFilename and calculate a line number based on the
1599 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1601 const std::string Filename = Parser->CppHashFilename;
1603 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1604 int CppHashLocLineNo =
1605 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1606 int LineNo = Parser->CppHashLineNumber - 1 +
1607 (DiagLocLineNo - CppHashLocLineNo);
1609 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1610 Filename, LineNo, Diag.getColumnNo(),
1611 Diag.getKind(), Diag.getMessage(),
1612 Diag.getLineContents(), Diag.getRanges());
1614 if (Parser->SavedDiagHandler)
1615 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1617 NewDiag.print(0, OS);
1620 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1621 // difference being that that function accepts '@' as part of identifiers and
1622 // we can't do that. AsmLexer.cpp should probably be changed to handle
1623 // '@' as a special case when needed.
1624 static bool isIdentifierChar(char c) {
1625 return isalnum(c) || c == '_' || c == '$' || c == '.';
1628 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1629 const MCAsmMacroParameters &Parameters,
1630 const MCAsmMacroArguments &A,
1632 unsigned NParameters = Parameters.size();
1633 if (NParameters != 0 && NParameters != A.size())
1634 return Error(L, "Wrong number of arguments");
1636 // A macro without parameters is handled differently on Darwin:
1637 // gas accepts no arguments and does no substitutions
1638 while (!Body.empty()) {
1639 // Scan for the next substitution.
1640 std::size_t End = Body.size(), Pos = 0;
1641 for (; Pos != End; ++Pos) {
1642 // Check for a substitution or escape.
1644 // This macro has no parameters, look for $0, $1, etc.
1645 if (Body[Pos] != '$' || Pos + 1 == End)
1648 char Next = Body[Pos + 1];
1649 if (Next == '$' || Next == 'n' || isdigit(Next))
1652 // This macro has parameters, look for \foo, \bar, etc.
1653 if (Body[Pos] == '\\' && Pos + 1 != End)
1659 OS << Body.slice(0, Pos);
1661 // Check if we reached the end.
1666 switch (Body[Pos+1]) {
1672 // $n => number of arguments
1677 // $[0-9] => argument
1679 // Missing arguments are ignored.
1680 unsigned Index = Body[Pos+1] - '0';
1681 if (Index >= A.size())
1684 // Otherwise substitute with the token values, with spaces eliminated.
1685 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1686 ie = A[Index].end(); it != ie; ++it)
1687 OS << it->getString();
1693 unsigned I = Pos + 1;
1694 while (isIdentifierChar(Body[I]) && I + 1 != End)
1697 const char *Begin = Body.data() + Pos +1;
1698 StringRef Argument(Begin, I - (Pos +1));
1700 for (; Index < NParameters; ++Index)
1701 if (Parameters[Index].first == Argument)
1704 if (Index == NParameters) {
1705 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1708 OS << '\\' << Argument;
1712 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1713 ie = A[Index].end(); it != ie; ++it)
1714 if (it->getKind() == AsmToken::String)
1715 OS << it->getStringContents();
1717 OS << it->getString();
1719 Pos += 1 + Argument.size();
1722 // Update the scan point.
1723 Body = Body.substr(Pos);
1729 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
1732 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1737 static bool IsOperator(AsmToken::TokenKind kind)
1743 case AsmToken::Plus:
1744 case AsmToken::Minus:
1745 case AsmToken::Tilde:
1746 case AsmToken::Slash:
1747 case AsmToken::Star:
1749 case AsmToken::Equal:
1750 case AsmToken::EqualEqual:
1751 case AsmToken::Pipe:
1752 case AsmToken::PipePipe:
1753 case AsmToken::Caret:
1755 case AsmToken::AmpAmp:
1756 case AsmToken::Exclaim:
1757 case AsmToken::ExclaimEqual:
1758 case AsmToken::Percent:
1759 case AsmToken::Less:
1760 case AsmToken::LessEqual:
1761 case AsmToken::LessLess:
1762 case AsmToken::LessGreater:
1763 case AsmToken::Greater:
1764 case AsmToken::GreaterEqual:
1765 case AsmToken::GreaterGreater:
1770 bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
1771 AsmToken::TokenKind &ArgumentDelimiter) {
1772 unsigned ParenLevel = 0;
1773 unsigned AddTokens = 0;
1775 // gas accepts arguments separated by whitespace, except on Darwin
1777 Lexer.setSkipSpace(false);
1780 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1781 Lexer.setSkipSpace(true);
1782 return TokError("unexpected token in macro instantiation");
1785 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1786 // Spaces and commas cannot be mixed to delimit parameters
1787 if (ArgumentDelimiter == AsmToken::Eof)
1788 ArgumentDelimiter = AsmToken::Comma;
1789 else if (ArgumentDelimiter != AsmToken::Comma) {
1790 Lexer.setSkipSpace(true);
1791 return TokError("expected ' ' for macro argument separator");
1796 if (Lexer.is(AsmToken::Space)) {
1797 Lex(); // Eat spaces
1799 // Spaces can delimit parameters, but could also be part an expression.
1800 // If the token after a space is an operator, add the token and the next
1801 // one into this argument
1802 if (ArgumentDelimiter == AsmToken::Space ||
1803 ArgumentDelimiter == AsmToken::Eof) {
1804 if (IsOperator(Lexer.getKind())) {
1805 // Check to see whether the token is used as an operator,
1806 // or part of an identifier
1807 const char *NextChar = getTok().getEndLoc().getPointer();
1808 if (*NextChar == ' ')
1812 if (!AddTokens && ParenLevel == 0) {
1813 if (ArgumentDelimiter == AsmToken::Eof &&
1814 !IsOperator(Lexer.getKind()))
1815 ArgumentDelimiter = AsmToken::Space;
1821 // HandleMacroEntry relies on not advancing the lexer here
1822 // to be able to fill in the remaining default parameter values
1823 if (Lexer.is(AsmToken::EndOfStatement))
1826 // Adjust the current parentheses level.
1827 if (Lexer.is(AsmToken::LParen))
1829 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1832 // Append the token to the current argument list.
1833 MA.push_back(getTok());
1839 Lexer.setSkipSpace(true);
1840 if (ParenLevel != 0)
1841 return TokError("unbalanced parentheses in macro argument");
1845 // Parse the macro instantiation arguments.
1846 bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
1847 const unsigned NParameters = M ? M->Parameters.size() : 0;
1848 // Argument delimiter is initially unknown. It will be set by
1849 // ParseMacroArgument()
1850 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1852 // Parse two kinds of macro invocations:
1853 // - macros defined without any parameters accept an arbitrary number of them
1854 // - macros defined with parameters accept at most that many of them
1855 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1857 MCAsmMacroArgument MA;
1859 if (ParseMacroArgument(MA, ArgumentDelimiter))
1862 if (!MA.empty() || !NParameters)
1864 else if (NParameters) {
1865 if (!M->Parameters[Parameter].second.empty())
1866 A.push_back(M->Parameters[Parameter].second);
1869 // At the end of the statement, fill in remaining arguments that have
1870 // default values. If there aren't any, then the next argument is
1871 // required but missing
1872 if (Lexer.is(AsmToken::EndOfStatement)) {
1873 if (NParameters && Parameter < NParameters - 1) {
1874 if (M->Parameters[Parameter + 1].second.empty())
1875 return TokError("macro argument '" +
1876 Twine(M->Parameters[Parameter + 1].first) +
1884 if (Lexer.is(AsmToken::Comma))
1887 return TokError("Too many arguments");
1890 const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1891 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1892 return (I == MacroMap.end()) ? NULL : I->getValue();
1895 void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1896 MacroMap[Name] = new MCAsmMacro(Macro);
1899 void AsmParser::UndefineMacro(StringRef Name) {
1900 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1901 if (I != MacroMap.end()) {
1902 delete I->getValue();
1907 bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1908 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1909 // this, although we should protect against infinite loops.
1910 if (ActiveMacros.size() == 20)
1911 return TokError("macros cannot be nested more than 20 levels deep");
1913 MCAsmMacroArguments A;
1914 if (ParseMacroArguments(M, A))
1917 // Remove any trailing empty arguments. Do this after-the-fact as we have
1918 // to keep empty arguments in the middle of the list or positionality
1919 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1920 while (!A.empty() && A.back().empty())
1923 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1924 // to hold the macro body with substitutions.
1925 SmallString<256> Buf;
1926 StringRef Body = M->Body;
1927 raw_svector_ostream OS(Buf);
1929 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1932 // We include the .endmacro in the buffer as our cue to exit the macro
1934 OS << ".endmacro\n";
1936 MemoryBuffer *Instantiation =
1937 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1939 // Create the macro instantiation object and add to the current macro
1940 // instantiation stack.
1941 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1945 ActiveMacros.push_back(MI);
1947 // Jump to the macro instantiation and prime the lexer.
1948 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1949 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1955 void AsmParser::HandleMacroExit() {
1956 // Jump to the EndOfStatement we should return to, and consume it.
1957 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1960 // Pop the instantiation entry.
1961 delete ActiveMacros.back();
1962 ActiveMacros.pop_back();
1965 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1966 switch (Value->getKind()) {
1967 case MCExpr::Binary: {
1968 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1969 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1972 case MCExpr::Target:
1973 case MCExpr::Constant:
1975 case MCExpr::SymbolRef: {
1976 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1978 return IsUsedIn(Sym, S.getVariableValue());
1982 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1985 llvm_unreachable("Unknown expr kind!");
1988 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1990 // FIXME: Use better location, we should use proper tokens.
1991 SMLoc EqualLoc = Lexer.getLoc();
1993 const MCExpr *Value;
1994 if (ParseExpression(Value))
1997 // Note: we don't count b as used in "a = b". This is to allow
2001 if (Lexer.isNot(AsmToken::EndOfStatement))
2002 return TokError("unexpected token in assignment");
2004 // Error on assignment to '.'.
2006 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2007 "(use '.space' or '.org').)"));
2010 // Eat the end of statement marker.
2013 // Validate that the LHS is allowed to be a variable (either it has not been
2014 // used as a symbol, or it is an absolute symbol).
2015 MCSymbol *Sym = getContext().LookupSymbol(Name);
2017 // Diagnose assignment to a label.
2019 // FIXME: Diagnostics. Note the location of the definition as a label.
2020 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2021 if (IsUsedIn(Sym, Value))
2022 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2023 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2024 ; // Allow redefinitions of undefined symbols only used in directives.
2025 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2026 ; // Allow redefinitions of variables that haven't yet been used.
2027 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2028 return Error(EqualLoc, "redefinition of '" + Name + "'");
2029 else if (!Sym->isVariable())
2030 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2031 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2032 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2035 // Don't count these checks as uses.
2036 Sym->setUsed(false);
2038 Sym = getContext().GetOrCreateSymbol(Name);
2040 // FIXME: Handle '.'.
2042 // Do the assignment.
2043 Out.EmitAssignment(Sym, Value);
2045 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2051 /// ParseIdentifier:
2054 bool AsmParser::ParseIdentifier(StringRef &Res) {
2055 // The assembler has relaxed rules for accepting identifiers, in particular we
2056 // allow things like '.globl $foo', which would normally be separate
2057 // tokens. At this level, we have already lexed so we cannot (currently)
2058 // handle this as a context dependent token, instead we detect adjacent tokens
2059 // and return the combined identifier.
2060 if (Lexer.is(AsmToken::Dollar)) {
2061 SMLoc DollarLoc = getLexer().getLoc();
2063 // Consume the dollar sign, and check for a following identifier.
2065 if (Lexer.isNot(AsmToken::Identifier))
2068 // We have a '$' followed by an identifier, make sure they are adjacent.
2069 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2072 // Construct the joined identifier and consume the token.
2073 Res = StringRef(DollarLoc.getPointer(),
2074 getTok().getIdentifier().size() + 1);
2079 if (Lexer.isNot(AsmToken::Identifier) &&
2080 Lexer.isNot(AsmToken::String))
2083 Res = getTok().getIdentifier();
2085 Lex(); // Consume the identifier token.
2090 /// ParseDirectiveSet:
2091 /// ::= .equ identifier ',' expression
2092 /// ::= .equiv identifier ',' expression
2093 /// ::= .set identifier ',' expression
2094 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2097 if (ParseIdentifier(Name))
2098 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2100 if (getLexer().isNot(AsmToken::Comma))
2101 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2104 return ParseAssignment(Name, allow_redef, true);
2107 bool AsmParser::ParseEscapedString(std::string &Data) {
2108 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2111 StringRef Str = getTok().getStringContents();
2112 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2113 if (Str[i] != '\\') {
2118 // Recognize escaped characters. Note that this escape semantics currently
2119 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2122 return TokError("unexpected backslash at end of string");
2124 // Recognize octal sequences.
2125 if ((unsigned) (Str[i] - '0') <= 7) {
2126 // Consume up to three octal characters.
2127 unsigned Value = Str[i] - '0';
2129 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2131 Value = Value * 8 + (Str[i] - '0');
2133 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2135 Value = Value * 8 + (Str[i] - '0');
2140 return TokError("invalid octal escape sequence (out of range)");
2142 Data += (unsigned char) Value;
2146 // Otherwise recognize individual escapes.
2149 // Just reject invalid escape sequences for now.
2150 return TokError("invalid escape sequence (unrecognized character)");
2152 case 'b': Data += '\b'; break;
2153 case 'f': Data += '\f'; break;
2154 case 'n': Data += '\n'; break;
2155 case 'r': Data += '\r'; break;
2156 case 't': Data += '\t'; break;
2157 case '"': Data += '"'; break;
2158 case '\\': Data += '\\'; break;
2165 /// ParseDirectiveAscii:
2166 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2167 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2168 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2169 CheckForValidSection();
2172 if (getLexer().isNot(AsmToken::String))
2173 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2176 if (ParseEscapedString(Data))
2179 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2181 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2185 if (getLexer().is(AsmToken::EndOfStatement))
2188 if (getLexer().isNot(AsmToken::Comma))
2189 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2198 /// ParseDirectiveValue
2199 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2200 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2201 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2202 CheckForValidSection();
2205 const MCExpr *Value;
2206 SMLoc ExprLoc = getLexer().getLoc();
2207 if (ParseExpression(Value))
2210 // Special case constant expressions to match code generator.
2211 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2212 assert(Size <= 8 && "Invalid size");
2213 uint64_t IntValue = MCE->getValue();
2214 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2215 return Error(ExprLoc, "literal value out of range for directive");
2216 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2218 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2220 if (getLexer().is(AsmToken::EndOfStatement))
2223 // FIXME: Improve diagnostic.
2224 if (getLexer().isNot(AsmToken::Comma))
2225 return TokError("unexpected token in directive");
2234 /// ParseDirectiveRealValue
2235 /// ::= (.single | .double) [ expression (, expression)* ]
2236 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2237 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2238 CheckForValidSection();
2241 // We don't truly support arithmetic on floating point expressions, so we
2242 // have to manually parse unary prefixes.
2244 if (getLexer().is(AsmToken::Minus)) {
2247 } else if (getLexer().is(AsmToken::Plus))
2250 if (getLexer().isNot(AsmToken::Integer) &&
2251 getLexer().isNot(AsmToken::Real) &&
2252 getLexer().isNot(AsmToken::Identifier))
2253 return TokError("unexpected token in directive");
2255 // Convert to an APFloat.
2256 APFloat Value(Semantics);
2257 StringRef IDVal = getTok().getString();
2258 if (getLexer().is(AsmToken::Identifier)) {
2259 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2260 Value = APFloat::getInf(Semantics);
2261 else if (!IDVal.compare_lower("nan"))
2262 Value = APFloat::getNaN(Semantics, false, ~0);
2264 return TokError("invalid floating point literal");
2265 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2266 APFloat::opInvalidOp)
2267 return TokError("invalid floating point literal");
2271 // Consume the numeric token.
2274 // Emit the value as an integer.
2275 APInt AsInt = Value.bitcastToAPInt();
2276 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2277 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2279 if (getLexer().is(AsmToken::EndOfStatement))
2282 if (getLexer().isNot(AsmToken::Comma))
2283 return TokError("unexpected token in directive");
2292 /// ParseDirectiveZero
2293 /// ::= .zero expression
2294 bool AsmParser::ParseDirectiveZero() {
2295 CheckForValidSection();
2298 if (ParseAbsoluteExpression(NumBytes))
2302 if (getLexer().is(AsmToken::Comma)) {
2304 if (ParseAbsoluteExpression(Val))
2308 if (getLexer().isNot(AsmToken::EndOfStatement))
2309 return TokError("unexpected token in '.zero' directive");
2313 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2318 /// ParseDirectiveFill
2319 /// ::= .fill expression , expression , expression
2320 bool AsmParser::ParseDirectiveFill() {
2321 CheckForValidSection();
2324 if (ParseAbsoluteExpression(NumValues))
2327 if (getLexer().isNot(AsmToken::Comma))
2328 return TokError("unexpected token in '.fill' directive");
2332 if (ParseAbsoluteExpression(FillSize))
2335 if (getLexer().isNot(AsmToken::Comma))
2336 return TokError("unexpected token in '.fill' directive");
2340 if (ParseAbsoluteExpression(FillExpr))
2343 if (getLexer().isNot(AsmToken::EndOfStatement))
2344 return TokError("unexpected token in '.fill' directive");
2348 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2349 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2351 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2352 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2357 /// ParseDirectiveOrg
2358 /// ::= .org expression [ , expression ]
2359 bool AsmParser::ParseDirectiveOrg() {
2360 CheckForValidSection();
2362 const MCExpr *Offset;
2363 SMLoc Loc = getTok().getLoc();
2364 if (ParseExpression(Offset))
2367 // Parse optional fill expression.
2368 int64_t FillExpr = 0;
2369 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2370 if (getLexer().isNot(AsmToken::Comma))
2371 return TokError("unexpected token in '.org' directive");
2374 if (ParseAbsoluteExpression(FillExpr))
2377 if (getLexer().isNot(AsmToken::EndOfStatement))
2378 return TokError("unexpected token in '.org' directive");
2383 // Only limited forms of relocatable expressions are accepted here, it
2384 // has to be relative to the current section. The streamer will return
2385 // 'true' if the expression wasn't evaluatable.
2386 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2387 return Error(Loc, "expected assembly-time absolute expression");
2392 /// ParseDirectiveAlign
2393 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2394 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2395 CheckForValidSection();
2397 SMLoc AlignmentLoc = getLexer().getLoc();
2399 if (ParseAbsoluteExpression(Alignment))
2403 bool HasFillExpr = false;
2404 int64_t FillExpr = 0;
2405 int64_t MaxBytesToFill = 0;
2406 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2407 if (getLexer().isNot(AsmToken::Comma))
2408 return TokError("unexpected token in directive");
2411 // The fill expression can be omitted while specifying a maximum number of
2412 // alignment bytes, e.g:
2414 if (getLexer().isNot(AsmToken::Comma)) {
2416 if (ParseAbsoluteExpression(FillExpr))
2420 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2421 if (getLexer().isNot(AsmToken::Comma))
2422 return TokError("unexpected token in directive");
2425 MaxBytesLoc = getLexer().getLoc();
2426 if (ParseAbsoluteExpression(MaxBytesToFill))
2429 if (getLexer().isNot(AsmToken::EndOfStatement))
2430 return TokError("unexpected token in directive");
2439 // Compute alignment in bytes.
2441 // FIXME: Diagnose overflow.
2442 if (Alignment >= 32) {
2443 Error(AlignmentLoc, "invalid alignment value");
2447 Alignment = 1ULL << Alignment;
2450 // Diagnose non-sensical max bytes to align.
2451 if (MaxBytesLoc.isValid()) {
2452 if (MaxBytesToFill < 1) {
2453 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2454 "many bytes, ignoring maximum bytes expression");
2458 if (MaxBytesToFill >= Alignment) {
2459 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2465 // Check whether we should use optimal code alignment for this .align
2467 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2468 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2469 ValueSize == 1 && UseCodeAlign) {
2470 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2472 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2473 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2480 /// ParseDirectiveFile
2481 /// ::= .file [number] filename
2482 /// ::= .file number directory filename
2483 bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2484 // FIXME: I'm not sure what this is.
2485 int64_t FileNumber = -1;
2486 SMLoc FileNumberLoc = getLexer().getLoc();
2487 if (getLexer().is(AsmToken::Integer)) {
2488 FileNumber = getTok().getIntVal();
2492 return TokError("file number less than one");
2495 if (getLexer().isNot(AsmToken::String))
2496 return TokError("unexpected token in '.file' directive");
2498 // Usually the directory and filename together, otherwise just the directory.
2499 StringRef Path = getTok().getString();
2500 Path = Path.substr(1, Path.size()-2);
2503 StringRef Directory;
2505 if (getLexer().is(AsmToken::String)) {
2506 if (FileNumber == -1)
2507 return TokError("explicit path specified, but no file number");
2508 Filename = getTok().getString();
2509 Filename = Filename.substr(1, Filename.size()-2);
2516 if (getLexer().isNot(AsmToken::EndOfStatement))
2517 return TokError("unexpected token in '.file' directive");
2519 if (FileNumber == -1)
2520 getStreamer().EmitFileDirective(Filename);
2522 if (getContext().getGenDwarfForAssembly() == true)
2523 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2524 "used to generate dwarf debug info for assembly code");
2526 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2527 Error(FileNumberLoc, "file number already allocated");
2533 /// ParseDirectiveLine
2534 /// ::= .line [number]
2535 bool AsmParser::ParseDirectiveLine() {
2536 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2537 if (getLexer().isNot(AsmToken::Integer))
2538 return TokError("unexpected token in '.line' directive");
2540 int64_t LineNumber = getTok().getIntVal();
2544 // FIXME: Do something with the .line.
2547 if (getLexer().isNot(AsmToken::EndOfStatement))
2548 return TokError("unexpected token in '.line' directive");
2553 /// ParseDirectiveLoc
2554 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2555 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2556 /// The first number is a file number, must have been previously assigned with
2557 /// a .file directive, the second number is the line number and optionally the
2558 /// third number is a column position (zero if not specified). The remaining
2559 /// optional items are .loc sub-directives.
2560 bool AsmParser::ParseDirectiveLoc() {
2561 if (getLexer().isNot(AsmToken::Integer))
2562 return TokError("unexpected token in '.loc' directive");
2563 int64_t FileNumber = getTok().getIntVal();
2565 return TokError("file number less than one in '.loc' directive");
2566 if (!getContext().isValidDwarfFileNumber(FileNumber))
2567 return TokError("unassigned file number in '.loc' directive");
2570 int64_t LineNumber = 0;
2571 if (getLexer().is(AsmToken::Integer)) {
2572 LineNumber = getTok().getIntVal();
2574 return TokError("line number less than one in '.loc' directive");
2578 int64_t ColumnPos = 0;
2579 if (getLexer().is(AsmToken::Integer)) {
2580 ColumnPos = getTok().getIntVal();
2582 return TokError("column position less than zero in '.loc' directive");
2586 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2588 int64_t Discriminator = 0;
2589 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2591 if (getLexer().is(AsmToken::EndOfStatement))
2595 SMLoc Loc = getTok().getLoc();
2596 if (ParseIdentifier(Name))
2597 return TokError("unexpected token in '.loc' directive");
2599 if (Name == "basic_block")
2600 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2601 else if (Name == "prologue_end")
2602 Flags |= DWARF2_FLAG_PROLOGUE_END;
2603 else if (Name == "epilogue_begin")
2604 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2605 else if (Name == "is_stmt") {
2606 Loc = getTok().getLoc();
2607 const MCExpr *Value;
2608 if (ParseExpression(Value))
2610 // The expression must be the constant 0 or 1.
2611 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2612 int Value = MCE->getValue();
2614 Flags &= ~DWARF2_FLAG_IS_STMT;
2615 else if (Value == 1)
2616 Flags |= DWARF2_FLAG_IS_STMT;
2618 return Error(Loc, "is_stmt value not 0 or 1");
2621 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2624 else if (Name == "isa") {
2625 Loc = getTok().getLoc();
2626 const MCExpr *Value;
2627 if (ParseExpression(Value))
2629 // The expression must be a constant greater or equal to 0.
2630 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2631 int Value = MCE->getValue();
2633 return Error(Loc, "isa number less than zero");
2637 return Error(Loc, "isa number not a constant value");
2640 else if (Name == "discriminator") {
2641 if (ParseAbsoluteExpression(Discriminator))
2645 return Error(Loc, "unknown sub-directive in '.loc' directive");
2648 if (getLexer().is(AsmToken::EndOfStatement))
2653 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2654 Isa, Discriminator, StringRef());
2659 /// ParseDirectiveStabs
2660 /// ::= .stabs string, number, number, number
2661 bool AsmParser::ParseDirectiveStabs() {
2662 return TokError("unsupported directive '.stabs'");
2665 /// ParseDirectiveCFISections
2666 /// ::= .cfi_sections section [, section]
2667 bool AsmParser::ParseDirectiveCFISections() {
2672 if (ParseIdentifier(Name))
2673 return TokError("Expected an identifier");
2675 if (Name == ".eh_frame")
2677 else if (Name == ".debug_frame")
2680 if (getLexer().is(AsmToken::Comma)) {
2683 if (ParseIdentifier(Name))
2684 return TokError("Expected an identifier");
2686 if (Name == ".eh_frame")
2688 else if (Name == ".debug_frame")
2692 getStreamer().EmitCFISections(EH, Debug);
2696 /// ParseDirectiveCFIStartProc
2697 /// ::= .cfi_startproc
2698 bool AsmParser::ParseDirectiveCFIStartProc() {
2699 getStreamer().EmitCFIStartProc();
2703 /// ParseDirectiveCFIEndProc
2704 /// ::= .cfi_endproc
2705 bool AsmParser::ParseDirectiveCFIEndProc() {
2706 getStreamer().EmitCFIEndProc();
2710 /// ParseRegisterOrRegisterNumber - parse register name or number.
2711 bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2712 SMLoc DirectiveLoc) {
2715 if (getLexer().isNot(AsmToken::Integer)) {
2716 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2718 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2720 return ParseAbsoluteExpression(Register);
2725 /// ParseDirectiveCFIDefCfa
2726 /// ::= .cfi_def_cfa register, offset
2727 bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2728 int64_t Register = 0;
2729 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2732 if (getLexer().isNot(AsmToken::Comma))
2733 return TokError("unexpected token in directive");
2737 if (ParseAbsoluteExpression(Offset))
2740 getStreamer().EmitCFIDefCfa(Register, Offset);
2744 /// ParseDirectiveCFIDefCfaOffset
2745 /// ::= .cfi_def_cfa_offset offset
2746 bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2748 if (ParseAbsoluteExpression(Offset))
2751 getStreamer().EmitCFIDefCfaOffset(Offset);
2755 /// ParseDirectiveCFIRegister
2756 /// ::= .cfi_register register, register
2757 bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2758 int64_t Register1 = 0;
2759 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2762 if (getLexer().isNot(AsmToken::Comma))
2763 return TokError("unexpected token in directive");
2766 int64_t Register2 = 0;
2767 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2770 getStreamer().EmitCFIRegister(Register1, Register2);
2774 /// ParseDirectiveCFIAdjustCfaOffset
2775 /// ::= .cfi_adjust_cfa_offset adjustment
2776 bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2777 int64_t Adjustment = 0;
2778 if (ParseAbsoluteExpression(Adjustment))
2781 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2785 /// ParseDirectiveCFIDefCfaRegister
2786 /// ::= .cfi_def_cfa_register register
2787 bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2788 int64_t Register = 0;
2789 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2792 getStreamer().EmitCFIDefCfaRegister(Register);
2796 /// ParseDirectiveCFIOffset
2797 /// ::= .cfi_offset register, offset
2798 bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2799 int64_t Register = 0;
2802 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2805 if (getLexer().isNot(AsmToken::Comma))
2806 return TokError("unexpected token in directive");
2809 if (ParseAbsoluteExpression(Offset))
2812 getStreamer().EmitCFIOffset(Register, Offset);
2816 /// ParseDirectiveCFIRelOffset
2817 /// ::= .cfi_rel_offset register, offset
2818 bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2819 int64_t Register = 0;
2821 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2824 if (getLexer().isNot(AsmToken::Comma))
2825 return TokError("unexpected token in directive");
2829 if (ParseAbsoluteExpression(Offset))
2832 getStreamer().EmitCFIRelOffset(Register, Offset);
2836 static bool isValidEncoding(int64_t Encoding) {
2837 if (Encoding & ~0xff)
2840 if (Encoding == dwarf::DW_EH_PE_omit)
2843 const unsigned Format = Encoding & 0xf;
2844 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2845 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2846 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2847 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2850 const unsigned Application = Encoding & 0x70;
2851 if (Application != dwarf::DW_EH_PE_absptr &&
2852 Application != dwarf::DW_EH_PE_pcrel)
2858 /// ParseDirectiveCFIPersonalityOrLsda
2859 /// IsPersonality true for cfi_personality, false for cfi_lsda
2860 /// ::= .cfi_personality encoding, [symbol_name]
2861 /// ::= .cfi_lsda encoding, [symbol_name]
2862 bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2863 int64_t Encoding = 0;
2864 if (ParseAbsoluteExpression(Encoding))
2866 if (Encoding == dwarf::DW_EH_PE_omit)
2869 if (!isValidEncoding(Encoding))
2870 return TokError("unsupported encoding.");
2872 if (getLexer().isNot(AsmToken::Comma))
2873 return TokError("unexpected token in directive");
2877 if (ParseIdentifier(Name))
2878 return TokError("expected identifier in directive");
2880 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2883 getStreamer().EmitCFIPersonality(Sym, Encoding);
2885 getStreamer().EmitCFILsda(Sym, Encoding);
2889 /// ParseDirectiveCFIRememberState
2890 /// ::= .cfi_remember_state
2891 bool AsmParser::ParseDirectiveCFIRememberState() {
2892 getStreamer().EmitCFIRememberState();
2896 /// ParseDirectiveCFIRestoreState
2897 /// ::= .cfi_remember_state
2898 bool AsmParser::ParseDirectiveCFIRestoreState() {
2899 getStreamer().EmitCFIRestoreState();
2903 /// ParseDirectiveCFISameValue
2904 /// ::= .cfi_same_value register
2905 bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2906 int64_t Register = 0;
2908 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2911 getStreamer().EmitCFISameValue(Register);
2915 /// ParseDirectiveCFIRestore
2916 /// ::= .cfi_restore register
2917 bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2918 int64_t Register = 0;
2919 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2922 getStreamer().EmitCFIRestore(Register);
2926 /// ParseDirectiveCFIEscape
2927 /// ::= .cfi_escape expression[,...]
2928 bool AsmParser::ParseDirectiveCFIEscape() {
2931 if (ParseAbsoluteExpression(CurrValue))
2934 Values.push_back((uint8_t)CurrValue);
2936 while (getLexer().is(AsmToken::Comma)) {
2939 if (ParseAbsoluteExpression(CurrValue))
2942 Values.push_back((uint8_t)CurrValue);
2945 getStreamer().EmitCFIEscape(Values);
2949 /// ParseDirectiveCFISignalFrame
2950 /// ::= .cfi_signal_frame
2951 bool AsmParser::ParseDirectiveCFISignalFrame() {
2952 if (getLexer().isNot(AsmToken::EndOfStatement))
2953 return Error(getLexer().getLoc(),
2954 "unexpected token in '.cfi_signal_frame'");
2956 getStreamer().EmitCFISignalFrame();
2960 /// ParseDirectiveCFIUndefined
2961 /// ::= .cfi_undefined register
2962 bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2963 int64_t Register = 0;
2965 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2968 getStreamer().EmitCFIUndefined(Register);
2972 /// ParseDirectiveMacrosOnOff
2975 bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2976 if (getLexer().isNot(AsmToken::EndOfStatement))
2977 return Error(getLexer().getLoc(),
2978 "unexpected token in '" + Directive + "' directive");
2980 SetMacrosEnabled(Directive == ".macros_on");
2984 /// ParseDirectiveMacro
2985 /// ::= .macro name [parameters]
2986 bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2988 if (ParseIdentifier(Name))
2989 return TokError("expected identifier in '.macro' directive");
2991 MCAsmMacroParameters Parameters;
2992 // Argument delimiter is initially unknown. It will be set by
2993 // ParseMacroArgument()
2994 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
2995 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2997 MCAsmMacroParameter Parameter;
2998 if (ParseIdentifier(Parameter.first))
2999 return TokError("expected identifier in '.macro' directive");
3001 if (getLexer().is(AsmToken::Equal)) {
3003 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3007 Parameters.push_back(Parameter);
3009 if (getLexer().is(AsmToken::Comma))
3011 else if (getLexer().is(AsmToken::EndOfStatement))
3016 // Eat the end of statement.
3019 AsmToken EndToken, StartToken = getTok();
3021 // Lex the macro definition.
3023 // Check whether we have reached the end of the file.
3024 if (getLexer().is(AsmToken::Eof))
3025 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3027 // Otherwise, check whether we have reach the .endmacro.
3028 if (getLexer().is(AsmToken::Identifier) &&
3029 (getTok().getIdentifier() == ".endm" ||
3030 getTok().getIdentifier() == ".endmacro")) {
3031 EndToken = getTok();
3033 if (getLexer().isNot(AsmToken::EndOfStatement))
3034 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3039 // Otherwise, scan til the end of the statement.
3040 EatToEndOfStatement();
3043 if (LookupMacro(Name)) {
3044 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3047 const char *BodyStart = StartToken.getLoc().getPointer();
3048 const char *BodyEnd = EndToken.getLoc().getPointer();
3049 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3050 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3054 /// ParseDirectiveEndMacro
3057 bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3058 if (getLexer().isNot(AsmToken::EndOfStatement))
3059 return TokError("unexpected token in '" + Directive + "' directive");
3061 // If we are inside a macro instantiation, terminate the current
3063 if (InsideMacroInstantiation()) {
3068 // Otherwise, this .endmacro is a stray entry in the file; well formed
3069 // .endmacro directives are handled during the macro definition parsing.
3070 return TokError("unexpected '" + Directive + "' in file, "
3071 "no current macro definition");
3074 /// ParseDirectivePurgeMacro
3076 bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3078 if (ParseIdentifier(Name))
3079 return TokError("expected identifier in '.purgem' directive");
3081 if (getLexer().isNot(AsmToken::EndOfStatement))
3082 return TokError("unexpected token in '.purgem' directive");
3084 if (!LookupMacro(Name))
3085 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3087 UndefineMacro(Name);
3091 /// ParseDirectiveBundleAlignMode
3092 /// ::= {.bundle_align_mode} expression
3093 bool AsmParser::ParseDirectiveBundleAlignMode() {
3094 CheckForValidSection();
3096 // Expect a single argument: an expression that evaluates to a constant
3097 // in the inclusive range 0-30.
3098 SMLoc ExprLoc = getLexer().getLoc();
3099 int64_t AlignSizePow2;
3100 if (ParseAbsoluteExpression(AlignSizePow2))
3102 else if (getLexer().isNot(AsmToken::EndOfStatement))
3103 return TokError("unexpected token after expression in"
3104 " '.bundle_align_mode' directive");
3105 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3106 return Error(ExprLoc,
3107 "invalid bundle alignment size (expected between 0 and 30)");
3111 // Because of AlignSizePow2's verified range we can safely truncate it to
3113 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3117 /// ParseDirectiveBundleLock
3118 /// ::= {.bundle_lock} [align_to_end]
3119 bool AsmParser::ParseDirectiveBundleLock() {
3120 CheckForValidSection();
3121 bool AlignToEnd = false;
3123 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3125 SMLoc Loc = getTok().getLoc();
3126 const char *kInvalidOptionError =
3127 "invalid option for '.bundle_lock' directive";
3129 if (ParseIdentifier(Option))
3130 return Error(Loc, kInvalidOptionError);
3132 if (Option != "align_to_end")
3133 return Error(Loc, kInvalidOptionError);
3134 else if (getLexer().isNot(AsmToken::EndOfStatement))
3136 "unexpected token after '.bundle_lock' directive option");
3142 getStreamer().EmitBundleLock(AlignToEnd);
3146 /// ParseDirectiveBundleLock
3147 /// ::= {.bundle_lock}
3148 bool AsmParser::ParseDirectiveBundleUnlock() {
3149 CheckForValidSection();
3151 if (getLexer().isNot(AsmToken::EndOfStatement))
3152 return TokError("unexpected token in '.bundle_unlock' directive");
3155 getStreamer().EmitBundleUnlock();
3159 /// ParseDirectiveSpace
3160 /// ::= (.skip | .space) expression [ , expression ]
3161 bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3162 CheckForValidSection();
3165 if (ParseAbsoluteExpression(NumBytes))
3168 int64_t FillExpr = 0;
3169 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3170 if (getLexer().isNot(AsmToken::Comma))
3171 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3174 if (ParseAbsoluteExpression(FillExpr))
3177 if (getLexer().isNot(AsmToken::EndOfStatement))
3178 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3184 return TokError("invalid number of bytes in '" +
3185 Twine(IDVal) + "' directive");
3187 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3188 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3193 /// ParseDirectiveLEB128
3194 /// ::= (.sleb128 | .uleb128) expression
3195 bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3196 CheckForValidSection();
3197 const MCExpr *Value;
3199 if (ParseExpression(Value))
3202 if (getLexer().isNot(AsmToken::EndOfStatement))
3203 return TokError("unexpected token in directive");
3206 getStreamer().EmitSLEB128Value(Value);
3208 getStreamer().EmitULEB128Value(Value);
3213 /// ParseDirectiveSymbolAttribute
3214 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3215 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3216 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3219 SMLoc Loc = getTok().getLoc();
3221 if (ParseIdentifier(Name))
3222 return Error(Loc, "expected identifier in directive");
3224 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3226 // Assembler local symbols don't make any sense here. Complain loudly.
3227 if (Sym->isTemporary())
3228 return Error(Loc, "non-local symbol required in directive");
3230 getStreamer().EmitSymbolAttribute(Sym, Attr);
3232 if (getLexer().is(AsmToken::EndOfStatement))
3235 if (getLexer().isNot(AsmToken::Comma))
3236 return TokError("unexpected token in directive");
3245 /// ParseDirectiveComm
3246 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3247 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
3248 CheckForValidSection();
3250 SMLoc IDLoc = getLexer().getLoc();
3252 if (ParseIdentifier(Name))
3253 return TokError("expected identifier in directive");
3255 // Handle the identifier as the key symbol.
3256 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3258 if (getLexer().isNot(AsmToken::Comma))
3259 return TokError("unexpected token in directive");
3263 SMLoc SizeLoc = getLexer().getLoc();
3264 if (ParseAbsoluteExpression(Size))
3267 int64_t Pow2Alignment = 0;
3268 SMLoc Pow2AlignmentLoc;
3269 if (getLexer().is(AsmToken::Comma)) {
3271 Pow2AlignmentLoc = getLexer().getLoc();
3272 if (ParseAbsoluteExpression(Pow2Alignment))
3275 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3276 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3277 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3279 // If this target takes alignments in bytes (not log) validate and convert.
3280 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3281 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3282 if (!isPowerOf2_64(Pow2Alignment))
3283 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3284 Pow2Alignment = Log2_64(Pow2Alignment);
3288 if (getLexer().isNot(AsmToken::EndOfStatement))
3289 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3293 // NOTE: a size of zero for a .comm should create a undefined symbol
3294 // but a size of .lcomm creates a bss symbol of size zero.
3296 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3297 "be less than zero");
3299 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3300 // may internally end up wanting an alignment in bytes.
3301 // FIXME: Diagnose overflow.
3302 if (Pow2Alignment < 0)
3303 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3304 "alignment, can't be less than zero");
3306 if (!Sym->isUndefined())
3307 return Error(IDLoc, "invalid symbol redefinition");
3309 // Create the Symbol as a common or local common with Size and Pow2Alignment
3311 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3315 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3319 /// ParseDirectiveAbort
3320 /// ::= .abort [... message ...]
3321 bool AsmParser::ParseDirectiveAbort() {
3322 // FIXME: Use loc from directive.
3323 SMLoc Loc = getLexer().getLoc();
3325 StringRef Str = ParseStringToEndOfStatement();
3326 if (getLexer().isNot(AsmToken::EndOfStatement))
3327 return TokError("unexpected token in '.abort' directive");
3332 Error(Loc, ".abort detected. Assembly stopping.");
3334 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3335 // FIXME: Actually abort assembly here.
3340 /// ParseDirectiveInclude
3341 /// ::= .include "filename"
3342 bool AsmParser::ParseDirectiveInclude() {
3343 if (getLexer().isNot(AsmToken::String))
3344 return TokError("expected string in '.include' directive");
3346 std::string Filename = getTok().getString();
3347 SMLoc IncludeLoc = getLexer().getLoc();
3350 if (getLexer().isNot(AsmToken::EndOfStatement))
3351 return TokError("unexpected token in '.include' directive");
3353 // Strip the quotes.
3354 Filename = Filename.substr(1, Filename.size()-2);
3356 // Attempt to switch the lexer to the included file before consuming the end
3357 // of statement to avoid losing it when we switch.
3358 if (EnterIncludeFile(Filename)) {
3359 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3366 /// ParseDirectiveIncbin
3367 /// ::= .incbin "filename"
3368 bool AsmParser::ParseDirectiveIncbin() {
3369 if (getLexer().isNot(AsmToken::String))
3370 return TokError("expected string in '.incbin' directive");
3372 std::string Filename = getTok().getString();
3373 SMLoc IncbinLoc = getLexer().getLoc();
3376 if (getLexer().isNot(AsmToken::EndOfStatement))
3377 return TokError("unexpected token in '.incbin' directive");
3379 // Strip the quotes.
3380 Filename = Filename.substr(1, Filename.size()-2);
3382 // Attempt to process the included file.
3383 if (ProcessIncbinFile(Filename)) {
3384 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3391 /// ParseDirectiveIf
3392 /// ::= .if expression
3393 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
3394 TheCondStack.push_back(TheCondState);
3395 TheCondState.TheCond = AsmCond::IfCond;
3396 if (TheCondState.Ignore) {
3397 EatToEndOfStatement();
3400 if (ParseAbsoluteExpression(ExprValue))
3403 if (getLexer().isNot(AsmToken::EndOfStatement))
3404 return TokError("unexpected token in '.if' directive");
3408 TheCondState.CondMet = ExprValue;
3409 TheCondState.Ignore = !TheCondState.CondMet;
3415 /// ParseDirectiveIfb
3417 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3418 TheCondStack.push_back(TheCondState);
3419 TheCondState.TheCond = AsmCond::IfCond;
3421 if (TheCondState.Ignore) {
3422 EatToEndOfStatement();
3424 StringRef Str = ParseStringToEndOfStatement();
3426 if (getLexer().isNot(AsmToken::EndOfStatement))
3427 return TokError("unexpected token in '.ifb' directive");
3431 TheCondState.CondMet = ExpectBlank == Str.empty();
3432 TheCondState.Ignore = !TheCondState.CondMet;
3438 /// ParseDirectiveIfc
3439 /// ::= .ifc string1, string2
3440 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3441 TheCondStack.push_back(TheCondState);
3442 TheCondState.TheCond = AsmCond::IfCond;
3444 if (TheCondState.Ignore) {
3445 EatToEndOfStatement();
3447 StringRef Str1 = ParseStringToComma();
3449 if (getLexer().isNot(AsmToken::Comma))
3450 return TokError("unexpected token in '.ifc' directive");
3454 StringRef Str2 = ParseStringToEndOfStatement();
3456 if (getLexer().isNot(AsmToken::EndOfStatement))
3457 return TokError("unexpected token in '.ifc' directive");
3461 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3462 TheCondState.Ignore = !TheCondState.CondMet;
3468 /// ParseDirectiveIfdef
3469 /// ::= .ifdef symbol
3470 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3472 TheCondStack.push_back(TheCondState);
3473 TheCondState.TheCond = AsmCond::IfCond;
3475 if (TheCondState.Ignore) {
3476 EatToEndOfStatement();
3478 if (ParseIdentifier(Name))
3479 return TokError("expected identifier after '.ifdef'");
3483 MCSymbol *Sym = getContext().LookupSymbol(Name);
3486 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3488 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3489 TheCondState.Ignore = !TheCondState.CondMet;
3495 /// ParseDirectiveElseIf
3496 /// ::= .elseif expression
3497 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3498 if (TheCondState.TheCond != AsmCond::IfCond &&
3499 TheCondState.TheCond != AsmCond::ElseIfCond)
3500 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3502 TheCondState.TheCond = AsmCond::ElseIfCond;
3504 bool LastIgnoreState = false;
3505 if (!TheCondStack.empty())
3506 LastIgnoreState = TheCondStack.back().Ignore;
3507 if (LastIgnoreState || TheCondState.CondMet) {
3508 TheCondState.Ignore = true;
3509 EatToEndOfStatement();
3513 if (ParseAbsoluteExpression(ExprValue))
3516 if (getLexer().isNot(AsmToken::EndOfStatement))
3517 return TokError("unexpected token in '.elseif' directive");
3520 TheCondState.CondMet = ExprValue;
3521 TheCondState.Ignore = !TheCondState.CondMet;
3527 /// ParseDirectiveElse
3529 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
3530 if (getLexer().isNot(AsmToken::EndOfStatement))
3531 return TokError("unexpected token in '.else' directive");
3535 if (TheCondState.TheCond != AsmCond::IfCond &&
3536 TheCondState.TheCond != AsmCond::ElseIfCond)
3537 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3539 TheCondState.TheCond = AsmCond::ElseCond;
3540 bool LastIgnoreState = false;
3541 if (!TheCondStack.empty())
3542 LastIgnoreState = TheCondStack.back().Ignore;
3543 if (LastIgnoreState || TheCondState.CondMet)
3544 TheCondState.Ignore = true;
3546 TheCondState.Ignore = false;
3551 /// ParseDirectiveEndIf
3553 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
3554 if (getLexer().isNot(AsmToken::EndOfStatement))
3555 return TokError("unexpected token in '.endif' directive");
3559 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3560 TheCondStack.empty())
3561 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3563 if (!TheCondStack.empty()) {
3564 TheCondState = TheCondStack.back();
3565 TheCondStack.pop_back();
3571 void AsmParser::initializeDirectiveKindMap() {
3572 DirectiveKindMap[".set"] = DK_SET;
3573 DirectiveKindMap[".equ"] = DK_EQU;
3574 DirectiveKindMap[".equiv"] = DK_EQUIV;
3575 DirectiveKindMap[".ascii"] = DK_ASCII;
3576 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3577 DirectiveKindMap[".string"] = DK_STRING;
3578 DirectiveKindMap[".byte"] = DK_BYTE;
3579 DirectiveKindMap[".short"] = DK_SHORT;
3580 DirectiveKindMap[".value"] = DK_VALUE;
3581 DirectiveKindMap[".2byte"] = DK_2BYTE;
3582 DirectiveKindMap[".long"] = DK_LONG;
3583 DirectiveKindMap[".int"] = DK_INT;
3584 DirectiveKindMap[".4byte"] = DK_4BYTE;
3585 DirectiveKindMap[".quad"] = DK_QUAD;
3586 DirectiveKindMap[".8byte"] = DK_8BYTE;
3587 DirectiveKindMap[".single"] = DK_SINGLE;
3588 DirectiveKindMap[".float"] = DK_FLOAT;
3589 DirectiveKindMap[".double"] = DK_DOUBLE;
3590 DirectiveKindMap[".align"] = DK_ALIGN;
3591 DirectiveKindMap[".align32"] = DK_ALIGN32;
3592 DirectiveKindMap[".balign"] = DK_BALIGN;
3593 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3594 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3595 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3596 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3597 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3598 DirectiveKindMap[".org"] = DK_ORG;
3599 DirectiveKindMap[".fill"] = DK_FILL;
3600 DirectiveKindMap[".zero"] = DK_ZERO;
3601 DirectiveKindMap[".extern"] = DK_EXTERN;
3602 DirectiveKindMap[".globl"] = DK_GLOBL;
3603 DirectiveKindMap[".global"] = DK_GLOBAL;
3604 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3605 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3606 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3607 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3608 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3609 DirectiveKindMap[".reference"] = DK_REFERENCE;
3610 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3611 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3612 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3613 DirectiveKindMap[".comm"] = DK_COMM;
3614 DirectiveKindMap[".common"] = DK_COMMON;
3615 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3616 DirectiveKindMap[".abort"] = DK_ABORT;
3617 DirectiveKindMap[".include"] = DK_INCLUDE;
3618 DirectiveKindMap[".incbin"] = DK_INCBIN;
3619 DirectiveKindMap[".code16"] = DK_CODE16;
3620 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3621 DirectiveKindMap[".rept"] = DK_REPT;
3622 DirectiveKindMap[".irp"] = DK_IRP;
3623 DirectiveKindMap[".irpc"] = DK_IRPC;
3624 DirectiveKindMap[".endr"] = DK_ENDR;
3625 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3626 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3627 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3628 DirectiveKindMap[".if"] = DK_IF;
3629 DirectiveKindMap[".ifb"] = DK_IFB;
3630 DirectiveKindMap[".ifnb"] = DK_IFNB;
3631 DirectiveKindMap[".ifc"] = DK_IFC;
3632 DirectiveKindMap[".ifnc"] = DK_IFNC;
3633 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3634 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3635 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3636 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3637 DirectiveKindMap[".else"] = DK_ELSE;
3638 DirectiveKindMap[".endif"] = DK_ENDIF;
3639 DirectiveKindMap[".skip"] = DK_SKIP;
3640 DirectiveKindMap[".space"] = DK_SPACE;
3641 DirectiveKindMap[".file"] = DK_FILE;
3642 DirectiveKindMap[".line"] = DK_LINE;
3643 DirectiveKindMap[".loc"] = DK_LOC;
3644 DirectiveKindMap[".stabs"] = DK_STABS;
3645 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3646 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3647 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3648 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3649 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3650 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3651 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3652 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3653 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3654 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3655 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3656 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3657 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3658 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3659 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3660 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3661 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3662 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3663 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3664 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3665 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3666 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3667 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3668 DirectiveKindMap[".macro"] = DK_MACRO;
3669 DirectiveKindMap[".endm"] = DK_ENDM;
3670 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3671 DirectiveKindMap[".purgem"] = DK_PURGEM;
3675 MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3676 AsmToken EndToken, StartToken = getTok();
3678 unsigned NestLevel = 0;
3680 // Check whether we have reached the end of the file.
3681 if (getLexer().is(AsmToken::Eof)) {
3682 Error(DirectiveLoc, "no matching '.endr' in definition");
3686 if (Lexer.is(AsmToken::Identifier) &&
3687 (getTok().getIdentifier() == ".rept")) {
3691 // Otherwise, check whether we have reached the .endr.
3692 if (Lexer.is(AsmToken::Identifier) &&
3693 getTok().getIdentifier() == ".endr") {
3694 if (NestLevel == 0) {
3695 EndToken = getTok();
3697 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3698 TokError("unexpected token in '.endr' directive");
3706 // Otherwise, scan till the end of the statement.
3707 EatToEndOfStatement();
3710 const char *BodyStart = StartToken.getLoc().getPointer();
3711 const char *BodyEnd = EndToken.getLoc().getPointer();
3712 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3714 // We Are Anonymous.
3716 MCAsmMacroParameters Parameters;
3717 return new MCAsmMacro(Name, Body, Parameters);
3720 void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3721 raw_svector_ostream &OS) {
3724 MemoryBuffer *Instantiation =
3725 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3727 // Create the macro instantiation object and add to the current macro
3728 // instantiation stack.
3729 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3733 ActiveMacros.push_back(MI);
3735 // Jump to the macro instantiation and prime the lexer.
3736 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3737 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3741 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3743 if (ParseAbsoluteExpression(Count))
3744 return TokError("unexpected token in '.rept' directive");
3747 return TokError("Count is negative");
3749 if (Lexer.isNot(AsmToken::EndOfStatement))
3750 return TokError("unexpected token in '.rept' directive");
3752 // Eat the end of statement.
3755 // Lex the rept definition.
3756 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3760 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3761 // to hold the macro body with substitutions.
3762 SmallString<256> Buf;
3763 MCAsmMacroParameters Parameters;
3764 MCAsmMacroArguments A;
3765 raw_svector_ostream OS(Buf);
3767 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3770 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3775 /// ParseDirectiveIrp
3776 /// ::= .irp symbol,values
3777 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3778 MCAsmMacroParameters Parameters;
3779 MCAsmMacroParameter Parameter;
3781 if (ParseIdentifier(Parameter.first))
3782 return TokError("expected identifier in '.irp' directive");
3784 Parameters.push_back(Parameter);
3786 if (Lexer.isNot(AsmToken::Comma))
3787 return TokError("expected comma in '.irp' directive");
3791 MCAsmMacroArguments A;
3792 if (ParseMacroArguments(0, A))
3795 // Eat the end of statement.
3798 // Lex the irp definition.
3799 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3803 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3804 // to hold the macro body with substitutions.
3805 SmallString<256> Buf;
3806 raw_svector_ostream OS(Buf);
3808 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3809 MCAsmMacroArguments Args;
3812 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3816 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3821 /// ParseDirectiveIrpc
3822 /// ::= .irpc symbol,values
3823 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3824 MCAsmMacroParameters Parameters;
3825 MCAsmMacroParameter Parameter;
3827 if (ParseIdentifier(Parameter.first))
3828 return TokError("expected identifier in '.irpc' directive");
3830 Parameters.push_back(Parameter);
3832 if (Lexer.isNot(AsmToken::Comma))
3833 return TokError("expected comma in '.irpc' directive");
3837 MCAsmMacroArguments A;
3838 if (ParseMacroArguments(0, A))
3841 if (A.size() != 1 || A.front().size() != 1)
3842 return TokError("unexpected token in '.irpc' directive");
3844 // Eat the end of statement.
3847 // Lex the irpc definition.
3848 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3852 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3853 // to hold the macro body with substitutions.
3854 SmallString<256> Buf;
3855 raw_svector_ostream OS(Buf);
3857 StringRef Values = A.front().front().getString();
3858 std::size_t I, End = Values.size();
3859 for (I = 0; I < End; ++I) {
3860 MCAsmMacroArgument Arg;
3861 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3863 MCAsmMacroArguments Args;
3864 Args.push_back(Arg);
3866 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3870 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3875 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3876 if (ActiveMacros.empty())
3877 return TokError("unmatched '.endr' directive");
3879 // The only .repl that should get here are the ones created by
3880 // InstantiateMacroLikeBody.
3881 assert(getLexer().is(AsmToken::EndOfStatement));
3887 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3888 const MCExpr *Value;
3889 SMLoc ExprLoc = getLexer().getLoc();
3890 if (ParseExpression(Value))
3892 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3894 return Error(ExprLoc, "unexpected expression in _emit");
3895 uint64_t IntValue = MCE->getValue();
3896 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3897 return Error(ExprLoc, "literal value out of range for directive");
3899 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3903 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3904 unsigned &NumOutputs, unsigned &NumInputs,
3905 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
3906 SmallVectorImpl<std::string> &Constraints,
3907 SmallVectorImpl<std::string> &Clobbers,
3908 const MCInstrInfo *MII,
3909 const MCInstPrinter *IP,
3910 MCAsmParserSemaCallback &SI) {
3911 SmallVector<void *, 4> InputDecls;
3912 SmallVector<void *, 4> OutputDecls;
3913 SmallVector<bool, 4> InputDeclsAddressOf;
3914 SmallVector<bool, 4> OutputDeclsAddressOf;
3915 SmallVector<std::string, 4> InputConstraints;
3916 SmallVector<std::string, 4> OutputConstraints;
3917 std::set<std::string> ClobberRegs;
3919 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3924 // While we have input, parse each statement.
3925 unsigned InputIdx = 0;
3926 unsigned OutputIdx = 0;
3927 while (getLexer().isNot(AsmToken::Eof)) {
3928 ParseStatementInfo Info(&AsmStrRewrites);
3929 if (ParseStatement(Info))
3932 if (Info.ParseError)
3935 if (Info.Opcode != ~0U) {
3936 const MCInstrDesc &Desc = MII->get(Info.Opcode);
3938 // Build the list of clobbers, outputs and inputs.
3939 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3940 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
3943 if (Operand->isImm()) {
3944 if (Operand->needAsmRewrite())
3945 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3946 Operand->getStartLoc()));
3950 // Register operand.
3951 if (Operand->isReg() && !Operand->needAddressOf()) {
3952 unsigned NumDefs = Desc.getNumDefs();
3954 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3956 raw_string_ostream OS(Reg);
3957 IP->printRegName(OS, Operand->getReg());
3958 ClobberRegs.insert(StringRef(OS.str()));
3963 // Expr/Input or Output.
3966 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3969 bool isOutput = (i == 1) && Desc.mayStore();
3970 if (Operand->isMem() && Operand->needSizeDirective())
3971 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3972 Operand->getStartLoc(),
3974 Operand->getMemSize()));
3976 std::string Constraint = "=";
3978 OutputDecls.push_back(OpDecl);
3979 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
3980 Constraint += Operand->getConstraint().str();
3981 OutputConstraints.push_back(Constraint);
3982 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3983 Operand->getStartLoc(),
3984 Operand->getNameLen()));
3986 InputDecls.push_back(OpDecl);
3987 InputDeclsAddressOf.push_back(Operand->needAddressOf());
3988 InputConstraints.push_back(Operand->getConstraint().str());
3989 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3990 Operand->getStartLoc(),
3991 Operand->getNameLen()));
3998 // Set the number of Outputs and Inputs.
3999 NumOutputs = OutputDecls.size();
4000 NumInputs = InputDecls.size();
4002 // Set the unique clobbers.
4003 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
4004 E = ClobberRegs.end(); I != E; ++I)
4005 Clobbers.push_back(*I);
4007 // Merge the various outputs and inputs. Output are expected first.
4008 if (NumOutputs || NumInputs) {
4009 unsigned NumExprs = NumOutputs + NumInputs;
4010 OpDecls.resize(NumExprs);
4011 Constraints.resize(NumExprs);
4012 for (unsigned i = 0; i < NumOutputs; ++i) {
4013 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4014 Constraints[i] = OutputConstraints[i];
4016 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4017 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4018 Constraints[j] = InputConstraints[i];
4022 // Build the IR assembly string.
4023 std::string AsmStringIR;
4024 AsmRewriteKind PrevKind = AOK_Imm;
4025 raw_string_ostream OS(AsmStringIR);
4026 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4027 for (SmallVectorImpl<struct AsmRewrite>::iterator
4028 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
4029 const char *Loc = (*I).Loc.getPointer();
4031 AsmRewriteKind Kind = (*I).Kind;
4033 // Emit everything up to the immediate/expression. If the previous rewrite
4034 // was a size directive, then this has already been done.
4035 if (PrevKind != AOK_SizeDirective)
4036 OS << StringRef(Start, Loc - Start);
4039 // Skip the original expression.
4040 if (Kind == AOK_Skip) {
4041 Start = Loc + (*I).Len;
4045 // Rewrite expressions in $N notation.
4063 case AOK_SizeDirective:
4066 case 8: OS << "byte ptr "; break;
4067 case 16: OS << "word ptr "; break;
4068 case 32: OS << "dword ptr "; break;
4069 case 64: OS << "qword ptr "; break;
4070 case 80: OS << "xword ptr "; break;
4071 case 128: OS << "xmmword ptr "; break;
4072 case 256: OS << "ymmword ptr "; break;
4078 case AOK_DotOperator:
4083 // Skip the original expression.
4084 if (Kind != AOK_SizeDirective)
4085 Start = Loc + (*I).Len;
4088 // Emit the remainder of the asm string.
4089 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4090 if (Start != AsmEnd)
4091 OS << StringRef(Start, AsmEnd - Start);
4093 AsmString = OS.str();
4097 /// \brief Create an MCAsmParser instance.
4098 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4099 MCContext &C, MCStreamer &Out,
4100 const MCAsmInfo &MAI) {
4101 return new AsmParser(SM, C, Out, MAI);