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 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
241 MCAsmMacroParameters Parameters);
242 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
243 const MCAsmMacroParameters &Parameters,
244 const MCAsmMacroArguments &A,
247 /// \brief Are macros enabled in the parser?
248 bool MacrosEnabled() {return MacrosEnabledFlag;}
250 /// \brief Control a flag in the parser that enables or disables macros.
251 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
253 /// \brief Lookup a previously defined macro.
254 /// \param Name Macro name.
255 /// \returns Pointer to macro. NULL if no such macro was defined.
256 const MCAsmMacro* LookupMacro(StringRef Name);
258 /// \brief Define a new macro with the given name and information.
259 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
261 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
262 void UndefineMacro(StringRef Name);
264 /// \brief Are we inside a macro instantiation?
265 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
267 /// \brief Handle entry to macro instantiation.
269 /// \param M The macro.
270 /// \param NameLoc Instantiation location.
271 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
273 /// \brief Handle exit from macro instantiation.
274 void HandleMacroExit();
276 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
277 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
278 /// correct delimiter by the method.
279 bool ParseMacroArgument(MCAsmMacroArgument &MA,
280 AsmToken::TokenKind &ArgumentDelimiter);
282 /// \brief Parse all macro arguments for a given macro.
283 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
285 void PrintMacroInstantiations();
286 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
287 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
288 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
290 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
292 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
293 bool EnterIncludeFile(const std::string &Filename);
294 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
295 /// This returns true on failure.
296 bool ProcessIncbinFile(const std::string &Filename);
298 /// \brief Reset the current lexer position to that given by \p Loc. The
299 /// current token is not set; clients should ensure Lex() is called
302 /// \param InBuffer If not -1, should be the known buffer id that contains the
304 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
306 /// \brief Parse up to the end of statement and a return the contents from the
307 /// current token until the end of the statement; the current token on exit
308 /// will be either the EndOfStatement or EOF.
309 virtual StringRef ParseStringToEndOfStatement();
311 /// \brief Parse until the end of a statement or a comma is encountered,
312 /// return the contents from the current token up to the end or comma.
313 StringRef ParseStringToComma();
315 bool ParseAssignment(StringRef Name, bool allow_redef,
316 bool NoDeadStrip = false);
318 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
319 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
320 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
321 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
323 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
325 // Generic (target and platform independent) directive parsing.
327 DK_NO_DIRECTIVE, // Placeholder
328 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
329 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
330 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
331 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
332 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
333 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
334 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
335 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
336 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
337 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
338 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
339 DK_ELSEIF, DK_ELSE, DK_ENDIF,
340 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
341 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
342 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
343 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
344 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
345 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
347 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
348 DK_SLEB128, DK_ULEB128
351 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
352 /// directives parsed by this class.
353 StringMap<DirectiveKind> DirectiveKindMap;
355 // ".ascii", ".asciz", ".string"
356 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
357 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
358 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
359 bool ParseDirectiveFill(); // ".fill"
360 bool ParseDirectiveZero(); // ".zero"
361 // ".set", ".equ", ".equiv"
362 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
363 bool ParseDirectiveOrg(); // ".org"
364 // ".align{,32}", ".p2align{,w,l}"
365 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
367 // ".file", ".line", ".loc", ".stabs"
368 bool ParseDirectiveFile(SMLoc DirectiveLoc);
369 bool ParseDirectiveLine();
370 bool ParseDirectiveLoc();
371 bool ParseDirectiveStabs();
374 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
375 bool ParseDirectiveCFISections();
376 bool ParseDirectiveCFIStartProc();
377 bool ParseDirectiveCFIEndProc();
378 bool ParseDirectiveCFIDefCfaOffset();
379 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
380 bool ParseDirectiveCFIAdjustCfaOffset();
381 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
383 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
385 bool ParseDirectiveCFIRememberState();
386 bool ParseDirectiveCFIRestoreState();
387 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
388 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
389 bool ParseDirectiveCFIEscape();
390 bool ParseDirectiveCFISignalFrame();
391 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
394 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
395 bool ParseDirectiveEndMacro(StringRef Directive);
396 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
397 bool ParseDirectiveMacrosOnOff(StringRef Directive);
399 // ".bundle_align_mode"
400 bool ParseDirectiveBundleAlignMode();
402 bool ParseDirectiveBundleLock();
404 bool ParseDirectiveBundleUnlock();
407 bool ParseDirectiveSpace(StringRef IDVal);
409 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
410 bool ParseDirectiveLEB128(bool Signed);
412 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
413 /// accepts a single symbol (which should be a label or an external).
414 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
416 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
418 bool ParseDirectiveAbort(); // ".abort"
419 bool ParseDirectiveInclude(); // ".include"
420 bool ParseDirectiveIncbin(); // ".incbin"
422 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
423 // ".ifb" or ".ifnb", depending on ExpectBlank.
424 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
425 // ".ifc" or ".ifnc", depending on ExpectEqual.
426 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
427 // ".ifdef" or ".ifndef", depending on expect_defined
428 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
429 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
430 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
431 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
432 virtual bool ParseEscapedString(std::string &Data);
434 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
435 MCSymbolRefExpr::VariantKind Variant);
437 // Macro-like directives
438 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
439 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
440 raw_svector_ostream &OS);
441 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
442 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
443 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
444 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
447 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
449 void initializeDirectiveKindMap();
455 extern MCAsmParserExtension *createDarwinAsmParser();
456 extern MCAsmParserExtension *createELFAsmParser();
457 extern MCAsmParserExtension *createCOFFAsmParser();
461 enum { DEFAULT_ADDRSPACE = 0 };
463 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
464 MCStreamer &_Out, const MCAsmInfo &_MAI)
465 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
467 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
468 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
469 // Save the old handler.
470 SavedDiagHandler = SrcMgr.getDiagHandler();
471 SavedDiagContext = SrcMgr.getDiagContext();
472 // Set our own handler which calls the saved handler.
473 SrcMgr.setDiagHandler(DiagHandler, this);
474 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
476 // Initialize the platform / file format parser.
478 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
480 if (_MAI.hasMicrosoftFastStdCallMangling()) {
481 PlatformParser = createCOFFAsmParser();
482 PlatformParser->Initialize(*this);
483 } else if (_MAI.hasSubsectionsViaSymbols()) {
484 PlatformParser = createDarwinAsmParser();
485 PlatformParser->Initialize(*this);
488 PlatformParser = createELFAsmParser();
489 PlatformParser->Initialize(*this);
492 initializeDirectiveKindMap();
495 AsmParser::~AsmParser() {
496 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
498 // Destroy any macros.
499 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
500 ie = MacroMap.end(); it != ie; ++it)
501 delete it->getValue();
503 delete PlatformParser;
506 void AsmParser::PrintMacroInstantiations() {
507 // Print the active macro instantiation stack.
508 for (std::vector<MacroInstantiation*>::const_reverse_iterator
509 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
510 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
511 "while in macro instantiation");
514 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
515 if (FatalAssemblerWarnings)
516 return Error(L, Msg, Ranges);
517 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
518 PrintMacroInstantiations();
522 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
524 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
525 PrintMacroInstantiations();
529 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
530 std::string IncludedFile;
531 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
537 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
542 /// Process the specified .incbin file by seaching for it in the include paths
543 /// then just emitting the byte contents of the file to the streamer. This
544 /// returns true on failure.
545 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
546 std::string IncludedFile;
547 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
551 // Pick up the bytes from the file and emit them.
552 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
557 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
558 if (InBuffer != -1) {
559 CurBuffer = InBuffer;
561 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
563 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
566 const AsmToken &AsmParser::Lex() {
567 const AsmToken *tok = &Lexer.Lex();
569 if (tok->is(AsmToken::Eof)) {
570 // If this is the end of an included file, pop the parent file off the
572 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
573 if (ParentIncludeLoc != SMLoc()) {
574 JumpToLoc(ParentIncludeLoc);
579 if (tok->is(AsmToken::Error))
580 Error(Lexer.getErrLoc(), Lexer.getErr());
585 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
586 // Create the initial section, if requested.
587 if (!NoInitialTextSection)
594 AsmCond StartingCondState = TheCondState;
596 // If we are generating dwarf for assembly source files save the initial text
597 // section and generate a .file directive.
598 if (getContext().getGenDwarfForAssembly()) {
599 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
600 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
601 getStreamer().EmitLabel(SectionStartSym);
602 getContext().setGenDwarfSectionStartSym(SectionStartSym);
603 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
605 getContext().getMainFileName());
608 // While we have input, parse each statement.
609 while (Lexer.isNot(AsmToken::Eof)) {
610 ParseStatementInfo Info;
611 if (!ParseStatement(Info)) continue;
613 // We had an error, validate that one was emitted and recover by skipping to
615 assert(HadError && "Parse statement returned an error, but none emitted!");
616 EatToEndOfStatement();
619 if (TheCondState.TheCond != StartingCondState.TheCond ||
620 TheCondState.Ignore != StartingCondState.Ignore)
621 return TokError("unmatched .ifs or .elses");
623 // Check to see there are no empty DwarfFile slots.
624 const std::vector<MCDwarfFile *> &MCDwarfFiles =
625 getContext().getMCDwarfFiles();
626 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
627 if (!MCDwarfFiles[i])
628 TokError("unassigned file number: " + Twine(i) + " for .file directives");
631 // Check to see that all assembler local symbols were actually defined.
632 // Targets that don't do subsections via symbols may not want this, though,
633 // so conservatively exclude them. Only do this if we're finalizing, though,
634 // as otherwise we won't necessarilly have seen everything yet.
635 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
636 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
637 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
640 MCSymbol *Sym = i->getValue();
641 // Variable symbols may not be marked as defined, so check those
642 // explicitly. If we know it's a variable, we have a definition for
643 // the purposes of this check.
644 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
645 // FIXME: We would really like to refer back to where the symbol was
646 // first referenced for a source location. We need to add something
647 // to track that. Currently, we just point to the end of the file.
648 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
649 "assembler local symbol '" + Sym->getName() +
655 // Finalize the output stream if there are no errors and if the client wants
657 if (!HadError && !NoFinalize)
663 void AsmParser::CheckForValidSection() {
664 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
665 TokError("expected section directive before assembly directive");
666 Out.InitToTextSection();
670 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
671 void AsmParser::EatToEndOfStatement() {
672 while (Lexer.isNot(AsmToken::EndOfStatement) &&
673 Lexer.isNot(AsmToken::Eof))
677 if (Lexer.is(AsmToken::EndOfStatement))
681 StringRef AsmParser::ParseStringToEndOfStatement() {
682 const char *Start = getTok().getLoc().getPointer();
684 while (Lexer.isNot(AsmToken::EndOfStatement) &&
685 Lexer.isNot(AsmToken::Eof))
688 const char *End = getTok().getLoc().getPointer();
689 return StringRef(Start, End - Start);
692 StringRef AsmParser::ParseStringToComma() {
693 const char *Start = getTok().getLoc().getPointer();
695 while (Lexer.isNot(AsmToken::EndOfStatement) &&
696 Lexer.isNot(AsmToken::Comma) &&
697 Lexer.isNot(AsmToken::Eof))
700 const char *End = getTok().getLoc().getPointer();
701 return StringRef(Start, End - Start);
704 /// ParseParenExpr - Parse a paren expression and return it.
705 /// NOTE: This assumes the leading '(' has already been consumed.
707 /// parenexpr ::= expr)
709 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
710 if (ParseExpression(Res)) return true;
711 if (Lexer.isNot(AsmToken::RParen))
712 return TokError("expected ')' in parentheses expression");
713 EndLoc = Lexer.getTok().getEndLoc();
718 /// ParseBracketExpr - Parse a bracket expression and return it.
719 /// NOTE: This assumes the leading '[' has already been consumed.
721 /// bracketexpr ::= expr]
723 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
724 if (ParseExpression(Res)) return true;
725 if (Lexer.isNot(AsmToken::RBrac))
726 return TokError("expected ']' in brackets expression");
727 EndLoc = Lexer.getTok().getEndLoc();
732 /// ParsePrimaryExpr - Parse a primary expression and return it.
733 /// primaryexpr ::= (parenexpr
734 /// primaryexpr ::= symbol
735 /// primaryexpr ::= number
736 /// primaryexpr ::= '.'
737 /// primaryexpr ::= ~,+,- primaryexpr
738 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
739 SMLoc FirstTokenLoc = getLexer().getLoc();
740 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
741 switch (FirstTokenKind) {
743 return TokError("unknown token in expression");
744 // If we have an error assume that we've already handled it.
745 case AsmToken::Error:
747 case AsmToken::Exclaim:
748 Lex(); // Eat the operator.
749 if (ParsePrimaryExpr(Res, EndLoc))
751 Res = MCUnaryExpr::CreateLNot(Res, getContext());
753 case AsmToken::Dollar:
754 case AsmToken::String:
755 case AsmToken::Identifier: {
756 StringRef Identifier;
757 if (ParseIdentifier(Identifier)) {
758 if (FirstTokenKind == AsmToken::Dollar)
759 return Error(FirstTokenLoc, "invalid token in expression");
763 EndLoc = SMLoc::getFromPointer(Identifier.end());
765 // This is a symbol reference.
766 std::pair<StringRef, StringRef> Split = Identifier.split('@');
767 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
769 // Lookup the symbol variant if used.
770 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
771 if (Split.first.size() != Identifier.size()) {
772 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
773 if (Variant == MCSymbolRefExpr::VK_Invalid) {
774 Variant = MCSymbolRefExpr::VK_None;
775 return TokError("invalid variant '" + Split.second + "'");
779 // If this is an absolute variable reference, substitute it now to preserve
780 // semantics in the face of reassignment.
781 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
783 return Error(EndLoc, "unexpected modifier on variable reference");
785 Res = Sym->getVariableValue();
789 // Otherwise create a symbol ref.
790 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
793 case AsmToken::Integer: {
794 SMLoc Loc = getTok().getLoc();
795 int64_t IntVal = getTok().getIntVal();
796 Res = MCConstantExpr::Create(IntVal, getContext());
797 EndLoc = Lexer.getTok().getEndLoc();
799 // Look for 'b' or 'f' following an Integer as a directional label
800 if (Lexer.getKind() == AsmToken::Identifier) {
801 StringRef IDVal = getTok().getString();
802 if (IDVal == "f" || IDVal == "b"){
803 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
804 IDVal == "f" ? 1 : 0);
805 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
807 if (IDVal == "b" && Sym->isUndefined())
808 return Error(Loc, "invalid reference to undefined symbol");
809 EndLoc = Lexer.getTok().getEndLoc();
810 Lex(); // Eat identifier.
815 case AsmToken::Real: {
816 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
817 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
818 Res = MCConstantExpr::Create(IntVal, getContext());
819 EndLoc = Lexer.getTok().getEndLoc();
823 case AsmToken::Dot: {
824 // This is a '.' reference, which references the current PC. Emit a
825 // temporary label to the streamer and refer to it.
826 MCSymbol *Sym = Ctx.CreateTempSymbol();
828 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
829 EndLoc = Lexer.getTok().getEndLoc();
830 Lex(); // Eat identifier.
833 case AsmToken::LParen:
834 Lex(); // Eat the '('.
835 return ParseParenExpr(Res, EndLoc);
836 case AsmToken::LBrac:
837 if (!PlatformParser->HasBracketExpressions())
838 return TokError("brackets expression not supported on this target");
839 Lex(); // Eat the '['.
840 return ParseBracketExpr(Res, EndLoc);
841 case AsmToken::Minus:
842 Lex(); // Eat the operator.
843 if (ParsePrimaryExpr(Res, EndLoc))
845 Res = MCUnaryExpr::CreateMinus(Res, getContext());
848 Lex(); // Eat the operator.
849 if (ParsePrimaryExpr(Res, EndLoc))
851 Res = MCUnaryExpr::CreatePlus(Res, getContext());
853 case AsmToken::Tilde:
854 Lex(); // Eat the operator.
855 if (ParsePrimaryExpr(Res, EndLoc))
857 Res = MCUnaryExpr::CreateNot(Res, getContext());
862 bool AsmParser::ParseExpression(const MCExpr *&Res) {
864 return ParseExpression(Res, EndLoc);
868 AsmParser::ApplyModifierToExpr(const MCExpr *E,
869 MCSymbolRefExpr::VariantKind Variant) {
870 // Recurse over the given expression, rebuilding it to apply the given variant
871 // if there is exactly one symbol.
872 switch (E->getKind()) {
874 case MCExpr::Constant:
877 case MCExpr::SymbolRef: {
878 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
880 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
881 TokError("invalid variant on expression '" +
882 getTok().getIdentifier() + "' (already modified)");
886 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
889 case MCExpr::Unary: {
890 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
891 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
894 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
897 case MCExpr::Binary: {
898 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
899 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
900 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
905 if (!LHS) LHS = BE->getLHS();
906 if (!RHS) RHS = BE->getRHS();
908 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
912 llvm_unreachable("Invalid expression kind!");
915 /// ParseExpression - Parse an expression and return it.
917 /// expr ::= expr &&,|| expr -> lowest.
918 /// expr ::= expr |,^,&,! expr
919 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
920 /// expr ::= expr <<,>> expr
921 /// expr ::= expr +,- expr
922 /// expr ::= expr *,/,% expr -> highest.
923 /// expr ::= primaryexpr
925 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
926 // Parse the expression.
928 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
931 // As a special case, we support 'a op b @ modifier' by rewriting the
932 // expression to include the modifier. This is inefficient, but in general we
933 // expect users to use 'a@modifier op b'.
934 if (Lexer.getKind() == AsmToken::At) {
937 if (Lexer.isNot(AsmToken::Identifier))
938 return TokError("unexpected symbol modifier following '@'");
940 MCSymbolRefExpr::VariantKind Variant =
941 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
942 if (Variant == MCSymbolRefExpr::VK_Invalid)
943 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
945 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
947 return TokError("invalid modifier '" + getTok().getIdentifier() +
948 "' (no symbols present)");
955 // Try to constant fold it up front, if possible.
957 if (Res->EvaluateAsAbsolute(Value))
958 Res = MCConstantExpr::Create(Value, getContext());
963 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
965 return ParseParenExpr(Res, EndLoc) ||
966 ParseBinOpRHS(1, Res, EndLoc);
969 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
972 SMLoc StartLoc = Lexer.getLoc();
973 if (ParseExpression(Expr))
976 if (!Expr->EvaluateAsAbsolute(Res))
977 return Error(StartLoc, "expected absolute expression");
982 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
983 MCBinaryExpr::Opcode &Kind) {
986 return 0; // not a binop.
988 // Lowest Precedence: &&, ||
989 case AsmToken::AmpAmp:
990 Kind = MCBinaryExpr::LAnd;
992 case AsmToken::PipePipe:
993 Kind = MCBinaryExpr::LOr;
997 // Low Precedence: |, &, ^
999 // FIXME: gas seems to support '!' as an infix operator?
1000 case AsmToken::Pipe:
1001 Kind = MCBinaryExpr::Or;
1003 case AsmToken::Caret:
1004 Kind = MCBinaryExpr::Xor;
1007 Kind = MCBinaryExpr::And;
1010 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1011 case AsmToken::EqualEqual:
1012 Kind = MCBinaryExpr::EQ;
1014 case AsmToken::ExclaimEqual:
1015 case AsmToken::LessGreater:
1016 Kind = MCBinaryExpr::NE;
1018 case AsmToken::Less:
1019 Kind = MCBinaryExpr::LT;
1021 case AsmToken::LessEqual:
1022 Kind = MCBinaryExpr::LTE;
1024 case AsmToken::Greater:
1025 Kind = MCBinaryExpr::GT;
1027 case AsmToken::GreaterEqual:
1028 Kind = MCBinaryExpr::GTE;
1031 // Intermediate Precedence: <<, >>
1032 case AsmToken::LessLess:
1033 Kind = MCBinaryExpr::Shl;
1035 case AsmToken::GreaterGreater:
1036 Kind = MCBinaryExpr::Shr;
1039 // High Intermediate Precedence: +, -
1040 case AsmToken::Plus:
1041 Kind = MCBinaryExpr::Add;
1043 case AsmToken::Minus:
1044 Kind = MCBinaryExpr::Sub;
1047 // Highest Precedence: *, /, %
1048 case AsmToken::Star:
1049 Kind = MCBinaryExpr::Mul;
1051 case AsmToken::Slash:
1052 Kind = MCBinaryExpr::Div;
1054 case AsmToken::Percent:
1055 Kind = MCBinaryExpr::Mod;
1061 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1062 /// Res contains the LHS of the expression on input.
1063 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1066 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1067 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1069 // If the next token is lower precedence than we are allowed to eat, return
1070 // successfully with what we ate already.
1071 if (TokPrec < Precedence)
1076 // Eat the next primary expression.
1078 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1080 // If BinOp binds less tightly with RHS than the operator after RHS, let
1081 // the pending operator take RHS as its LHS.
1082 MCBinaryExpr::Opcode Dummy;
1083 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1084 if (TokPrec < NextTokPrec) {
1085 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1088 // Merge LHS and RHS according to operator.
1089 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1094 /// ::= EndOfStatement
1095 /// ::= Label* Directive ...Operands... EndOfStatement
1096 /// ::= Label* Identifier OperandList* EndOfStatement
1097 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1098 if (Lexer.is(AsmToken::EndOfStatement)) {
1104 // Statements always start with an identifier or are a full line comment.
1105 AsmToken ID = getTok();
1106 SMLoc IDLoc = ID.getLoc();
1108 int64_t LocalLabelVal = -1;
1109 // A full line comment is a '#' as the first token.
1110 if (Lexer.is(AsmToken::Hash))
1111 return ParseCppHashLineFilenameComment(IDLoc);
1113 // Allow an integer followed by a ':' as a directional local label.
1114 if (Lexer.is(AsmToken::Integer)) {
1115 LocalLabelVal = getTok().getIntVal();
1116 if (LocalLabelVal < 0) {
1117 if (!TheCondState.Ignore)
1118 return TokError("unexpected token at start of statement");
1121 IDVal = getTok().getString();
1122 Lex(); // Consume the integer token to be used as an identifier token.
1123 if (Lexer.getKind() != AsmToken::Colon) {
1124 if (!TheCondState.Ignore)
1125 return TokError("unexpected token at start of statement");
1128 } else if (Lexer.is(AsmToken::Dot)) {
1129 // Treat '.' as a valid identifier in this context.
1132 } else if (ParseIdentifier(IDVal)) {
1133 if (!TheCondState.Ignore)
1134 return TokError("unexpected token at start of statement");
1138 // Handle conditional assembly here before checking for skipping. We
1139 // have to do this so that .endif isn't skipped in a ".if 0" block for
1141 StringMap<DirectiveKind>::const_iterator DirKindIt =
1142 DirectiveKindMap.find(IDVal);
1143 DirectiveKind DirKind =
1144 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1145 DirKindIt->getValue();
1150 return ParseDirectiveIf(IDLoc);
1152 return ParseDirectiveIfb(IDLoc, true);
1154 return ParseDirectiveIfb(IDLoc, false);
1156 return ParseDirectiveIfc(IDLoc, true);
1158 return ParseDirectiveIfc(IDLoc, false);
1160 return ParseDirectiveIfdef(IDLoc, true);
1163 return ParseDirectiveIfdef(IDLoc, false);
1165 return ParseDirectiveElseIf(IDLoc);
1167 return ParseDirectiveElse(IDLoc);
1169 return ParseDirectiveEndIf(IDLoc);
1172 // Ignore the statement if in the middle of inactive conditional
1174 if (TheCondState.Ignore) {
1175 EatToEndOfStatement();
1179 // FIXME: Recurse on local labels?
1181 // See what kind of statement we have.
1182 switch (Lexer.getKind()) {
1183 case AsmToken::Colon: {
1184 CheckForValidSection();
1186 // identifier ':' -> Label.
1189 // Diagnose attempt to use '.' as a label.
1191 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1193 // Diagnose attempt to use a variable as a label.
1195 // FIXME: Diagnostics. Note the location of the definition as a label.
1196 // FIXME: This doesn't diagnose assignment to a symbol which has been
1197 // implicitly marked as external.
1199 if (LocalLabelVal == -1)
1200 Sym = getContext().GetOrCreateSymbol(IDVal);
1202 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1203 if (!Sym->isUndefined() || Sym->isVariable())
1204 return Error(IDLoc, "invalid symbol redefinition");
1207 if (!ParsingInlineAsm)
1210 // If we are generating dwarf for assembly source files then gather the
1211 // info to make a dwarf label entry for this label if needed.
1212 if (getContext().getGenDwarfForAssembly())
1213 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1216 // Consume any end of statement token, if present, to avoid spurious
1217 // AddBlankLine calls().
1218 if (Lexer.is(AsmToken::EndOfStatement)) {
1220 if (Lexer.is(AsmToken::Eof))
1227 case AsmToken::Equal:
1228 // identifier '=' ... -> assignment statement
1231 return ParseAssignment(IDVal, true);
1233 default: // Normal instruction or directive.
1237 // If macros are enabled, check to see if this is a macro instantiation.
1238 if (MacrosEnabled())
1239 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1240 return HandleMacroEntry(M, IDLoc);
1243 // Otherwise, we have a normal instruction or directive.
1245 // Directives start with "."
1246 if (IDVal[0] == '.' && IDVal != ".") {
1247 // There are several entities interested in parsing directives:
1249 // 1. The target-specific assembly parser. Some directives are target
1250 // specific or may potentially behave differently on certain targets.
1251 // 2. Asm parser extensions. For example, platform-specific parsers
1252 // (like the ELF parser) register themselves as extensions.
1253 // 3. The generic directive parser implemented by this class. These are
1254 // all the directives that behave in a target and platform independent
1255 // manner, or at least have a default behavior that's shared between
1256 // all targets and platforms.
1258 // First query the target-specific parser. It will return 'true' if it
1259 // isn't interested in this directive.
1260 if (!getTargetParser().ParseDirective(ID))
1263 // Next, check the extention directive map to see if any extension has
1264 // registered itself to parse this directive.
1265 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1266 ExtensionDirectiveMap.lookup(IDVal);
1268 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1270 // Finally, if no one else is interested in this directive, it must be
1271 // generic and familiar to this class.
1277 return ParseDirectiveSet(IDVal, true);
1279 return ParseDirectiveSet(IDVal, false);
1281 return ParseDirectiveAscii(IDVal, false);
1284 return ParseDirectiveAscii(IDVal, true);
1286 return ParseDirectiveValue(1);
1290 return ParseDirectiveValue(2);
1294 return ParseDirectiveValue(4);
1297 return ParseDirectiveValue(8);
1300 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1302 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1304 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1305 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1308 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1309 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1312 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1314 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1316 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1318 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1320 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1322 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1324 return ParseDirectiveOrg();
1326 return ParseDirectiveFill();
1328 return ParseDirectiveZero();
1330 EatToEndOfStatement(); // .extern is the default, ignore it.
1334 return ParseDirectiveSymbolAttribute(MCSA_Global);
1335 case DK_INDIRECT_SYMBOL:
1336 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1337 case DK_LAZY_REFERENCE:
1338 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1339 case DK_NO_DEAD_STRIP:
1340 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1341 case DK_SYMBOL_RESOLVER:
1342 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1343 case DK_PRIVATE_EXTERN:
1344 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1346 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1347 case DK_WEAK_DEFINITION:
1348 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1349 case DK_WEAK_REFERENCE:
1350 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1351 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1352 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1355 return ParseDirectiveComm(/*IsLocal=*/false);
1357 return ParseDirectiveComm(/*IsLocal=*/true);
1359 return ParseDirectiveAbort();
1361 return ParseDirectiveInclude();
1363 return ParseDirectiveIncbin();
1366 return TokError(Twine(IDVal) + " not supported yet");
1368 return ParseDirectiveRept(IDLoc);
1370 return ParseDirectiveIrp(IDLoc);
1372 return ParseDirectiveIrpc(IDLoc);
1374 return ParseDirectiveEndr(IDLoc);
1375 case DK_BUNDLE_ALIGN_MODE:
1376 return ParseDirectiveBundleAlignMode();
1377 case DK_BUNDLE_LOCK:
1378 return ParseDirectiveBundleLock();
1379 case DK_BUNDLE_UNLOCK:
1380 return ParseDirectiveBundleUnlock();
1382 return ParseDirectiveLEB128(true);
1384 return ParseDirectiveLEB128(false);
1387 return ParseDirectiveSpace(IDVal);
1389 return ParseDirectiveFile(IDLoc);
1391 return ParseDirectiveLine();
1393 return ParseDirectiveLoc();
1395 return ParseDirectiveStabs();
1396 case DK_CFI_SECTIONS:
1397 return ParseDirectiveCFISections();
1398 case DK_CFI_STARTPROC:
1399 return ParseDirectiveCFIStartProc();
1400 case DK_CFI_ENDPROC:
1401 return ParseDirectiveCFIEndProc();
1402 case DK_CFI_DEF_CFA:
1403 return ParseDirectiveCFIDefCfa(IDLoc);
1404 case DK_CFI_DEF_CFA_OFFSET:
1405 return ParseDirectiveCFIDefCfaOffset();
1406 case DK_CFI_ADJUST_CFA_OFFSET:
1407 return ParseDirectiveCFIAdjustCfaOffset();
1408 case DK_CFI_DEF_CFA_REGISTER:
1409 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1411 return ParseDirectiveCFIOffset(IDLoc);
1412 case DK_CFI_REL_OFFSET:
1413 return ParseDirectiveCFIRelOffset(IDLoc);
1414 case DK_CFI_PERSONALITY:
1415 return ParseDirectiveCFIPersonalityOrLsda(true);
1417 return ParseDirectiveCFIPersonalityOrLsda(false);
1418 case DK_CFI_REMEMBER_STATE:
1419 return ParseDirectiveCFIRememberState();
1420 case DK_CFI_RESTORE_STATE:
1421 return ParseDirectiveCFIRestoreState();
1422 case DK_CFI_SAME_VALUE:
1423 return ParseDirectiveCFISameValue(IDLoc);
1424 case DK_CFI_RESTORE:
1425 return ParseDirectiveCFIRestore(IDLoc);
1427 return ParseDirectiveCFIEscape();
1428 case DK_CFI_SIGNAL_FRAME:
1429 return ParseDirectiveCFISignalFrame();
1430 case DK_CFI_UNDEFINED:
1431 return ParseDirectiveCFIUndefined(IDLoc);
1432 case DK_CFI_REGISTER:
1433 return ParseDirectiveCFIRegister(IDLoc);
1436 return ParseDirectiveMacrosOnOff(IDVal);
1438 return ParseDirectiveMacro(IDLoc);
1441 return ParseDirectiveEndMacro(IDVal);
1443 return ParseDirectivePurgeMacro(IDLoc);
1446 return Error(IDLoc, "unknown directive");
1450 if (ParsingInlineAsm && IDVal == "_emit")
1451 return ParseDirectiveEmit(IDLoc, Info);
1453 CheckForValidSection();
1455 // Canonicalize the opcode to lower case.
1456 std::string OpcodeStr = IDVal.lower();
1457 ParseInstructionInfo IInfo(Info.AsmRewrites);
1458 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1459 IDLoc, Info.ParsedOperands);
1460 Info.ParseError = HadError;
1462 // Dump the parsed representation, if requested.
1463 if (getShowParsedOperands()) {
1464 SmallString<256> Str;
1465 raw_svector_ostream OS(Str);
1466 OS << "parsed instruction: [";
1467 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1470 Info.ParsedOperands[i]->print(OS);
1474 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1477 // If we are generating dwarf for assembly source files and the current
1478 // section is the initial text section then generate a .loc directive for
1480 if (!HadError && getContext().getGenDwarfForAssembly() &&
1481 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1483 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1485 // If we previously parsed a cpp hash file line comment then make sure the
1486 // current Dwarf File is for the CppHashFilename if not then emit the
1487 // Dwarf File table for it and adjust the line number for the .loc.
1488 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1489 getContext().getMCDwarfFiles();
1490 if (CppHashFilename.size() != 0) {
1491 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1493 getStreamer().EmitDwarfFileDirective(
1494 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1496 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1497 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1500 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1501 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1502 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1506 // If parsing succeeded, match the instruction.
1509 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1510 Info.ParsedOperands,
1515 // Don't skip the rest of the line, the instruction parser is responsible for
1520 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1521 /// since they may not be able to be tokenized to get to the end of line token.
1522 void AsmParser::EatToEndOfLine() {
1523 if (!Lexer.is(AsmToken::EndOfStatement))
1524 Lexer.LexUntilEndOfLine();
1529 /// ParseCppHashLineFilenameComment as this:
1530 /// ::= # number "filename"
1531 /// or just as a full line comment if it doesn't have a number and a string.
1532 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1533 Lex(); // Eat the hash token.
1535 if (getLexer().isNot(AsmToken::Integer)) {
1536 // Consume the line since in cases it is not a well-formed line directive,
1537 // as if were simply a full line comment.
1542 int64_t LineNumber = getTok().getIntVal();
1545 if (getLexer().isNot(AsmToken::String)) {
1550 StringRef Filename = getTok().getString();
1551 // Get rid of the enclosing quotes.
1552 Filename = Filename.substr(1, Filename.size()-2);
1554 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1556 CppHashFilename = Filename;
1557 CppHashLineNumber = LineNumber;
1558 CppHashBuf = CurBuffer;
1560 // Ignore any trailing characters, they're just comment.
1565 /// DiagHandler - will use the last parsed cpp hash line filename comment
1566 /// for the Filename and LineNo if any in the diagnostic.
1567 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1568 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1569 raw_ostream &OS = errs();
1571 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1572 const SMLoc &DiagLoc = Diag.getLoc();
1573 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1574 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1576 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1577 // before printing the message.
1578 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1579 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1580 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1581 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1584 // If we have not parsed a cpp hash line filename comment or the source
1585 // manager changed or buffer changed (like in a nested include) then just
1586 // print the normal diagnostic using its Filename and LineNo.
1587 if (!Parser->CppHashLineNumber ||
1588 &DiagSrcMgr != &Parser->SrcMgr ||
1589 DiagBuf != CppHashBuf) {
1590 if (Parser->SavedDiagHandler)
1591 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1597 // Use the CppHashFilename and calculate a line number based on the
1598 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1600 const std::string Filename = Parser->CppHashFilename;
1602 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1603 int CppHashLocLineNo =
1604 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1605 int LineNo = Parser->CppHashLineNumber - 1 +
1606 (DiagLocLineNo - CppHashLocLineNo);
1608 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1609 Filename, LineNo, Diag.getColumnNo(),
1610 Diag.getKind(), Diag.getMessage(),
1611 Diag.getLineContents(), Diag.getRanges());
1613 if (Parser->SavedDiagHandler)
1614 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1616 NewDiag.print(0, OS);
1619 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1620 // difference being that that function accepts '@' as part of identifiers and
1621 // we can't do that. AsmLexer.cpp should probably be changed to handle
1622 // '@' as a special case when needed.
1623 static bool isIdentifierChar(char c) {
1624 return isalnum(c) || c == '_' || c == '$' || c == '.';
1627 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1628 const MCAsmMacroParameters &Parameters,
1629 const MCAsmMacroArguments &A,
1631 unsigned NParameters = Parameters.size();
1632 if (NParameters != 0 && NParameters != A.size())
1633 return Error(L, "Wrong number of arguments");
1635 // A macro without parameters is handled differently on Darwin:
1636 // gas accepts no arguments and does no substitutions
1637 while (!Body.empty()) {
1638 // Scan for the next substitution.
1639 std::size_t End = Body.size(), Pos = 0;
1640 for (; Pos != End; ++Pos) {
1641 // Check for a substitution or escape.
1643 // This macro has no parameters, look for $0, $1, etc.
1644 if (Body[Pos] != '$' || Pos + 1 == End)
1647 char Next = Body[Pos + 1];
1648 if (Next == '$' || Next == 'n' || isdigit(Next))
1651 // This macro has parameters, look for \foo, \bar, etc.
1652 if (Body[Pos] == '\\' && Pos + 1 != End)
1658 OS << Body.slice(0, Pos);
1660 // Check if we reached the end.
1665 switch (Body[Pos+1]) {
1671 // $n => number of arguments
1676 // $[0-9] => argument
1678 // Missing arguments are ignored.
1679 unsigned Index = Body[Pos+1] - '0';
1680 if (Index >= A.size())
1683 // Otherwise substitute with the token values, with spaces eliminated.
1684 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1685 ie = A[Index].end(); it != ie; ++it)
1686 OS << it->getString();
1692 unsigned I = Pos + 1;
1693 while (isIdentifierChar(Body[I]) && I + 1 != End)
1696 const char *Begin = Body.data() + Pos +1;
1697 StringRef Argument(Begin, I - (Pos +1));
1699 for (; Index < NParameters; ++Index)
1700 if (Parameters[Index].first == Argument)
1703 if (Index == NParameters) {
1704 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1707 OS << '\\' << Argument;
1711 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1712 ie = A[Index].end(); it != ie; ++it)
1713 if (it->getKind() == AsmToken::String)
1714 OS << it->getStringContents();
1716 OS << it->getString();
1718 Pos += 1 + Argument.size();
1721 // Update the scan point.
1722 Body = Body.substr(Pos);
1728 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
1731 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1736 static bool IsOperator(AsmToken::TokenKind kind)
1742 case AsmToken::Plus:
1743 case AsmToken::Minus:
1744 case AsmToken::Tilde:
1745 case AsmToken::Slash:
1746 case AsmToken::Star:
1748 case AsmToken::Equal:
1749 case AsmToken::EqualEqual:
1750 case AsmToken::Pipe:
1751 case AsmToken::PipePipe:
1752 case AsmToken::Caret:
1754 case AsmToken::AmpAmp:
1755 case AsmToken::Exclaim:
1756 case AsmToken::ExclaimEqual:
1757 case AsmToken::Percent:
1758 case AsmToken::Less:
1759 case AsmToken::LessEqual:
1760 case AsmToken::LessLess:
1761 case AsmToken::LessGreater:
1762 case AsmToken::Greater:
1763 case AsmToken::GreaterEqual:
1764 case AsmToken::GreaterGreater:
1769 bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
1770 AsmToken::TokenKind &ArgumentDelimiter) {
1771 unsigned ParenLevel = 0;
1772 unsigned AddTokens = 0;
1774 // gas accepts arguments separated by whitespace, except on Darwin
1776 Lexer.setSkipSpace(false);
1779 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1780 Lexer.setSkipSpace(true);
1781 return TokError("unexpected token in macro instantiation");
1784 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1785 // Spaces and commas cannot be mixed to delimit parameters
1786 if (ArgumentDelimiter == AsmToken::Eof)
1787 ArgumentDelimiter = AsmToken::Comma;
1788 else if (ArgumentDelimiter != AsmToken::Comma) {
1789 Lexer.setSkipSpace(true);
1790 return TokError("expected ' ' for macro argument separator");
1795 if (Lexer.is(AsmToken::Space)) {
1796 Lex(); // Eat spaces
1798 // Spaces can delimit parameters, but could also be part an expression.
1799 // If the token after a space is an operator, add the token and the next
1800 // one into this argument
1801 if (ArgumentDelimiter == AsmToken::Space ||
1802 ArgumentDelimiter == AsmToken::Eof) {
1803 if (IsOperator(Lexer.getKind())) {
1804 // Check to see whether the token is used as an operator,
1805 // or part of an identifier
1806 const char *NextChar = getTok().getEndLoc().getPointer();
1807 if (*NextChar == ' ')
1811 if (!AddTokens && ParenLevel == 0) {
1812 if (ArgumentDelimiter == AsmToken::Eof &&
1813 !IsOperator(Lexer.getKind()))
1814 ArgumentDelimiter = AsmToken::Space;
1820 // HandleMacroEntry relies on not advancing the lexer here
1821 // to be able to fill in the remaining default parameter values
1822 if (Lexer.is(AsmToken::EndOfStatement))
1825 // Adjust the current parentheses level.
1826 if (Lexer.is(AsmToken::LParen))
1828 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1831 // Append the token to the current argument list.
1832 MA.push_back(getTok());
1838 Lexer.setSkipSpace(true);
1839 if (ParenLevel != 0)
1840 return TokError("unbalanced parentheses in macro argument");
1844 // Parse the macro instantiation arguments.
1845 bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
1846 const unsigned NParameters = M ? M->Parameters.size() : 0;
1847 // Argument delimiter is initially unknown. It will be set by
1848 // ParseMacroArgument()
1849 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1851 // Parse two kinds of macro invocations:
1852 // - macros defined without any parameters accept an arbitrary number of them
1853 // - macros defined with parameters accept at most that many of them
1854 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1856 MCAsmMacroArgument MA;
1858 if (ParseMacroArgument(MA, ArgumentDelimiter))
1861 if (!MA.empty() || !NParameters)
1863 else if (NParameters) {
1864 if (!M->Parameters[Parameter].second.empty())
1865 A.push_back(M->Parameters[Parameter].second);
1868 // At the end of the statement, fill in remaining arguments that have
1869 // default values. If there aren't any, then the next argument is
1870 // required but missing
1871 if (Lexer.is(AsmToken::EndOfStatement)) {
1872 if (NParameters && Parameter < NParameters - 1) {
1873 if (M->Parameters[Parameter + 1].second.empty())
1874 return TokError("macro argument '" +
1875 Twine(M->Parameters[Parameter + 1].first) +
1883 if (Lexer.is(AsmToken::Comma))
1886 return TokError("Too many arguments");
1889 const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1890 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1891 return (I == MacroMap.end()) ? NULL : I->getValue();
1894 void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1895 MacroMap[Name] = new MCAsmMacro(Macro);
1898 void AsmParser::UndefineMacro(StringRef Name) {
1899 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1900 if (I != MacroMap.end()) {
1901 delete I->getValue();
1906 bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1907 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1908 // this, although we should protect against infinite loops.
1909 if (ActiveMacros.size() == 20)
1910 return TokError("macros cannot be nested more than 20 levels deep");
1912 MCAsmMacroArguments A;
1913 if (ParseMacroArguments(M, A))
1916 // Remove any trailing empty arguments. Do this after-the-fact as we have
1917 // to keep empty arguments in the middle of the list or positionality
1918 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1919 while (!A.empty() && A.back().empty())
1922 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1923 // to hold the macro body with substitutions.
1924 SmallString<256> Buf;
1925 StringRef Body = M->Body;
1926 raw_svector_ostream OS(Buf);
1928 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1931 // We include the .endmacro in the buffer as our cue to exit the macro
1933 OS << ".endmacro\n";
1935 MemoryBuffer *Instantiation =
1936 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1938 // Create the macro instantiation object and add to the current macro
1939 // instantiation stack.
1940 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1944 ActiveMacros.push_back(MI);
1946 // Jump to the macro instantiation and prime the lexer.
1947 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1948 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1954 void AsmParser::HandleMacroExit() {
1955 // Jump to the EndOfStatement we should return to, and consume it.
1956 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1959 // Pop the instantiation entry.
1960 delete ActiveMacros.back();
1961 ActiveMacros.pop_back();
1964 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1965 switch (Value->getKind()) {
1966 case MCExpr::Binary: {
1967 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1968 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1971 case MCExpr::Target:
1972 case MCExpr::Constant:
1974 case MCExpr::SymbolRef: {
1975 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1977 return IsUsedIn(Sym, S.getVariableValue());
1981 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1984 llvm_unreachable("Unknown expr kind!");
1987 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1989 // FIXME: Use better location, we should use proper tokens.
1990 SMLoc EqualLoc = Lexer.getLoc();
1992 const MCExpr *Value;
1993 if (ParseExpression(Value))
1996 // Note: we don't count b as used in "a = b". This is to allow
2000 if (Lexer.isNot(AsmToken::EndOfStatement))
2001 return TokError("unexpected token in assignment");
2003 // Error on assignment to '.'.
2005 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2006 "(use '.space' or '.org').)"));
2009 // Eat the end of statement marker.
2012 // Validate that the LHS is allowed to be a variable (either it has not been
2013 // used as a symbol, or it is an absolute symbol).
2014 MCSymbol *Sym = getContext().LookupSymbol(Name);
2016 // Diagnose assignment to a label.
2018 // FIXME: Diagnostics. Note the location of the definition as a label.
2019 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2020 if (IsUsedIn(Sym, Value))
2021 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2022 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2023 ; // Allow redefinitions of undefined symbols only used in directives.
2024 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2025 ; // Allow redefinitions of variables that haven't yet been used.
2026 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2027 return Error(EqualLoc, "redefinition of '" + Name + "'");
2028 else if (!Sym->isVariable())
2029 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2030 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2031 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2034 // Don't count these checks as uses.
2035 Sym->setUsed(false);
2037 Sym = getContext().GetOrCreateSymbol(Name);
2039 // FIXME: Handle '.'.
2041 // Do the assignment.
2042 Out.EmitAssignment(Sym, Value);
2044 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2050 /// ParseIdentifier:
2053 bool AsmParser::ParseIdentifier(StringRef &Res) {
2054 // The assembler has relaxed rules for accepting identifiers, in particular we
2055 // allow things like '.globl $foo', which would normally be separate
2056 // tokens. At this level, we have already lexed so we cannot (currently)
2057 // handle this as a context dependent token, instead we detect adjacent tokens
2058 // and return the combined identifier.
2059 if (Lexer.is(AsmToken::Dollar)) {
2060 SMLoc DollarLoc = getLexer().getLoc();
2062 // Consume the dollar sign, and check for a following identifier.
2064 if (Lexer.isNot(AsmToken::Identifier))
2067 // We have a '$' followed by an identifier, make sure they are adjacent.
2068 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2071 // Construct the joined identifier and consume the token.
2072 Res = StringRef(DollarLoc.getPointer(),
2073 getTok().getIdentifier().size() + 1);
2078 if (Lexer.isNot(AsmToken::Identifier) &&
2079 Lexer.isNot(AsmToken::String))
2082 Res = getTok().getIdentifier();
2084 Lex(); // Consume the identifier token.
2089 /// ParseDirectiveSet:
2090 /// ::= .equ identifier ',' expression
2091 /// ::= .equiv identifier ',' expression
2092 /// ::= .set identifier ',' expression
2093 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2096 if (ParseIdentifier(Name))
2097 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2099 if (getLexer().isNot(AsmToken::Comma))
2100 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2103 return ParseAssignment(Name, allow_redef, true);
2106 bool AsmParser::ParseEscapedString(std::string &Data) {
2107 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2110 StringRef Str = getTok().getStringContents();
2111 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2112 if (Str[i] != '\\') {
2117 // Recognize escaped characters. Note that this escape semantics currently
2118 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2121 return TokError("unexpected backslash at end of string");
2123 // Recognize octal sequences.
2124 if ((unsigned) (Str[i] - '0') <= 7) {
2125 // Consume up to three octal characters.
2126 unsigned Value = Str[i] - '0';
2128 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2130 Value = Value * 8 + (Str[i] - '0');
2132 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2134 Value = Value * 8 + (Str[i] - '0');
2139 return TokError("invalid octal escape sequence (out of range)");
2141 Data += (unsigned char) Value;
2145 // Otherwise recognize individual escapes.
2148 // Just reject invalid escape sequences for now.
2149 return TokError("invalid escape sequence (unrecognized character)");
2151 case 'b': Data += '\b'; break;
2152 case 'f': Data += '\f'; break;
2153 case 'n': Data += '\n'; break;
2154 case 'r': Data += '\r'; break;
2155 case 't': Data += '\t'; break;
2156 case '"': Data += '"'; break;
2157 case '\\': Data += '\\'; break;
2164 /// ParseDirectiveAscii:
2165 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2166 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2167 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2168 CheckForValidSection();
2171 if (getLexer().isNot(AsmToken::String))
2172 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2175 if (ParseEscapedString(Data))
2178 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2180 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2184 if (getLexer().is(AsmToken::EndOfStatement))
2187 if (getLexer().isNot(AsmToken::Comma))
2188 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2197 /// ParseDirectiveValue
2198 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2199 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2200 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2201 CheckForValidSection();
2204 const MCExpr *Value;
2205 SMLoc ExprLoc = getLexer().getLoc();
2206 if (ParseExpression(Value))
2209 // Special case constant expressions to match code generator.
2210 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2211 assert(Size <= 8 && "Invalid size");
2212 uint64_t IntValue = MCE->getValue();
2213 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2214 return Error(ExprLoc, "literal value out of range for directive");
2215 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2217 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2219 if (getLexer().is(AsmToken::EndOfStatement))
2222 // FIXME: Improve diagnostic.
2223 if (getLexer().isNot(AsmToken::Comma))
2224 return TokError("unexpected token in directive");
2233 /// ParseDirectiveRealValue
2234 /// ::= (.single | .double) [ expression (, expression)* ]
2235 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2236 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2237 CheckForValidSection();
2240 // We don't truly support arithmetic on floating point expressions, so we
2241 // have to manually parse unary prefixes.
2243 if (getLexer().is(AsmToken::Minus)) {
2246 } else if (getLexer().is(AsmToken::Plus))
2249 if (getLexer().isNot(AsmToken::Integer) &&
2250 getLexer().isNot(AsmToken::Real) &&
2251 getLexer().isNot(AsmToken::Identifier))
2252 return TokError("unexpected token in directive");
2254 // Convert to an APFloat.
2255 APFloat Value(Semantics);
2256 StringRef IDVal = getTok().getString();
2257 if (getLexer().is(AsmToken::Identifier)) {
2258 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2259 Value = APFloat::getInf(Semantics);
2260 else if (!IDVal.compare_lower("nan"))
2261 Value = APFloat::getNaN(Semantics, false, ~0);
2263 return TokError("invalid floating point literal");
2264 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2265 APFloat::opInvalidOp)
2266 return TokError("invalid floating point literal");
2270 // Consume the numeric token.
2273 // Emit the value as an integer.
2274 APInt AsInt = Value.bitcastToAPInt();
2275 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2276 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2278 if (getLexer().is(AsmToken::EndOfStatement))
2281 if (getLexer().isNot(AsmToken::Comma))
2282 return TokError("unexpected token in directive");
2291 /// ParseDirectiveZero
2292 /// ::= .zero expression
2293 bool AsmParser::ParseDirectiveZero() {
2294 CheckForValidSection();
2297 if (ParseAbsoluteExpression(NumBytes))
2301 if (getLexer().is(AsmToken::Comma)) {
2303 if (ParseAbsoluteExpression(Val))
2307 if (getLexer().isNot(AsmToken::EndOfStatement))
2308 return TokError("unexpected token in '.zero' directive");
2312 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2317 /// ParseDirectiveFill
2318 /// ::= .fill expression , expression , expression
2319 bool AsmParser::ParseDirectiveFill() {
2320 CheckForValidSection();
2323 if (ParseAbsoluteExpression(NumValues))
2326 if (getLexer().isNot(AsmToken::Comma))
2327 return TokError("unexpected token in '.fill' directive");
2331 if (ParseAbsoluteExpression(FillSize))
2334 if (getLexer().isNot(AsmToken::Comma))
2335 return TokError("unexpected token in '.fill' directive");
2339 if (ParseAbsoluteExpression(FillExpr))
2342 if (getLexer().isNot(AsmToken::EndOfStatement))
2343 return TokError("unexpected token in '.fill' directive");
2347 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2348 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2350 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2351 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2356 /// ParseDirectiveOrg
2357 /// ::= .org expression [ , expression ]
2358 bool AsmParser::ParseDirectiveOrg() {
2359 CheckForValidSection();
2361 const MCExpr *Offset;
2362 SMLoc Loc = getTok().getLoc();
2363 if (ParseExpression(Offset))
2366 // Parse optional fill expression.
2367 int64_t FillExpr = 0;
2368 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2369 if (getLexer().isNot(AsmToken::Comma))
2370 return TokError("unexpected token in '.org' directive");
2373 if (ParseAbsoluteExpression(FillExpr))
2376 if (getLexer().isNot(AsmToken::EndOfStatement))
2377 return TokError("unexpected token in '.org' directive");
2382 // Only limited forms of relocatable expressions are accepted here, it
2383 // has to be relative to the current section. The streamer will return
2384 // 'true' if the expression wasn't evaluatable.
2385 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2386 return Error(Loc, "expected assembly-time absolute expression");
2391 /// ParseDirectiveAlign
2392 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2393 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2394 CheckForValidSection();
2396 SMLoc AlignmentLoc = getLexer().getLoc();
2398 if (ParseAbsoluteExpression(Alignment))
2402 bool HasFillExpr = false;
2403 int64_t FillExpr = 0;
2404 int64_t MaxBytesToFill = 0;
2405 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2406 if (getLexer().isNot(AsmToken::Comma))
2407 return TokError("unexpected token in directive");
2410 // The fill expression can be omitted while specifying a maximum number of
2411 // alignment bytes, e.g:
2413 if (getLexer().isNot(AsmToken::Comma)) {
2415 if (ParseAbsoluteExpression(FillExpr))
2419 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2420 if (getLexer().isNot(AsmToken::Comma))
2421 return TokError("unexpected token in directive");
2424 MaxBytesLoc = getLexer().getLoc();
2425 if (ParseAbsoluteExpression(MaxBytesToFill))
2428 if (getLexer().isNot(AsmToken::EndOfStatement))
2429 return TokError("unexpected token in directive");
2438 // Compute alignment in bytes.
2440 // FIXME: Diagnose overflow.
2441 if (Alignment >= 32) {
2442 Error(AlignmentLoc, "invalid alignment value");
2446 Alignment = 1ULL << Alignment;
2449 // Diagnose non-sensical max bytes to align.
2450 if (MaxBytesLoc.isValid()) {
2451 if (MaxBytesToFill < 1) {
2452 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2453 "many bytes, ignoring maximum bytes expression");
2457 if (MaxBytesToFill >= Alignment) {
2458 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2464 // Check whether we should use optimal code alignment for this .align
2466 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2467 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2468 ValueSize == 1 && UseCodeAlign) {
2469 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2471 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2472 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2479 /// ParseDirectiveFile
2480 /// ::= .file [number] filename
2481 /// ::= .file number directory filename
2482 bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2483 // FIXME: I'm not sure what this is.
2484 int64_t FileNumber = -1;
2485 SMLoc FileNumberLoc = getLexer().getLoc();
2486 if (getLexer().is(AsmToken::Integer)) {
2487 FileNumber = getTok().getIntVal();
2491 return TokError("file number less than one");
2494 if (getLexer().isNot(AsmToken::String))
2495 return TokError("unexpected token in '.file' directive");
2497 // Usually the directory and filename together, otherwise just the directory.
2498 StringRef Path = getTok().getString();
2499 Path = Path.substr(1, Path.size()-2);
2502 StringRef Directory;
2504 if (getLexer().is(AsmToken::String)) {
2505 if (FileNumber == -1)
2506 return TokError("explicit path specified, but no file number");
2507 Filename = getTok().getString();
2508 Filename = Filename.substr(1, Filename.size()-2);
2515 if (getLexer().isNot(AsmToken::EndOfStatement))
2516 return TokError("unexpected token in '.file' directive");
2518 if (FileNumber == -1)
2519 getStreamer().EmitFileDirective(Filename);
2521 if (getContext().getGenDwarfForAssembly() == true)
2522 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2523 "used to generate dwarf debug info for assembly code");
2525 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2526 Error(FileNumberLoc, "file number already allocated");
2532 /// ParseDirectiveLine
2533 /// ::= .line [number]
2534 bool AsmParser::ParseDirectiveLine() {
2535 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2536 if (getLexer().isNot(AsmToken::Integer))
2537 return TokError("unexpected token in '.line' directive");
2539 int64_t LineNumber = getTok().getIntVal();
2543 // FIXME: Do something with the .line.
2546 if (getLexer().isNot(AsmToken::EndOfStatement))
2547 return TokError("unexpected token in '.line' directive");
2552 /// ParseDirectiveLoc
2553 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2554 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2555 /// The first number is a file number, must have been previously assigned with
2556 /// a .file directive, the second number is the line number and optionally the
2557 /// third number is a column position (zero if not specified). The remaining
2558 /// optional items are .loc sub-directives.
2559 bool AsmParser::ParseDirectiveLoc() {
2560 if (getLexer().isNot(AsmToken::Integer))
2561 return TokError("unexpected token in '.loc' directive");
2562 int64_t FileNumber = getTok().getIntVal();
2564 return TokError("file number less than one in '.loc' directive");
2565 if (!getContext().isValidDwarfFileNumber(FileNumber))
2566 return TokError("unassigned file number in '.loc' directive");
2569 int64_t LineNumber = 0;
2570 if (getLexer().is(AsmToken::Integer)) {
2571 LineNumber = getTok().getIntVal();
2573 return TokError("line number less than one in '.loc' directive");
2577 int64_t ColumnPos = 0;
2578 if (getLexer().is(AsmToken::Integer)) {
2579 ColumnPos = getTok().getIntVal();
2581 return TokError("column position less than zero in '.loc' directive");
2585 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2587 int64_t Discriminator = 0;
2588 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2590 if (getLexer().is(AsmToken::EndOfStatement))
2594 SMLoc Loc = getTok().getLoc();
2595 if (ParseIdentifier(Name))
2596 return TokError("unexpected token in '.loc' directive");
2598 if (Name == "basic_block")
2599 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2600 else if (Name == "prologue_end")
2601 Flags |= DWARF2_FLAG_PROLOGUE_END;
2602 else if (Name == "epilogue_begin")
2603 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2604 else if (Name == "is_stmt") {
2605 Loc = getTok().getLoc();
2606 const MCExpr *Value;
2607 if (ParseExpression(Value))
2609 // The expression must be the constant 0 or 1.
2610 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2611 int Value = MCE->getValue();
2613 Flags &= ~DWARF2_FLAG_IS_STMT;
2614 else if (Value == 1)
2615 Flags |= DWARF2_FLAG_IS_STMT;
2617 return Error(Loc, "is_stmt value not 0 or 1");
2620 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2623 else if (Name == "isa") {
2624 Loc = getTok().getLoc();
2625 const MCExpr *Value;
2626 if (ParseExpression(Value))
2628 // The expression must be a constant greater or equal to 0.
2629 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2630 int Value = MCE->getValue();
2632 return Error(Loc, "isa number less than zero");
2636 return Error(Loc, "isa number not a constant value");
2639 else if (Name == "discriminator") {
2640 if (ParseAbsoluteExpression(Discriminator))
2644 return Error(Loc, "unknown sub-directive in '.loc' directive");
2647 if (getLexer().is(AsmToken::EndOfStatement))
2652 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2653 Isa, Discriminator, StringRef());
2658 /// ParseDirectiveStabs
2659 /// ::= .stabs string, number, number, number
2660 bool AsmParser::ParseDirectiveStabs() {
2661 return TokError("unsupported directive '.stabs'");
2664 /// ParseDirectiveCFISections
2665 /// ::= .cfi_sections section [, section]
2666 bool AsmParser::ParseDirectiveCFISections() {
2671 if (ParseIdentifier(Name))
2672 return TokError("Expected an identifier");
2674 if (Name == ".eh_frame")
2676 else if (Name == ".debug_frame")
2679 if (getLexer().is(AsmToken::Comma)) {
2682 if (ParseIdentifier(Name))
2683 return TokError("Expected an identifier");
2685 if (Name == ".eh_frame")
2687 else if (Name == ".debug_frame")
2691 getStreamer().EmitCFISections(EH, Debug);
2695 /// ParseDirectiveCFIStartProc
2696 /// ::= .cfi_startproc
2697 bool AsmParser::ParseDirectiveCFIStartProc() {
2698 getStreamer().EmitCFIStartProc();
2702 /// ParseDirectiveCFIEndProc
2703 /// ::= .cfi_endproc
2704 bool AsmParser::ParseDirectiveCFIEndProc() {
2705 getStreamer().EmitCFIEndProc();
2709 /// ParseRegisterOrRegisterNumber - parse register name or number.
2710 bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2711 SMLoc DirectiveLoc) {
2714 if (getLexer().isNot(AsmToken::Integer)) {
2715 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2717 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2719 return ParseAbsoluteExpression(Register);
2724 /// ParseDirectiveCFIDefCfa
2725 /// ::= .cfi_def_cfa register, offset
2726 bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2727 int64_t Register = 0;
2728 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2731 if (getLexer().isNot(AsmToken::Comma))
2732 return TokError("unexpected token in directive");
2736 if (ParseAbsoluteExpression(Offset))
2739 getStreamer().EmitCFIDefCfa(Register, Offset);
2743 /// ParseDirectiveCFIDefCfaOffset
2744 /// ::= .cfi_def_cfa_offset offset
2745 bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2747 if (ParseAbsoluteExpression(Offset))
2750 getStreamer().EmitCFIDefCfaOffset(Offset);
2754 /// ParseDirectiveCFIRegister
2755 /// ::= .cfi_register register, register
2756 bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2757 int64_t Register1 = 0;
2758 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2761 if (getLexer().isNot(AsmToken::Comma))
2762 return TokError("unexpected token in directive");
2765 int64_t Register2 = 0;
2766 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2769 getStreamer().EmitCFIRegister(Register1, Register2);
2773 /// ParseDirectiveCFIAdjustCfaOffset
2774 /// ::= .cfi_adjust_cfa_offset adjustment
2775 bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2776 int64_t Adjustment = 0;
2777 if (ParseAbsoluteExpression(Adjustment))
2780 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2784 /// ParseDirectiveCFIDefCfaRegister
2785 /// ::= .cfi_def_cfa_register register
2786 bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2787 int64_t Register = 0;
2788 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2791 getStreamer().EmitCFIDefCfaRegister(Register);
2795 /// ParseDirectiveCFIOffset
2796 /// ::= .cfi_offset register, offset
2797 bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2798 int64_t Register = 0;
2801 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2804 if (getLexer().isNot(AsmToken::Comma))
2805 return TokError("unexpected token in directive");
2808 if (ParseAbsoluteExpression(Offset))
2811 getStreamer().EmitCFIOffset(Register, Offset);
2815 /// ParseDirectiveCFIRelOffset
2816 /// ::= .cfi_rel_offset register, offset
2817 bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2818 int64_t Register = 0;
2820 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2823 if (getLexer().isNot(AsmToken::Comma))
2824 return TokError("unexpected token in directive");
2828 if (ParseAbsoluteExpression(Offset))
2831 getStreamer().EmitCFIRelOffset(Register, Offset);
2835 static bool isValidEncoding(int64_t Encoding) {
2836 if (Encoding & ~0xff)
2839 if (Encoding == dwarf::DW_EH_PE_omit)
2842 const unsigned Format = Encoding & 0xf;
2843 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2844 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2845 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2846 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2849 const unsigned Application = Encoding & 0x70;
2850 if (Application != dwarf::DW_EH_PE_absptr &&
2851 Application != dwarf::DW_EH_PE_pcrel)
2857 /// ParseDirectiveCFIPersonalityOrLsda
2858 /// IsPersonality true for cfi_personality, false for cfi_lsda
2859 /// ::= .cfi_personality encoding, [symbol_name]
2860 /// ::= .cfi_lsda encoding, [symbol_name]
2861 bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2862 int64_t Encoding = 0;
2863 if (ParseAbsoluteExpression(Encoding))
2865 if (Encoding == dwarf::DW_EH_PE_omit)
2868 if (!isValidEncoding(Encoding))
2869 return TokError("unsupported encoding.");
2871 if (getLexer().isNot(AsmToken::Comma))
2872 return TokError("unexpected token in directive");
2876 if (ParseIdentifier(Name))
2877 return TokError("expected identifier in directive");
2879 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2882 getStreamer().EmitCFIPersonality(Sym, Encoding);
2884 getStreamer().EmitCFILsda(Sym, Encoding);
2888 /// ParseDirectiveCFIRememberState
2889 /// ::= .cfi_remember_state
2890 bool AsmParser::ParseDirectiveCFIRememberState() {
2891 getStreamer().EmitCFIRememberState();
2895 /// ParseDirectiveCFIRestoreState
2896 /// ::= .cfi_remember_state
2897 bool AsmParser::ParseDirectiveCFIRestoreState() {
2898 getStreamer().EmitCFIRestoreState();
2902 /// ParseDirectiveCFISameValue
2903 /// ::= .cfi_same_value register
2904 bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2905 int64_t Register = 0;
2907 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2910 getStreamer().EmitCFISameValue(Register);
2914 /// ParseDirectiveCFIRestore
2915 /// ::= .cfi_restore register
2916 bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2917 int64_t Register = 0;
2918 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2921 getStreamer().EmitCFIRestore(Register);
2925 /// ParseDirectiveCFIEscape
2926 /// ::= .cfi_escape expression[,...]
2927 bool AsmParser::ParseDirectiveCFIEscape() {
2930 if (ParseAbsoluteExpression(CurrValue))
2933 Values.push_back((uint8_t)CurrValue);
2935 while (getLexer().is(AsmToken::Comma)) {
2938 if (ParseAbsoluteExpression(CurrValue))
2941 Values.push_back((uint8_t)CurrValue);
2944 getStreamer().EmitCFIEscape(Values);
2948 /// ParseDirectiveCFISignalFrame
2949 /// ::= .cfi_signal_frame
2950 bool AsmParser::ParseDirectiveCFISignalFrame() {
2951 if (getLexer().isNot(AsmToken::EndOfStatement))
2952 return Error(getLexer().getLoc(),
2953 "unexpected token in '.cfi_signal_frame'");
2955 getStreamer().EmitCFISignalFrame();
2959 /// ParseDirectiveCFIUndefined
2960 /// ::= .cfi_undefined register
2961 bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2962 int64_t Register = 0;
2964 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2967 getStreamer().EmitCFIUndefined(Register);
2971 /// ParseDirectiveMacrosOnOff
2974 bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2975 if (getLexer().isNot(AsmToken::EndOfStatement))
2976 return Error(getLexer().getLoc(),
2977 "unexpected token in '" + Directive + "' directive");
2979 SetMacrosEnabled(Directive == ".macros_on");
2983 /// ParseDirectiveMacro
2984 /// ::= .macro name [parameters]
2985 bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2987 if (ParseIdentifier(Name))
2988 return TokError("expected identifier in '.macro' directive");
2990 MCAsmMacroParameters Parameters;
2991 // Argument delimiter is initially unknown. It will be set by
2992 // ParseMacroArgument()
2993 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
2994 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2996 MCAsmMacroParameter Parameter;
2997 if (ParseIdentifier(Parameter.first))
2998 return TokError("expected identifier in '.macro' directive");
3000 if (getLexer().is(AsmToken::Equal)) {
3002 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3006 Parameters.push_back(Parameter);
3008 if (getLexer().is(AsmToken::Comma))
3010 else if (getLexer().is(AsmToken::EndOfStatement))
3015 // Eat the end of statement.
3018 AsmToken EndToken, StartToken = getTok();
3020 // Lex the macro definition.
3022 // Check whether we have reached the end of the file.
3023 if (getLexer().is(AsmToken::Eof))
3024 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3026 // Otherwise, check whether we have reach the .endmacro.
3027 if (getLexer().is(AsmToken::Identifier) &&
3028 (getTok().getIdentifier() == ".endm" ||
3029 getTok().getIdentifier() == ".endmacro")) {
3030 EndToken = getTok();
3032 if (getLexer().isNot(AsmToken::EndOfStatement))
3033 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3038 // Otherwise, scan til the end of the statement.
3039 EatToEndOfStatement();
3042 if (LookupMacro(Name)) {
3043 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3046 const char *BodyStart = StartToken.getLoc().getPointer();
3047 const char *BodyEnd = EndToken.getLoc().getPointer();
3048 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3049 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
3050 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3054 /// CheckForBadMacro
3056 /// With the support added for named parameters there may be code out there that
3057 /// is transitioning from positional parameters. In versions of gas that did
3058 /// not support named parameters they would be ignored on the macro defintion.
3059 /// But to support both styles of parameters this is not possible so if a macro
3060 /// defintion has named parameters but does not use them and has what appears
3061 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3062 /// warning that the positional parameter found in body which have no effect.
3063 /// Hoping the developer will either remove the named parameters from the macro
3064 /// definiton so the positional parameters get used if that was what was
3065 /// intended or change the macro to use the named parameters. It is possible
3066 /// this warning will trigger when the none of the named parameters are used
3067 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3068 void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3070 MCAsmMacroParameters Parameters) {
3071 // If this macro is not defined with named parameters the warning we are
3072 // checking for here doesn't apply.
3073 unsigned NParameters = Parameters.size();
3074 if (NParameters == 0)
3077 bool NamedParametersFound = false;
3078 bool PositionalParametersFound = false;
3080 // Look at the body of the macro for use of both the named parameters and what
3081 // are likely to be positional parameters. This is what expandMacro() is
3082 // doing when it finds the parameters in the body.
3083 while (!Body.empty()) {
3084 // Scan for the next possible parameter.
3085 std::size_t End = Body.size(), Pos = 0;
3086 for (; Pos != End; ++Pos) {
3087 // Check for a substitution or escape.
3088 // This macro is defined with parameters, look for \foo, \bar, etc.
3089 if (Body[Pos] == '\\' && Pos + 1 != End)
3092 // This macro should have parameters, but look for $0, $1, ..., $n too.
3093 if (Body[Pos] != '$' || Pos + 1 == End)
3095 char Next = Body[Pos + 1];
3096 if (Next == '$' || Next == 'n' || isdigit(Next))
3100 // Check if we reached the end.
3104 if (Body[Pos] == '$') {
3105 switch (Body[Pos+1]) {
3110 // $n => number of arguments
3112 PositionalParametersFound = true;
3115 // $[0-9] => argument
3117 PositionalParametersFound = true;
3123 unsigned I = Pos + 1;
3124 while (isIdentifierChar(Body[I]) && I + 1 != End)
3127 const char *Begin = Body.data() + Pos +1;
3128 StringRef Argument(Begin, I - (Pos +1));
3130 for (; Index < NParameters; ++Index)
3131 if (Parameters[Index].first == Argument)
3134 if (Index == NParameters) {
3135 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3141 NamedParametersFound = true;
3142 Pos += 1 + Argument.size();
3145 // Update the scan point.
3146 Body = Body.substr(Pos);
3149 if (!NamedParametersFound && PositionalParametersFound)
3150 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3151 "used in macro body, possible positional parameter "
3152 "found in body which will have no effect");
3155 /// ParseDirectiveEndMacro
3158 bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3159 if (getLexer().isNot(AsmToken::EndOfStatement))
3160 return TokError("unexpected token in '" + Directive + "' directive");
3162 // If we are inside a macro instantiation, terminate the current
3164 if (InsideMacroInstantiation()) {
3169 // Otherwise, this .endmacro is a stray entry in the file; well formed
3170 // .endmacro directives are handled during the macro definition parsing.
3171 return TokError("unexpected '" + Directive + "' in file, "
3172 "no current macro definition");
3175 /// ParseDirectivePurgeMacro
3177 bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3179 if (ParseIdentifier(Name))
3180 return TokError("expected identifier in '.purgem' directive");
3182 if (getLexer().isNot(AsmToken::EndOfStatement))
3183 return TokError("unexpected token in '.purgem' directive");
3185 if (!LookupMacro(Name))
3186 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3188 UndefineMacro(Name);
3192 /// ParseDirectiveBundleAlignMode
3193 /// ::= {.bundle_align_mode} expression
3194 bool AsmParser::ParseDirectiveBundleAlignMode() {
3195 CheckForValidSection();
3197 // Expect a single argument: an expression that evaluates to a constant
3198 // in the inclusive range 0-30.
3199 SMLoc ExprLoc = getLexer().getLoc();
3200 int64_t AlignSizePow2;
3201 if (ParseAbsoluteExpression(AlignSizePow2))
3203 else if (getLexer().isNot(AsmToken::EndOfStatement))
3204 return TokError("unexpected token after expression in"
3205 " '.bundle_align_mode' directive");
3206 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3207 return Error(ExprLoc,
3208 "invalid bundle alignment size (expected between 0 and 30)");
3212 // Because of AlignSizePow2's verified range we can safely truncate it to
3214 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3218 /// ParseDirectiveBundleLock
3219 /// ::= {.bundle_lock} [align_to_end]
3220 bool AsmParser::ParseDirectiveBundleLock() {
3221 CheckForValidSection();
3222 bool AlignToEnd = false;
3224 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3226 SMLoc Loc = getTok().getLoc();
3227 const char *kInvalidOptionError =
3228 "invalid option for '.bundle_lock' directive";
3230 if (ParseIdentifier(Option))
3231 return Error(Loc, kInvalidOptionError);
3233 if (Option != "align_to_end")
3234 return Error(Loc, kInvalidOptionError);
3235 else if (getLexer().isNot(AsmToken::EndOfStatement))
3237 "unexpected token after '.bundle_lock' directive option");
3243 getStreamer().EmitBundleLock(AlignToEnd);
3247 /// ParseDirectiveBundleLock
3248 /// ::= {.bundle_lock}
3249 bool AsmParser::ParseDirectiveBundleUnlock() {
3250 CheckForValidSection();
3252 if (getLexer().isNot(AsmToken::EndOfStatement))
3253 return TokError("unexpected token in '.bundle_unlock' directive");
3256 getStreamer().EmitBundleUnlock();
3260 /// ParseDirectiveSpace
3261 /// ::= (.skip | .space) expression [ , expression ]
3262 bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3263 CheckForValidSection();
3266 if (ParseAbsoluteExpression(NumBytes))
3269 int64_t FillExpr = 0;
3270 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3271 if (getLexer().isNot(AsmToken::Comma))
3272 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3275 if (ParseAbsoluteExpression(FillExpr))
3278 if (getLexer().isNot(AsmToken::EndOfStatement))
3279 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3285 return TokError("invalid number of bytes in '" +
3286 Twine(IDVal) + "' directive");
3288 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3289 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3294 /// ParseDirectiveLEB128
3295 /// ::= (.sleb128 | .uleb128) expression
3296 bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3297 CheckForValidSection();
3298 const MCExpr *Value;
3300 if (ParseExpression(Value))
3303 if (getLexer().isNot(AsmToken::EndOfStatement))
3304 return TokError("unexpected token in directive");
3307 getStreamer().EmitSLEB128Value(Value);
3309 getStreamer().EmitULEB128Value(Value);
3314 /// ParseDirectiveSymbolAttribute
3315 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3316 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3317 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3320 SMLoc Loc = getTok().getLoc();
3322 if (ParseIdentifier(Name))
3323 return Error(Loc, "expected identifier in directive");
3325 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3327 // Assembler local symbols don't make any sense here. Complain loudly.
3328 if (Sym->isTemporary())
3329 return Error(Loc, "non-local symbol required in directive");
3331 getStreamer().EmitSymbolAttribute(Sym, Attr);
3333 if (getLexer().is(AsmToken::EndOfStatement))
3336 if (getLexer().isNot(AsmToken::Comma))
3337 return TokError("unexpected token in directive");
3346 /// ParseDirectiveComm
3347 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3348 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
3349 CheckForValidSection();
3351 SMLoc IDLoc = getLexer().getLoc();
3353 if (ParseIdentifier(Name))
3354 return TokError("expected identifier in directive");
3356 // Handle the identifier as the key symbol.
3357 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3359 if (getLexer().isNot(AsmToken::Comma))
3360 return TokError("unexpected token in directive");
3364 SMLoc SizeLoc = getLexer().getLoc();
3365 if (ParseAbsoluteExpression(Size))
3368 int64_t Pow2Alignment = 0;
3369 SMLoc Pow2AlignmentLoc;
3370 if (getLexer().is(AsmToken::Comma)) {
3372 Pow2AlignmentLoc = getLexer().getLoc();
3373 if (ParseAbsoluteExpression(Pow2Alignment))
3376 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3377 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3378 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3380 // If this target takes alignments in bytes (not log) validate and convert.
3381 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3382 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3383 if (!isPowerOf2_64(Pow2Alignment))
3384 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3385 Pow2Alignment = Log2_64(Pow2Alignment);
3389 if (getLexer().isNot(AsmToken::EndOfStatement))
3390 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3394 // NOTE: a size of zero for a .comm should create a undefined symbol
3395 // but a size of .lcomm creates a bss symbol of size zero.
3397 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3398 "be less than zero");
3400 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3401 // may internally end up wanting an alignment in bytes.
3402 // FIXME: Diagnose overflow.
3403 if (Pow2Alignment < 0)
3404 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3405 "alignment, can't be less than zero");
3407 if (!Sym->isUndefined())
3408 return Error(IDLoc, "invalid symbol redefinition");
3410 // Create the Symbol as a common or local common with Size and Pow2Alignment
3412 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3416 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3420 /// ParseDirectiveAbort
3421 /// ::= .abort [... message ...]
3422 bool AsmParser::ParseDirectiveAbort() {
3423 // FIXME: Use loc from directive.
3424 SMLoc Loc = getLexer().getLoc();
3426 StringRef Str = ParseStringToEndOfStatement();
3427 if (getLexer().isNot(AsmToken::EndOfStatement))
3428 return TokError("unexpected token in '.abort' directive");
3433 Error(Loc, ".abort detected. Assembly stopping.");
3435 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3436 // FIXME: Actually abort assembly here.
3441 /// ParseDirectiveInclude
3442 /// ::= .include "filename"
3443 bool AsmParser::ParseDirectiveInclude() {
3444 if (getLexer().isNot(AsmToken::String))
3445 return TokError("expected string in '.include' directive");
3447 std::string Filename = getTok().getString();
3448 SMLoc IncludeLoc = getLexer().getLoc();
3451 if (getLexer().isNot(AsmToken::EndOfStatement))
3452 return TokError("unexpected token in '.include' directive");
3454 // Strip the quotes.
3455 Filename = Filename.substr(1, Filename.size()-2);
3457 // Attempt to switch the lexer to the included file before consuming the end
3458 // of statement to avoid losing it when we switch.
3459 if (EnterIncludeFile(Filename)) {
3460 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3467 /// ParseDirectiveIncbin
3468 /// ::= .incbin "filename"
3469 bool AsmParser::ParseDirectiveIncbin() {
3470 if (getLexer().isNot(AsmToken::String))
3471 return TokError("expected string in '.incbin' directive");
3473 std::string Filename = getTok().getString();
3474 SMLoc IncbinLoc = getLexer().getLoc();
3477 if (getLexer().isNot(AsmToken::EndOfStatement))
3478 return TokError("unexpected token in '.incbin' directive");
3480 // Strip the quotes.
3481 Filename = Filename.substr(1, Filename.size()-2);
3483 // Attempt to process the included file.
3484 if (ProcessIncbinFile(Filename)) {
3485 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3492 /// ParseDirectiveIf
3493 /// ::= .if expression
3494 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
3495 TheCondStack.push_back(TheCondState);
3496 TheCondState.TheCond = AsmCond::IfCond;
3497 if (TheCondState.Ignore) {
3498 EatToEndOfStatement();
3501 if (ParseAbsoluteExpression(ExprValue))
3504 if (getLexer().isNot(AsmToken::EndOfStatement))
3505 return TokError("unexpected token in '.if' directive");
3509 TheCondState.CondMet = ExprValue;
3510 TheCondState.Ignore = !TheCondState.CondMet;
3516 /// ParseDirectiveIfb
3518 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3519 TheCondStack.push_back(TheCondState);
3520 TheCondState.TheCond = AsmCond::IfCond;
3522 if (TheCondState.Ignore) {
3523 EatToEndOfStatement();
3525 StringRef Str = ParseStringToEndOfStatement();
3527 if (getLexer().isNot(AsmToken::EndOfStatement))
3528 return TokError("unexpected token in '.ifb' directive");
3532 TheCondState.CondMet = ExpectBlank == Str.empty();
3533 TheCondState.Ignore = !TheCondState.CondMet;
3539 /// ParseDirectiveIfc
3540 /// ::= .ifc string1, string2
3541 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3542 TheCondStack.push_back(TheCondState);
3543 TheCondState.TheCond = AsmCond::IfCond;
3545 if (TheCondState.Ignore) {
3546 EatToEndOfStatement();
3548 StringRef Str1 = ParseStringToComma();
3550 if (getLexer().isNot(AsmToken::Comma))
3551 return TokError("unexpected token in '.ifc' directive");
3555 StringRef Str2 = ParseStringToEndOfStatement();
3557 if (getLexer().isNot(AsmToken::EndOfStatement))
3558 return TokError("unexpected token in '.ifc' directive");
3562 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3563 TheCondState.Ignore = !TheCondState.CondMet;
3569 /// ParseDirectiveIfdef
3570 /// ::= .ifdef symbol
3571 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3573 TheCondStack.push_back(TheCondState);
3574 TheCondState.TheCond = AsmCond::IfCond;
3576 if (TheCondState.Ignore) {
3577 EatToEndOfStatement();
3579 if (ParseIdentifier(Name))
3580 return TokError("expected identifier after '.ifdef'");
3584 MCSymbol *Sym = getContext().LookupSymbol(Name);
3587 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3589 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3590 TheCondState.Ignore = !TheCondState.CondMet;
3596 /// ParseDirectiveElseIf
3597 /// ::= .elseif expression
3598 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3599 if (TheCondState.TheCond != AsmCond::IfCond &&
3600 TheCondState.TheCond != AsmCond::ElseIfCond)
3601 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3603 TheCondState.TheCond = AsmCond::ElseIfCond;
3605 bool LastIgnoreState = false;
3606 if (!TheCondStack.empty())
3607 LastIgnoreState = TheCondStack.back().Ignore;
3608 if (LastIgnoreState || TheCondState.CondMet) {
3609 TheCondState.Ignore = true;
3610 EatToEndOfStatement();
3614 if (ParseAbsoluteExpression(ExprValue))
3617 if (getLexer().isNot(AsmToken::EndOfStatement))
3618 return TokError("unexpected token in '.elseif' directive");
3621 TheCondState.CondMet = ExprValue;
3622 TheCondState.Ignore = !TheCondState.CondMet;
3628 /// ParseDirectiveElse
3630 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
3631 if (getLexer().isNot(AsmToken::EndOfStatement))
3632 return TokError("unexpected token in '.else' directive");
3636 if (TheCondState.TheCond != AsmCond::IfCond &&
3637 TheCondState.TheCond != AsmCond::ElseIfCond)
3638 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3640 TheCondState.TheCond = AsmCond::ElseCond;
3641 bool LastIgnoreState = false;
3642 if (!TheCondStack.empty())
3643 LastIgnoreState = TheCondStack.back().Ignore;
3644 if (LastIgnoreState || TheCondState.CondMet)
3645 TheCondState.Ignore = true;
3647 TheCondState.Ignore = false;
3652 /// ParseDirectiveEndIf
3654 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
3655 if (getLexer().isNot(AsmToken::EndOfStatement))
3656 return TokError("unexpected token in '.endif' directive");
3660 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3661 TheCondStack.empty())
3662 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3664 if (!TheCondStack.empty()) {
3665 TheCondState = TheCondStack.back();
3666 TheCondStack.pop_back();
3672 void AsmParser::initializeDirectiveKindMap() {
3673 DirectiveKindMap[".set"] = DK_SET;
3674 DirectiveKindMap[".equ"] = DK_EQU;
3675 DirectiveKindMap[".equiv"] = DK_EQUIV;
3676 DirectiveKindMap[".ascii"] = DK_ASCII;
3677 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3678 DirectiveKindMap[".string"] = DK_STRING;
3679 DirectiveKindMap[".byte"] = DK_BYTE;
3680 DirectiveKindMap[".short"] = DK_SHORT;
3681 DirectiveKindMap[".value"] = DK_VALUE;
3682 DirectiveKindMap[".2byte"] = DK_2BYTE;
3683 DirectiveKindMap[".long"] = DK_LONG;
3684 DirectiveKindMap[".int"] = DK_INT;
3685 DirectiveKindMap[".4byte"] = DK_4BYTE;
3686 DirectiveKindMap[".quad"] = DK_QUAD;
3687 DirectiveKindMap[".8byte"] = DK_8BYTE;
3688 DirectiveKindMap[".single"] = DK_SINGLE;
3689 DirectiveKindMap[".float"] = DK_FLOAT;
3690 DirectiveKindMap[".double"] = DK_DOUBLE;
3691 DirectiveKindMap[".align"] = DK_ALIGN;
3692 DirectiveKindMap[".align32"] = DK_ALIGN32;
3693 DirectiveKindMap[".balign"] = DK_BALIGN;
3694 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3695 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3696 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3697 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3698 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3699 DirectiveKindMap[".org"] = DK_ORG;
3700 DirectiveKindMap[".fill"] = DK_FILL;
3701 DirectiveKindMap[".zero"] = DK_ZERO;
3702 DirectiveKindMap[".extern"] = DK_EXTERN;
3703 DirectiveKindMap[".globl"] = DK_GLOBL;
3704 DirectiveKindMap[".global"] = DK_GLOBAL;
3705 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3706 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3707 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3708 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3709 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3710 DirectiveKindMap[".reference"] = DK_REFERENCE;
3711 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3712 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3713 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3714 DirectiveKindMap[".comm"] = DK_COMM;
3715 DirectiveKindMap[".common"] = DK_COMMON;
3716 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3717 DirectiveKindMap[".abort"] = DK_ABORT;
3718 DirectiveKindMap[".include"] = DK_INCLUDE;
3719 DirectiveKindMap[".incbin"] = DK_INCBIN;
3720 DirectiveKindMap[".code16"] = DK_CODE16;
3721 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3722 DirectiveKindMap[".rept"] = DK_REPT;
3723 DirectiveKindMap[".irp"] = DK_IRP;
3724 DirectiveKindMap[".irpc"] = DK_IRPC;
3725 DirectiveKindMap[".endr"] = DK_ENDR;
3726 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3727 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3728 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3729 DirectiveKindMap[".if"] = DK_IF;
3730 DirectiveKindMap[".ifb"] = DK_IFB;
3731 DirectiveKindMap[".ifnb"] = DK_IFNB;
3732 DirectiveKindMap[".ifc"] = DK_IFC;
3733 DirectiveKindMap[".ifnc"] = DK_IFNC;
3734 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3735 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3736 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3737 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3738 DirectiveKindMap[".else"] = DK_ELSE;
3739 DirectiveKindMap[".endif"] = DK_ENDIF;
3740 DirectiveKindMap[".skip"] = DK_SKIP;
3741 DirectiveKindMap[".space"] = DK_SPACE;
3742 DirectiveKindMap[".file"] = DK_FILE;
3743 DirectiveKindMap[".line"] = DK_LINE;
3744 DirectiveKindMap[".loc"] = DK_LOC;
3745 DirectiveKindMap[".stabs"] = DK_STABS;
3746 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3747 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3748 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3749 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3750 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3751 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3752 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3753 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3754 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3755 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3756 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3757 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3758 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3759 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3760 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3761 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3762 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3763 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3764 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3765 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3766 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3767 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3768 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3769 DirectiveKindMap[".macro"] = DK_MACRO;
3770 DirectiveKindMap[".endm"] = DK_ENDM;
3771 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3772 DirectiveKindMap[".purgem"] = DK_PURGEM;
3776 MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3777 AsmToken EndToken, StartToken = getTok();
3779 unsigned NestLevel = 0;
3781 // Check whether we have reached the end of the file.
3782 if (getLexer().is(AsmToken::Eof)) {
3783 Error(DirectiveLoc, "no matching '.endr' in definition");
3787 if (Lexer.is(AsmToken::Identifier) &&
3788 (getTok().getIdentifier() == ".rept")) {
3792 // Otherwise, check whether we have reached the .endr.
3793 if (Lexer.is(AsmToken::Identifier) &&
3794 getTok().getIdentifier() == ".endr") {
3795 if (NestLevel == 0) {
3796 EndToken = getTok();
3798 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3799 TokError("unexpected token in '.endr' directive");
3807 // Otherwise, scan till the end of the statement.
3808 EatToEndOfStatement();
3811 const char *BodyStart = StartToken.getLoc().getPointer();
3812 const char *BodyEnd = EndToken.getLoc().getPointer();
3813 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3815 // We Are Anonymous.
3817 MCAsmMacroParameters Parameters;
3818 return new MCAsmMacro(Name, Body, Parameters);
3821 void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3822 raw_svector_ostream &OS) {
3825 MemoryBuffer *Instantiation =
3826 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3828 // Create the macro instantiation object and add to the current macro
3829 // instantiation stack.
3830 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3834 ActiveMacros.push_back(MI);
3836 // Jump to the macro instantiation and prime the lexer.
3837 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3838 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3842 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3844 if (ParseAbsoluteExpression(Count))
3845 return TokError("unexpected token in '.rept' directive");
3848 return TokError("Count is negative");
3850 if (Lexer.isNot(AsmToken::EndOfStatement))
3851 return TokError("unexpected token in '.rept' directive");
3853 // Eat the end of statement.
3856 // Lex the rept definition.
3857 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3861 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3862 // to hold the macro body with substitutions.
3863 SmallString<256> Buf;
3864 MCAsmMacroParameters Parameters;
3865 MCAsmMacroArguments A;
3866 raw_svector_ostream OS(Buf);
3868 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3871 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3876 /// ParseDirectiveIrp
3877 /// ::= .irp symbol,values
3878 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3879 MCAsmMacroParameters Parameters;
3880 MCAsmMacroParameter Parameter;
3882 if (ParseIdentifier(Parameter.first))
3883 return TokError("expected identifier in '.irp' directive");
3885 Parameters.push_back(Parameter);
3887 if (Lexer.isNot(AsmToken::Comma))
3888 return TokError("expected comma in '.irp' directive");
3892 MCAsmMacroArguments A;
3893 if (ParseMacroArguments(0, A))
3896 // Eat the end of statement.
3899 // Lex the irp definition.
3900 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3904 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3905 // to hold the macro body with substitutions.
3906 SmallString<256> Buf;
3907 raw_svector_ostream OS(Buf);
3909 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3910 MCAsmMacroArguments Args;
3913 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3917 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3922 /// ParseDirectiveIrpc
3923 /// ::= .irpc symbol,values
3924 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3925 MCAsmMacroParameters Parameters;
3926 MCAsmMacroParameter Parameter;
3928 if (ParseIdentifier(Parameter.first))
3929 return TokError("expected identifier in '.irpc' directive");
3931 Parameters.push_back(Parameter);
3933 if (Lexer.isNot(AsmToken::Comma))
3934 return TokError("expected comma in '.irpc' directive");
3938 MCAsmMacroArguments A;
3939 if (ParseMacroArguments(0, A))
3942 if (A.size() != 1 || A.front().size() != 1)
3943 return TokError("unexpected token in '.irpc' directive");
3945 // Eat the end of statement.
3948 // Lex the irpc definition.
3949 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3953 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3954 // to hold the macro body with substitutions.
3955 SmallString<256> Buf;
3956 raw_svector_ostream OS(Buf);
3958 StringRef Values = A.front().front().getString();
3959 std::size_t I, End = Values.size();
3960 for (I = 0; I < End; ++I) {
3961 MCAsmMacroArgument Arg;
3962 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3964 MCAsmMacroArguments Args;
3965 Args.push_back(Arg);
3967 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3971 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3976 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3977 if (ActiveMacros.empty())
3978 return TokError("unmatched '.endr' directive");
3980 // The only .repl that should get here are the ones created by
3981 // InstantiateMacroLikeBody.
3982 assert(getLexer().is(AsmToken::EndOfStatement));
3988 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3989 const MCExpr *Value;
3990 SMLoc ExprLoc = getLexer().getLoc();
3991 if (ParseExpression(Value))
3993 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3995 return Error(ExprLoc, "unexpected expression in _emit");
3996 uint64_t IntValue = MCE->getValue();
3997 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3998 return Error(ExprLoc, "literal value out of range for directive");
4000 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
4004 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
4005 unsigned &NumOutputs, unsigned &NumInputs,
4006 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4007 SmallVectorImpl<std::string> &Constraints,
4008 SmallVectorImpl<std::string> &Clobbers,
4009 const MCInstrInfo *MII,
4010 const MCInstPrinter *IP,
4011 MCAsmParserSemaCallback &SI) {
4012 SmallVector<void *, 4> InputDecls;
4013 SmallVector<void *, 4> OutputDecls;
4014 SmallVector<bool, 4> InputDeclsAddressOf;
4015 SmallVector<bool, 4> OutputDeclsAddressOf;
4016 SmallVector<std::string, 4> InputConstraints;
4017 SmallVector<std::string, 4> OutputConstraints;
4018 std::set<std::string> ClobberRegs;
4020 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
4025 // While we have input, parse each statement.
4026 unsigned InputIdx = 0;
4027 unsigned OutputIdx = 0;
4028 while (getLexer().isNot(AsmToken::Eof)) {
4029 ParseStatementInfo Info(&AsmStrRewrites);
4030 if (ParseStatement(Info))
4033 if (Info.ParseError)
4036 if (Info.Opcode != ~0U) {
4037 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4039 // Build the list of clobbers, outputs and inputs.
4040 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4041 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4044 if (Operand->isImm()) {
4045 if (Operand->needAsmRewrite())
4046 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
4047 Operand->getStartLoc()));
4051 // Register operand.
4052 if (Operand->isReg() && !Operand->needAddressOf()) {
4053 unsigned NumDefs = Desc.getNumDefs();
4055 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
4057 raw_string_ostream OS(Reg);
4058 IP->printRegName(OS, Operand->getReg());
4059 ClobberRegs.insert(StringRef(OS.str()));
4064 // Expr/Input or Output.
4066 unsigned Length, Size, Type;
4067 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
4068 Length, Size, Type, IsVarDecl);
4070 bool isOutput = (i == 1) && Desc.mayStore();
4071 if (Operand->isMem() && Operand->needSizeDirective())
4072 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
4073 Operand->getStartLoc(),
4075 Operand->getMemSize()));
4077 std::string Constraint = "=";
4079 OutputDecls.push_back(OpDecl);
4080 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4081 Constraint += Operand->getConstraint().str();
4082 OutputConstraints.push_back(Constraint);
4083 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
4084 Operand->getStartLoc(),
4085 Operand->getNameLen()));
4087 InputDecls.push_back(OpDecl);
4088 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4089 InputConstraints.push_back(Operand->getConstraint().str());
4090 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
4091 Operand->getStartLoc(),
4092 Operand->getNameLen()));
4099 // Set the number of Outputs and Inputs.
4100 NumOutputs = OutputDecls.size();
4101 NumInputs = InputDecls.size();
4103 // Set the unique clobbers.
4104 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
4105 E = ClobberRegs.end(); I != E; ++I)
4106 Clobbers.push_back(*I);
4108 // Merge the various outputs and inputs. Output are expected first.
4109 if (NumOutputs || NumInputs) {
4110 unsigned NumExprs = NumOutputs + NumInputs;
4111 OpDecls.resize(NumExprs);
4112 Constraints.resize(NumExprs);
4113 for (unsigned i = 0; i < NumOutputs; ++i) {
4114 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4115 Constraints[i] = OutputConstraints[i];
4117 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4118 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4119 Constraints[j] = InputConstraints[i];
4123 // Build the IR assembly string.
4124 std::string AsmStringIR;
4125 AsmRewriteKind PrevKind = AOK_Imm;
4126 raw_string_ostream OS(AsmStringIR);
4127 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4128 for (SmallVectorImpl<struct AsmRewrite>::iterator
4129 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
4130 const char *Loc = (*I).Loc.getPointer();
4132 AsmRewriteKind Kind = (*I).Kind;
4134 // Emit everything up to the immediate/expression. If the previous rewrite
4135 // was a size directive, then this has already been done.
4136 if (PrevKind != AOK_SizeDirective)
4137 OS << StringRef(Start, Loc - Start);
4140 // Skip the original expression.
4141 if (Kind == AOK_Skip) {
4142 Start = Loc + (*I).Len;
4146 // Rewrite expressions in $N notation.
4164 case AOK_SizeDirective:
4167 case 8: OS << "byte ptr "; break;
4168 case 16: OS << "word ptr "; break;
4169 case 32: OS << "dword ptr "; break;
4170 case 64: OS << "qword ptr "; break;
4171 case 80: OS << "xword ptr "; break;
4172 case 128: OS << "xmmword ptr "; break;
4173 case 256: OS << "ymmword ptr "; break;
4179 case AOK_DotOperator:
4184 // Skip the original expression.
4185 if (Kind != AOK_SizeDirective)
4186 Start = Loc + (*I).Len;
4189 // Emit the remainder of the asm string.
4190 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4191 if (Start != AsmEnd)
4192 OS << StringRef(Start, AsmEnd - Start);
4194 AsmString = OS.str();
4198 /// \brief Create an MCAsmParser instance.
4199 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4200 MCContext &C, MCStreamer &Out,
4201 const MCAsmInfo &MAI) {
4202 return new AsmParser(SM, C, Out, MAI);