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/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCParser/AsmCond.h"
26 #include "llvm/MC/MCParser/AsmLexer.h"
27 #include "llvm/MC/MCParser/MCAsmParser.h"
28 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/MCTargetAsmParser.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/raw_ostream.h"
47 FatalAssemblerWarnings("fatal-assembler-warnings",
48 cl::desc("Consider warnings as error"));
50 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
54 /// \brief Helper types for tracking macro definitions.
55 typedef std::vector<AsmToken> MCAsmMacroArgument;
56 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
58 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
63 MCAsmMacroParameters Parameters;
66 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
67 Name(N), Body(B), Parameters(P) {}
69 MCAsmMacro(const MCAsmMacro& Other)
70 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
73 /// \brief Helper class for storing information about an active macro
75 struct MacroInstantiation {
76 /// The macro being instantiated.
77 const MCAsmMacro *TheMacro;
79 /// The macro instantiation with substitutions.
80 MemoryBuffer *Instantiation;
82 /// The location of the instantiation.
83 SMLoc InstantiationLoc;
85 /// The buffer where parsing should resume upon instantiation completion.
88 /// The location where parsing should resume upon instantiation completion.
92 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
96 struct ParseStatementInfo {
97 /// ParsedOperands - The parsed operands from the last parsed statement.
98 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
100 /// Opcode - The opcode from the last parsed instruction.
103 /// Error - Was there an error parsing the inline assembly?
106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112 ~ParseStatementInfo() {
113 // Free any parsed operands.
114 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
115 delete ParsedOperands[i];
116 ParsedOperands.clear();
120 /// \brief The concrete assembly parser instance.
121 class AsmParser : public MCAsmParser {
122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
128 const MCAsmInfo &MAI;
130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
132 MCAsmParserExtension *PlatformParser;
134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
141 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
142 /// extensions. Extensions register themselves in this map by calling
143 /// addDirectiveHandler.
144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
146 /// MacroMap - Map of currently defined macros.
147 StringMap<MCAsmMacro*> MacroMap;
149 /// ActiveMacros - Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
152 /// MacroLikeBodies - List of bodies of anonymous macros.
153 std::deque<MCAsmMacro> MacroLikeBodies;
155 /// Boolean tracking whether macro substitution is enabled.
156 unsigned MacrosEnabledFlag : 1;
158 /// Flag tracking whether any errors have been encountered.
159 unsigned HadError : 1;
161 /// The values from the last parsed cpp hash file line comment if any.
162 StringRef CppHashFilename;
163 int64_t CppHashLineNumber;
166 /// When generating dwarf for assembly source files we need to calculate the
167 /// logical line number based on the last parsed cpp hash file line comment
168 /// and current line. Since this is slow and messes up the SourceMgr's
169 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
170 SMLoc LastQueryIDLoc;
172 unsigned LastQueryLine;
174 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
175 unsigned AssemblerDialect;
177 /// IsDarwin - is Darwin compatibility enabled?
180 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
181 bool ParsingInlineAsm;
184 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
185 const MCAsmInfo &MAI);
186 virtual ~AsmParser();
188 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
190 virtual void addDirectiveHandler(StringRef Directive,
191 ExtensionDirectiveHandler Handler) {
192 ExtensionDirectiveMap[Directive] = Handler;
196 /// @name MCAsmParser Interface
199 virtual SourceMgr &getSourceManager() { return SrcMgr; }
200 virtual MCAsmLexer &getLexer() { return Lexer; }
201 virtual MCContext &getContext() { return Ctx; }
202 virtual MCStreamer &getStreamer() { return Out; }
203 virtual unsigned getAssemblerDialect() {
204 if (AssemblerDialect == ~0U)
205 return MAI.getAssemblerDialect();
207 return AssemblerDialect;
209 virtual void setAssemblerDialect(unsigned i) {
210 AssemblerDialect = i;
213 virtual bool Warning(SMLoc L, const Twine &Msg,
214 ArrayRef<SMRange> Ranges = None);
215 virtual bool Error(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None);
218 virtual const AsmToken &Lex();
220 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
221 bool isParsingInlineAsm() { return ParsingInlineAsm; }
223 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
224 unsigned &NumOutputs, unsigned &NumInputs,
225 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
226 SmallVectorImpl<std::string> &Constraints,
227 SmallVectorImpl<std::string> &Clobbers,
228 const MCInstrInfo *MII,
229 const MCInstPrinter *IP,
230 MCAsmParserSemaCallback &SI);
232 bool parseExpression(const MCExpr *&Res);
233 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
234 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
235 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
236 virtual bool parseAbsoluteExpression(int64_t &Res);
238 /// parseIdentifier - Parse an identifier or string (as a quoted identifier)
239 /// and set \p Res to the identifier contents.
240 virtual bool parseIdentifier(StringRef &Res);
241 virtual void eatToEndOfStatement();
243 virtual void checkForValidSection();
248 bool ParseStatement(ParseStatementInfo &Info);
249 void EatToEndOfLine();
250 bool ParseCppHashLineFilenameComment(const SMLoc &L);
252 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
253 MCAsmMacroParameters Parameters);
254 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
255 const MCAsmMacroParameters &Parameters,
256 const MCAsmMacroArguments &A,
259 /// \brief Are macros enabled in the parser?
260 bool MacrosEnabled() {return MacrosEnabledFlag;}
262 /// \brief Control a flag in the parser that enables or disables macros.
263 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
265 /// \brief Lookup a previously defined macro.
266 /// \param Name Macro name.
267 /// \returns Pointer to macro. NULL if no such macro was defined.
268 const MCAsmMacro* LookupMacro(StringRef Name);
270 /// \brief Define a new macro with the given name and information.
271 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
273 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
274 void UndefineMacro(StringRef Name);
276 /// \brief Are we inside a macro instantiation?
277 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
279 /// \brief Handle entry to macro instantiation.
281 /// \param M The macro.
282 /// \param NameLoc Instantiation location.
283 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
285 /// \brief Handle exit from macro instantiation.
286 void HandleMacroExit();
288 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
289 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
290 /// correct delimiter by the method.
291 bool ParseMacroArgument(MCAsmMacroArgument &MA,
292 AsmToken::TokenKind &ArgumentDelimiter);
294 /// \brief Parse all macro arguments for a given macro.
295 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
297 void PrintMacroInstantiations();
298 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
299 ArrayRef<SMRange> Ranges = None) const {
300 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
302 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
304 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
305 bool EnterIncludeFile(const std::string &Filename);
306 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
307 /// This returns true on failure.
308 bool ProcessIncbinFile(const std::string &Filename);
310 /// \brief Reset the current lexer position to that given by \p Loc. The
311 /// current token is not set; clients should ensure Lex() is called
314 /// \param InBuffer If not -1, should be the known buffer id that contains the
316 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
318 /// \brief Parse up to the end of statement and a return the contents from the
319 /// current token until the end of the statement; the current token on exit
320 /// will be either the EndOfStatement or EOF.
321 virtual StringRef parseStringToEndOfStatement();
323 /// \brief Parse until the end of a statement or a comma is encountered,
324 /// return the contents from the current token up to the end or comma.
325 StringRef ParseStringToComma();
327 bool ParseAssignment(StringRef Name, bool allow_redef,
328 bool NoDeadStrip = false);
330 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
331 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
332 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
333 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
335 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
337 // Generic (target and platform independent) directive parsing.
339 DK_NO_DIRECTIVE, // Placeholder
340 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
341 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
342 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
343 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
344 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
345 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
346 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
347 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
348 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
349 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
350 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
351 DK_ELSEIF, DK_ELSE, DK_ENDIF,
352 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
353 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
354 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
355 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
356 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
357 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
359 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
360 DK_SLEB128, DK_ULEB128
363 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
364 /// directives parsed by this class.
365 StringMap<DirectiveKind> DirectiveKindMap;
367 // ".ascii", ".asciz", ".string"
368 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
369 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
370 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
371 bool ParseDirectiveFill(); // ".fill"
372 bool ParseDirectiveZero(); // ".zero"
373 // ".set", ".equ", ".equiv"
374 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
375 bool ParseDirectiveOrg(); // ".org"
376 // ".align{,32}", ".p2align{,w,l}"
377 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
379 // ".file", ".line", ".loc", ".stabs"
380 bool ParseDirectiveFile(SMLoc DirectiveLoc);
381 bool ParseDirectiveLine();
382 bool ParseDirectiveLoc();
383 bool ParseDirectiveStabs();
386 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
387 bool ParseDirectiveCFISections();
388 bool ParseDirectiveCFIStartProc();
389 bool ParseDirectiveCFIEndProc();
390 bool ParseDirectiveCFIDefCfaOffset();
391 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
392 bool ParseDirectiveCFIAdjustCfaOffset();
393 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
394 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
395 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
396 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
397 bool ParseDirectiveCFIRememberState();
398 bool ParseDirectiveCFIRestoreState();
399 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
400 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
401 bool ParseDirectiveCFIEscape();
402 bool ParseDirectiveCFISignalFrame();
403 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
406 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
407 bool ParseDirectiveEndMacro(StringRef Directive);
408 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
409 bool ParseDirectiveMacrosOnOff(StringRef Directive);
411 // ".bundle_align_mode"
412 bool ParseDirectiveBundleAlignMode();
414 bool ParseDirectiveBundleLock();
416 bool ParseDirectiveBundleUnlock();
419 bool ParseDirectiveSpace(StringRef IDVal);
421 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
422 bool ParseDirectiveLEB128(bool Signed);
424 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
425 /// accepts a single symbol (which should be a label or an external).
426 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
428 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
430 bool ParseDirectiveAbort(); // ".abort"
431 bool ParseDirectiveInclude(); // ".include"
432 bool ParseDirectiveIncbin(); // ".incbin"
434 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
435 // ".ifb" or ".ifnb", depending on ExpectBlank.
436 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
437 // ".ifc" or ".ifnc", depending on ExpectEqual.
438 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
439 // ".ifdef" or ".ifndef", depending on expect_defined
440 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
441 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
442 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
443 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
444 virtual bool parseEscapedString(std::string &Data);
446 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
447 MCSymbolRefExpr::VariantKind Variant);
449 // Macro-like directives
450 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
451 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
452 raw_svector_ostream &OS);
453 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
454 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
455 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
456 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
458 // "_emit" or "__emit"
459 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
463 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
465 void initializeDirectiveKindMap();
471 extern MCAsmParserExtension *createDarwinAsmParser();
472 extern MCAsmParserExtension *createELFAsmParser();
473 extern MCAsmParserExtension *createCOFFAsmParser();
477 enum { DEFAULT_ADDRSPACE = 0 };
479 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
480 MCStreamer &_Out, const MCAsmInfo &_MAI)
481 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
483 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
484 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
485 // Save the old handler.
486 SavedDiagHandler = SrcMgr.getDiagHandler();
487 SavedDiagContext = SrcMgr.getDiagContext();
488 // Set our own handler which calls the saved handler.
489 SrcMgr.setDiagHandler(DiagHandler, this);
490 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
492 // Initialize the platform / file format parser.
494 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
496 if (_MAI.hasMicrosoftFastStdCallMangling()) {
497 PlatformParser = createCOFFAsmParser();
498 PlatformParser->Initialize(*this);
499 } else if (_MAI.hasSubsectionsViaSymbols()) {
500 PlatformParser = createDarwinAsmParser();
501 PlatformParser->Initialize(*this);
504 PlatformParser = createELFAsmParser();
505 PlatformParser->Initialize(*this);
508 initializeDirectiveKindMap();
511 AsmParser::~AsmParser() {
512 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
514 // Destroy any macros.
515 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
516 ie = MacroMap.end(); it != ie; ++it)
517 delete it->getValue();
519 delete PlatformParser;
522 void AsmParser::PrintMacroInstantiations() {
523 // Print the active macro instantiation stack.
524 for (std::vector<MacroInstantiation*>::const_reverse_iterator
525 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
526 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
527 "while in macro instantiation");
530 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
531 if (FatalAssemblerWarnings)
532 return Error(L, Msg, Ranges);
533 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
534 PrintMacroInstantiations();
538 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
540 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
541 PrintMacroInstantiations();
545 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
546 std::string IncludedFile;
547 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
553 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
558 /// Process the specified .incbin file by searching for it in the include paths
559 /// then just emitting the byte contents of the file to the streamer. This
560 /// returns true on failure.
561 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
562 std::string IncludedFile;
563 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
567 // Pick up the bytes from the file and emit them.
568 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
572 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
573 if (InBuffer != -1) {
574 CurBuffer = InBuffer;
576 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
578 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
581 const AsmToken &AsmParser::Lex() {
582 const AsmToken *tok = &Lexer.Lex();
584 if (tok->is(AsmToken::Eof)) {
585 // If this is the end of an included file, pop the parent file off the
587 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
588 if (ParentIncludeLoc != SMLoc()) {
589 JumpToLoc(ParentIncludeLoc);
594 if (tok->is(AsmToken::Error))
595 Error(Lexer.getErrLoc(), Lexer.getErr());
600 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
601 // Create the initial section, if requested.
602 if (!NoInitialTextSection)
609 AsmCond StartingCondState = TheCondState;
611 // If we are generating dwarf for assembly source files save the initial text
612 // section and generate a .file directive.
613 if (getContext().getGenDwarfForAssembly()) {
614 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
615 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
616 getStreamer().EmitLabel(SectionStartSym);
617 getContext().setGenDwarfSectionStartSym(SectionStartSym);
618 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
620 getContext().getMainFileName());
623 // While we have input, parse each statement.
624 while (Lexer.isNot(AsmToken::Eof)) {
625 ParseStatementInfo Info;
626 if (!ParseStatement(Info)) continue;
628 // We had an error, validate that one was emitted and recover by skipping to
630 assert(HadError && "Parse statement returned an error, but none emitted!");
631 eatToEndOfStatement();
634 if (TheCondState.TheCond != StartingCondState.TheCond ||
635 TheCondState.Ignore != StartingCondState.Ignore)
636 return TokError("unmatched .ifs or .elses");
638 // Check to see there are no empty DwarfFile slots.
639 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
640 getContext().getMCDwarfFiles();
641 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
642 if (!MCDwarfFiles[i])
643 TokError("unassigned file number: " + Twine(i) + " for .file directives");
646 // Check to see that all assembler local symbols were actually defined.
647 // Targets that don't do subsections via symbols may not want this, though,
648 // so conservatively exclude them. Only do this if we're finalizing, though,
649 // as otherwise we won't necessarilly have seen everything yet.
650 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
651 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
652 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
655 MCSymbol *Sym = i->getValue();
656 // Variable symbols may not be marked as defined, so check those
657 // explicitly. If we know it's a variable, we have a definition for
658 // the purposes of this check.
659 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
660 // FIXME: We would really like to refer back to where the symbol was
661 // first referenced for a source location. We need to add something
662 // to track that. Currently, we just point to the end of the file.
663 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
664 "assembler local symbol '" + Sym->getName() +
670 // Finalize the output stream if there are no errors and if the client wants
672 if (!HadError && !NoFinalize)
678 void AsmParser::checkForValidSection() {
679 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
680 TokError("expected section directive before assembly directive");
681 Out.InitToTextSection();
685 /// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
686 void AsmParser::eatToEndOfStatement() {
687 while (Lexer.isNot(AsmToken::EndOfStatement) &&
688 Lexer.isNot(AsmToken::Eof))
692 if (Lexer.is(AsmToken::EndOfStatement))
696 StringRef AsmParser::parseStringToEndOfStatement() {
697 const char *Start = getTok().getLoc().getPointer();
699 while (Lexer.isNot(AsmToken::EndOfStatement) &&
700 Lexer.isNot(AsmToken::Eof))
703 const char *End = getTok().getLoc().getPointer();
704 return StringRef(Start, End - Start);
707 StringRef AsmParser::ParseStringToComma() {
708 const char *Start = getTok().getLoc().getPointer();
710 while (Lexer.isNot(AsmToken::EndOfStatement) &&
711 Lexer.isNot(AsmToken::Comma) &&
712 Lexer.isNot(AsmToken::Eof))
715 const char *End = getTok().getLoc().getPointer();
716 return StringRef(Start, End - Start);
719 /// ParseParenExpr - Parse a paren expression and return it.
720 /// NOTE: This assumes the leading '(' has already been consumed.
722 /// parenexpr ::= expr)
724 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
725 if (parseExpression(Res)) return true;
726 if (Lexer.isNot(AsmToken::RParen))
727 return TokError("expected ')' in parentheses expression");
728 EndLoc = Lexer.getTok().getEndLoc();
733 /// ParseBracketExpr - Parse a bracket expression and return it.
734 /// NOTE: This assumes the leading '[' has already been consumed.
736 /// bracketexpr ::= expr]
738 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
739 if (parseExpression(Res)) return true;
740 if (Lexer.isNot(AsmToken::RBrac))
741 return TokError("expected ']' in brackets expression");
742 EndLoc = Lexer.getTok().getEndLoc();
747 /// ParsePrimaryExpr - Parse a primary expression and return it.
748 /// primaryexpr ::= (parenexpr
749 /// primaryexpr ::= symbol
750 /// primaryexpr ::= number
751 /// primaryexpr ::= '.'
752 /// primaryexpr ::= ~,+,- primaryexpr
753 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
754 SMLoc FirstTokenLoc = getLexer().getLoc();
755 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
756 switch (FirstTokenKind) {
758 return TokError("unknown token in expression");
759 // If we have an error assume that we've already handled it.
760 case AsmToken::Error:
762 case AsmToken::Exclaim:
763 Lex(); // Eat the operator.
764 if (ParsePrimaryExpr(Res, EndLoc))
766 Res = MCUnaryExpr::CreateLNot(Res, getContext());
768 case AsmToken::Dollar:
769 case AsmToken::String:
770 case AsmToken::Identifier: {
771 StringRef Identifier;
772 if (parseIdentifier(Identifier)) {
773 if (FirstTokenKind == AsmToken::Dollar)
774 return Error(FirstTokenLoc, "invalid token in expression");
778 EndLoc = SMLoc::getFromPointer(Identifier.end());
780 // This is a symbol reference.
781 std::pair<StringRef, StringRef> Split = Identifier.split('@');
782 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
784 // Lookup the symbol variant if used.
785 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
786 if (Split.first.size() != Identifier.size()) {
787 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
788 if (Variant == MCSymbolRefExpr::VK_Invalid) {
789 Variant = MCSymbolRefExpr::VK_None;
790 return TokError("invalid variant '" + Split.second + "'");
794 // If this is an absolute variable reference, substitute it now to preserve
795 // semantics in the face of reassignment.
796 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
798 return Error(EndLoc, "unexpected modifier on variable reference");
800 Res = Sym->getVariableValue();
804 // Otherwise create a symbol ref.
805 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
808 case AsmToken::Integer: {
809 SMLoc Loc = getTok().getLoc();
810 int64_t IntVal = getTok().getIntVal();
811 Res = MCConstantExpr::Create(IntVal, getContext());
812 EndLoc = Lexer.getTok().getEndLoc();
814 // Look for 'b' or 'f' following an Integer as a directional label
815 if (Lexer.getKind() == AsmToken::Identifier) {
816 StringRef IDVal = getTok().getString();
817 // Lookup the symbol variant if used.
818 std::pair<StringRef, StringRef> Split = IDVal.split('@');
819 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
820 if (Split.first.size() != IDVal.size()) {
821 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
822 if (Variant == MCSymbolRefExpr::VK_Invalid) {
823 Variant = MCSymbolRefExpr::VK_None;
824 return TokError("invalid variant '" + Split.second + "'");
828 if (IDVal == "f" || IDVal == "b"){
829 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
830 IDVal == "f" ? 1 : 0);
831 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
832 if (IDVal == "b" && Sym->isUndefined())
833 return Error(Loc, "invalid reference to undefined symbol");
834 EndLoc = Lexer.getTok().getEndLoc();
835 Lex(); // Eat identifier.
840 case AsmToken::Real: {
841 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
842 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
843 Res = MCConstantExpr::Create(IntVal, getContext());
844 EndLoc = Lexer.getTok().getEndLoc();
848 case AsmToken::Dot: {
849 // This is a '.' reference, which references the current PC. Emit a
850 // temporary label to the streamer and refer to it.
851 MCSymbol *Sym = Ctx.CreateTempSymbol();
853 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
854 EndLoc = Lexer.getTok().getEndLoc();
855 Lex(); // Eat identifier.
858 case AsmToken::LParen:
859 Lex(); // Eat the '('.
860 return ParseParenExpr(Res, EndLoc);
861 case AsmToken::LBrac:
862 if (!PlatformParser->HasBracketExpressions())
863 return TokError("brackets expression not supported on this target");
864 Lex(); // Eat the '['.
865 return ParseBracketExpr(Res, EndLoc);
866 case AsmToken::Minus:
867 Lex(); // Eat the operator.
868 if (ParsePrimaryExpr(Res, EndLoc))
870 Res = MCUnaryExpr::CreateMinus(Res, getContext());
873 Lex(); // Eat the operator.
874 if (ParsePrimaryExpr(Res, EndLoc))
876 Res = MCUnaryExpr::CreatePlus(Res, getContext());
878 case AsmToken::Tilde:
879 Lex(); // Eat the operator.
880 if (ParsePrimaryExpr(Res, EndLoc))
882 Res = MCUnaryExpr::CreateNot(Res, getContext());
887 bool AsmParser::parseExpression(const MCExpr *&Res) {
889 return parseExpression(Res, EndLoc);
892 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
893 return ParsePrimaryExpr(Res, EndLoc);
897 AsmParser::ApplyModifierToExpr(const MCExpr *E,
898 MCSymbolRefExpr::VariantKind Variant) {
899 // Recurse over the given expression, rebuilding it to apply the given variant
900 // if there is exactly one symbol.
901 switch (E->getKind()) {
903 case MCExpr::Constant:
906 case MCExpr::SymbolRef: {
907 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
909 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
910 TokError("invalid variant on expression '" +
911 getTok().getIdentifier() + "' (already modified)");
915 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
918 case MCExpr::Unary: {
919 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
920 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
923 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
926 case MCExpr::Binary: {
927 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
928 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
929 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
934 if (!LHS) LHS = BE->getLHS();
935 if (!RHS) RHS = BE->getRHS();
937 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
941 llvm_unreachable("Invalid expression kind!");
944 /// parseExpression - Parse an expression and return it.
946 /// expr ::= expr &&,|| expr -> lowest.
947 /// expr ::= expr |,^,&,! expr
948 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
949 /// expr ::= expr <<,>> expr
950 /// expr ::= expr +,- expr
951 /// expr ::= expr *,/,% expr -> highest.
952 /// expr ::= primaryexpr
954 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
955 // Parse the expression.
957 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
960 // As a special case, we support 'a op b @ modifier' by rewriting the
961 // expression to include the modifier. This is inefficient, but in general we
962 // expect users to use 'a@modifier op b'.
963 if (Lexer.getKind() == AsmToken::At) {
966 if (Lexer.isNot(AsmToken::Identifier))
967 return TokError("unexpected symbol modifier following '@'");
969 MCSymbolRefExpr::VariantKind Variant =
970 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
971 if (Variant == MCSymbolRefExpr::VK_Invalid)
972 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
974 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
976 return TokError("invalid modifier '" + getTok().getIdentifier() +
977 "' (no symbols present)");
984 // Try to constant fold it up front, if possible.
986 if (Res->EvaluateAsAbsolute(Value))
987 Res = MCConstantExpr::Create(Value, getContext());
992 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
994 return ParseParenExpr(Res, EndLoc) ||
995 ParseBinOpRHS(1, Res, EndLoc);
998 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1001 SMLoc StartLoc = Lexer.getLoc();
1002 if (parseExpression(Expr))
1005 if (!Expr->EvaluateAsAbsolute(Res))
1006 return Error(StartLoc, "expected absolute expression");
1011 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1012 MCBinaryExpr::Opcode &Kind) {
1015 return 0; // not a binop.
1017 // Lowest Precedence: &&, ||
1018 case AsmToken::AmpAmp:
1019 Kind = MCBinaryExpr::LAnd;
1021 case AsmToken::PipePipe:
1022 Kind = MCBinaryExpr::LOr;
1026 // Low Precedence: |, &, ^
1028 // FIXME: gas seems to support '!' as an infix operator?
1029 case AsmToken::Pipe:
1030 Kind = MCBinaryExpr::Or;
1032 case AsmToken::Caret:
1033 Kind = MCBinaryExpr::Xor;
1036 Kind = MCBinaryExpr::And;
1039 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1040 case AsmToken::EqualEqual:
1041 Kind = MCBinaryExpr::EQ;
1043 case AsmToken::ExclaimEqual:
1044 case AsmToken::LessGreater:
1045 Kind = MCBinaryExpr::NE;
1047 case AsmToken::Less:
1048 Kind = MCBinaryExpr::LT;
1050 case AsmToken::LessEqual:
1051 Kind = MCBinaryExpr::LTE;
1053 case AsmToken::Greater:
1054 Kind = MCBinaryExpr::GT;
1056 case AsmToken::GreaterEqual:
1057 Kind = MCBinaryExpr::GTE;
1060 // Intermediate Precedence: <<, >>
1061 case AsmToken::LessLess:
1062 Kind = MCBinaryExpr::Shl;
1064 case AsmToken::GreaterGreater:
1065 Kind = MCBinaryExpr::Shr;
1068 // High Intermediate Precedence: +, -
1069 case AsmToken::Plus:
1070 Kind = MCBinaryExpr::Add;
1072 case AsmToken::Minus:
1073 Kind = MCBinaryExpr::Sub;
1076 // Highest Precedence: *, /, %
1077 case AsmToken::Star:
1078 Kind = MCBinaryExpr::Mul;
1080 case AsmToken::Slash:
1081 Kind = MCBinaryExpr::Div;
1083 case AsmToken::Percent:
1084 Kind = MCBinaryExpr::Mod;
1090 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1091 /// Res contains the LHS of the expression on input.
1092 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1095 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1096 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1098 // If the next token is lower precedence than we are allowed to eat, return
1099 // successfully with what we ate already.
1100 if (TokPrec < Precedence)
1105 // Eat the next primary expression.
1107 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1109 // If BinOp binds less tightly with RHS than the operator after RHS, let
1110 // the pending operator take RHS as its LHS.
1111 MCBinaryExpr::Opcode Dummy;
1112 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1113 if (TokPrec < NextTokPrec) {
1114 if (ParseBinOpRHS(TokPrec+1, RHS, EndLoc)) return true;
1117 // Merge LHS and RHS according to operator.
1118 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1123 /// ::= EndOfStatement
1124 /// ::= Label* Directive ...Operands... EndOfStatement
1125 /// ::= Label* Identifier OperandList* EndOfStatement
1126 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1127 if (Lexer.is(AsmToken::EndOfStatement)) {
1133 // Statements always start with an identifier or are a full line comment.
1134 AsmToken ID = getTok();
1135 SMLoc IDLoc = ID.getLoc();
1137 int64_t LocalLabelVal = -1;
1138 // A full line comment is a '#' as the first token.
1139 if (Lexer.is(AsmToken::Hash))
1140 return ParseCppHashLineFilenameComment(IDLoc);
1142 // Allow an integer followed by a ':' as a directional local label.
1143 if (Lexer.is(AsmToken::Integer)) {
1144 LocalLabelVal = getTok().getIntVal();
1145 if (LocalLabelVal < 0) {
1146 if (!TheCondState.Ignore)
1147 return TokError("unexpected token at start of statement");
1150 IDVal = getTok().getString();
1151 Lex(); // Consume the integer token to be used as an identifier token.
1152 if (Lexer.getKind() != AsmToken::Colon) {
1153 if (!TheCondState.Ignore)
1154 return TokError("unexpected token at start of statement");
1157 } else if (Lexer.is(AsmToken::Dot)) {
1158 // Treat '.' as a valid identifier in this context.
1161 } else if (parseIdentifier(IDVal)) {
1162 if (!TheCondState.Ignore)
1163 return TokError("unexpected token at start of statement");
1167 // Handle conditional assembly here before checking for skipping. We
1168 // have to do this so that .endif isn't skipped in a ".if 0" block for
1170 StringMap<DirectiveKind>::const_iterator DirKindIt =
1171 DirectiveKindMap.find(IDVal);
1172 DirectiveKind DirKind =
1173 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1174 DirKindIt->getValue();
1179 return ParseDirectiveIf(IDLoc);
1181 return ParseDirectiveIfb(IDLoc, true);
1183 return ParseDirectiveIfb(IDLoc, false);
1185 return ParseDirectiveIfc(IDLoc, true);
1187 return ParseDirectiveIfc(IDLoc, false);
1189 return ParseDirectiveIfdef(IDLoc, true);
1192 return ParseDirectiveIfdef(IDLoc, false);
1194 return ParseDirectiveElseIf(IDLoc);
1196 return ParseDirectiveElse(IDLoc);
1198 return ParseDirectiveEndIf(IDLoc);
1201 // Ignore the statement if in the middle of inactive conditional
1203 if (TheCondState.Ignore) {
1204 eatToEndOfStatement();
1208 // FIXME: Recurse on local labels?
1210 // See what kind of statement we have.
1211 switch (Lexer.getKind()) {
1212 case AsmToken::Colon: {
1213 checkForValidSection();
1215 // identifier ':' -> Label.
1218 // Diagnose attempt to use '.' as a label.
1220 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1222 // Diagnose attempt to use a variable as a label.
1224 // FIXME: Diagnostics. Note the location of the definition as a label.
1225 // FIXME: This doesn't diagnose assignment to a symbol which has been
1226 // implicitly marked as external.
1228 if (LocalLabelVal == -1)
1229 Sym = getContext().GetOrCreateSymbol(IDVal);
1231 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1232 if (!Sym->isUndefined() || Sym->isVariable())
1233 return Error(IDLoc, "invalid symbol redefinition");
1236 if (!ParsingInlineAsm)
1239 // If we are generating dwarf for assembly source files then gather the
1240 // info to make a dwarf label entry for this label if needed.
1241 if (getContext().getGenDwarfForAssembly())
1242 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1245 // Consume any end of statement token, if present, to avoid spurious
1246 // AddBlankLine calls().
1247 if (Lexer.is(AsmToken::EndOfStatement)) {
1249 if (Lexer.is(AsmToken::Eof))
1256 case AsmToken::Equal:
1257 // identifier '=' ... -> assignment statement
1260 return ParseAssignment(IDVal, true);
1262 default: // Normal instruction or directive.
1266 // If macros are enabled, check to see if this is a macro instantiation.
1267 if (MacrosEnabled())
1268 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1269 return HandleMacroEntry(M, IDLoc);
1272 // Otherwise, we have a normal instruction or directive.
1274 // Directives start with "."
1275 if (IDVal[0] == '.' && IDVal != ".") {
1276 // There are several entities interested in parsing directives:
1278 // 1. The target-specific assembly parser. Some directives are target
1279 // specific or may potentially behave differently on certain targets.
1280 // 2. Asm parser extensions. For example, platform-specific parsers
1281 // (like the ELF parser) register themselves as extensions.
1282 // 3. The generic directive parser implemented by this class. These are
1283 // all the directives that behave in a target and platform independent
1284 // manner, or at least have a default behavior that's shared between
1285 // all targets and platforms.
1287 // First query the target-specific parser. It will return 'true' if it
1288 // isn't interested in this directive.
1289 if (!getTargetParser().ParseDirective(ID))
1292 // Next, check the extention directive map to see if any extension has
1293 // registered itself to parse this directive.
1294 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1295 ExtensionDirectiveMap.lookup(IDVal);
1297 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1299 // Finally, if no one else is interested in this directive, it must be
1300 // generic and familiar to this class.
1306 return ParseDirectiveSet(IDVal, true);
1308 return ParseDirectiveSet(IDVal, false);
1310 return ParseDirectiveAscii(IDVal, false);
1313 return ParseDirectiveAscii(IDVal, true);
1315 return ParseDirectiveValue(1);
1319 return ParseDirectiveValue(2);
1323 return ParseDirectiveValue(4);
1326 return ParseDirectiveValue(8);
1329 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1331 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1333 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1334 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1337 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1338 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1341 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1343 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1345 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1347 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1349 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1351 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1353 return ParseDirectiveOrg();
1355 return ParseDirectiveFill();
1357 return ParseDirectiveZero();
1359 eatToEndOfStatement(); // .extern is the default, ignore it.
1363 return ParseDirectiveSymbolAttribute(MCSA_Global);
1364 case DK_INDIRECT_SYMBOL:
1365 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1366 case DK_LAZY_REFERENCE:
1367 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1368 case DK_NO_DEAD_STRIP:
1369 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1370 case DK_SYMBOL_RESOLVER:
1371 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1372 case DK_PRIVATE_EXTERN:
1373 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1375 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1376 case DK_WEAK_DEFINITION:
1377 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1378 case DK_WEAK_REFERENCE:
1379 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1380 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1381 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1384 return ParseDirectiveComm(/*IsLocal=*/false);
1386 return ParseDirectiveComm(/*IsLocal=*/true);
1388 return ParseDirectiveAbort();
1390 return ParseDirectiveInclude();
1392 return ParseDirectiveIncbin();
1395 return TokError(Twine(IDVal) + " not supported yet");
1397 return ParseDirectiveRept(IDLoc);
1399 return ParseDirectiveIrp(IDLoc);
1401 return ParseDirectiveIrpc(IDLoc);
1403 return ParseDirectiveEndr(IDLoc);
1404 case DK_BUNDLE_ALIGN_MODE:
1405 return ParseDirectiveBundleAlignMode();
1406 case DK_BUNDLE_LOCK:
1407 return ParseDirectiveBundleLock();
1408 case DK_BUNDLE_UNLOCK:
1409 return ParseDirectiveBundleUnlock();
1411 return ParseDirectiveLEB128(true);
1413 return ParseDirectiveLEB128(false);
1416 return ParseDirectiveSpace(IDVal);
1418 return ParseDirectiveFile(IDLoc);
1420 return ParseDirectiveLine();
1422 return ParseDirectiveLoc();
1424 return ParseDirectiveStabs();
1425 case DK_CFI_SECTIONS:
1426 return ParseDirectiveCFISections();
1427 case DK_CFI_STARTPROC:
1428 return ParseDirectiveCFIStartProc();
1429 case DK_CFI_ENDPROC:
1430 return ParseDirectiveCFIEndProc();
1431 case DK_CFI_DEF_CFA:
1432 return ParseDirectiveCFIDefCfa(IDLoc);
1433 case DK_CFI_DEF_CFA_OFFSET:
1434 return ParseDirectiveCFIDefCfaOffset();
1435 case DK_CFI_ADJUST_CFA_OFFSET:
1436 return ParseDirectiveCFIAdjustCfaOffset();
1437 case DK_CFI_DEF_CFA_REGISTER:
1438 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1440 return ParseDirectiveCFIOffset(IDLoc);
1441 case DK_CFI_REL_OFFSET:
1442 return ParseDirectiveCFIRelOffset(IDLoc);
1443 case DK_CFI_PERSONALITY:
1444 return ParseDirectiveCFIPersonalityOrLsda(true);
1446 return ParseDirectiveCFIPersonalityOrLsda(false);
1447 case DK_CFI_REMEMBER_STATE:
1448 return ParseDirectiveCFIRememberState();
1449 case DK_CFI_RESTORE_STATE:
1450 return ParseDirectiveCFIRestoreState();
1451 case DK_CFI_SAME_VALUE:
1452 return ParseDirectiveCFISameValue(IDLoc);
1453 case DK_CFI_RESTORE:
1454 return ParseDirectiveCFIRestore(IDLoc);
1456 return ParseDirectiveCFIEscape();
1457 case DK_CFI_SIGNAL_FRAME:
1458 return ParseDirectiveCFISignalFrame();
1459 case DK_CFI_UNDEFINED:
1460 return ParseDirectiveCFIUndefined(IDLoc);
1461 case DK_CFI_REGISTER:
1462 return ParseDirectiveCFIRegister(IDLoc);
1465 return ParseDirectiveMacrosOnOff(IDVal);
1467 return ParseDirectiveMacro(IDLoc);
1470 return ParseDirectiveEndMacro(IDVal);
1472 return ParseDirectivePurgeMacro(IDLoc);
1475 return Error(IDLoc, "unknown directive");
1478 // __asm _emit or __asm __emit
1479 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1480 IDVal == "_EMIT" || IDVal == "__EMIT"))
1481 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1484 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1485 return ParseDirectiveMSAlign(IDLoc, Info);
1487 checkForValidSection();
1489 // Canonicalize the opcode to lower case.
1490 std::string OpcodeStr = IDVal.lower();
1491 ParseInstructionInfo IInfo(Info.AsmRewrites);
1492 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1494 Info.ParsedOperands);
1495 Info.ParseError = HadError;
1497 // Dump the parsed representation, if requested.
1498 if (getShowParsedOperands()) {
1499 SmallString<256> Str;
1500 raw_svector_ostream OS(Str);
1501 OS << "parsed instruction: [";
1502 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1505 Info.ParsedOperands[i]->print(OS);
1509 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1512 // If we are generating dwarf for assembly source files and the current
1513 // section is the initial text section then generate a .loc directive for
1515 if (!HadError && getContext().getGenDwarfForAssembly() &&
1516 getContext().getGenDwarfSection() ==
1517 getStreamer().getCurrentSection().first) {
1519 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1521 // If we previously parsed a cpp hash file line comment then make sure the
1522 // current Dwarf File is for the CppHashFilename if not then emit the
1523 // Dwarf File table for it and adjust the line number for the .loc.
1524 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1525 getContext().getMCDwarfFiles();
1526 if (CppHashFilename.size() != 0) {
1527 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1529 getStreamer().EmitDwarfFileDirective(
1530 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1532 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1533 // cache with the different Loc from the call above we save the last
1534 // info we queried here with SrcMgr.FindLineNumber().
1535 unsigned CppHashLocLineNo;
1536 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1537 CppHashLocLineNo = LastQueryLine;
1539 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1540 LastQueryLine = CppHashLocLineNo;
1541 LastQueryIDLoc = CppHashLoc;
1542 LastQueryBuffer = CppHashBuf;
1544 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1547 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1548 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1549 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1553 // If parsing succeeded, match the instruction.
1556 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1557 Info.ParsedOperands,
1562 // Don't skip the rest of the line, the instruction parser is responsible for
1567 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1568 /// since they may not be able to be tokenized to get to the end of line token.
1569 void AsmParser::EatToEndOfLine() {
1570 if (!Lexer.is(AsmToken::EndOfStatement))
1571 Lexer.LexUntilEndOfLine();
1576 /// ParseCppHashLineFilenameComment as this:
1577 /// ::= # number "filename"
1578 /// or just as a full line comment if it doesn't have a number and a string.
1579 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1580 Lex(); // Eat the hash token.
1582 if (getLexer().isNot(AsmToken::Integer)) {
1583 // Consume the line since in cases it is not a well-formed line directive,
1584 // as if were simply a full line comment.
1589 int64_t LineNumber = getTok().getIntVal();
1592 if (getLexer().isNot(AsmToken::String)) {
1597 StringRef Filename = getTok().getString();
1598 // Get rid of the enclosing quotes.
1599 Filename = Filename.substr(1, Filename.size()-2);
1601 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1603 CppHashFilename = Filename;
1604 CppHashLineNumber = LineNumber;
1605 CppHashBuf = CurBuffer;
1607 // Ignore any trailing characters, they're just comment.
1612 /// DiagHandler - will use the last parsed cpp hash line filename comment
1613 /// for the Filename and LineNo if any in the diagnostic.
1614 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1615 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1616 raw_ostream &OS = errs();
1618 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1619 const SMLoc &DiagLoc = Diag.getLoc();
1620 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1621 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1623 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1624 // before printing the message.
1625 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1626 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1627 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1628 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1631 // If we have not parsed a cpp hash line filename comment or the source
1632 // manager changed or buffer changed (like in a nested include) then just
1633 // print the normal diagnostic using its Filename and LineNo.
1634 if (!Parser->CppHashLineNumber ||
1635 &DiagSrcMgr != &Parser->SrcMgr ||
1636 DiagBuf != CppHashBuf) {
1637 if (Parser->SavedDiagHandler)
1638 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1644 // Use the CppHashFilename and calculate a line number based on the
1645 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1647 const std::string Filename = Parser->CppHashFilename;
1649 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1650 int CppHashLocLineNo =
1651 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1652 int LineNo = Parser->CppHashLineNumber - 1 +
1653 (DiagLocLineNo - CppHashLocLineNo);
1655 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1656 Filename, LineNo, Diag.getColumnNo(),
1657 Diag.getKind(), Diag.getMessage(),
1658 Diag.getLineContents(), Diag.getRanges());
1660 if (Parser->SavedDiagHandler)
1661 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1663 NewDiag.print(0, OS);
1666 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1667 // difference being that that function accepts '@' as part of identifiers and
1668 // we can't do that. AsmLexer.cpp should probably be changed to handle
1669 // '@' as a special case when needed.
1670 static bool isIdentifierChar(char c) {
1671 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1675 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1676 const MCAsmMacroParameters &Parameters,
1677 const MCAsmMacroArguments &A,
1679 unsigned NParameters = Parameters.size();
1680 if (NParameters != 0 && NParameters != A.size())
1681 return Error(L, "Wrong number of arguments");
1683 // A macro without parameters is handled differently on Darwin:
1684 // gas accepts no arguments and does no substitutions
1685 while (!Body.empty()) {
1686 // Scan for the next substitution.
1687 std::size_t End = Body.size(), Pos = 0;
1688 for (; Pos != End; ++Pos) {
1689 // Check for a substitution or escape.
1691 // This macro has no parameters, look for $0, $1, etc.
1692 if (Body[Pos] != '$' || Pos + 1 == End)
1695 char Next = Body[Pos + 1];
1696 if (Next == '$' || Next == 'n' ||
1697 isdigit(static_cast<unsigned char>(Next)))
1700 // This macro has parameters, look for \foo, \bar, etc.
1701 if (Body[Pos] == '\\' && Pos + 1 != End)
1707 OS << Body.slice(0, Pos);
1709 // Check if we reached the end.
1714 switch (Body[Pos+1]) {
1720 // $n => number of arguments
1725 // $[0-9] => argument
1727 // Missing arguments are ignored.
1728 unsigned Index = Body[Pos+1] - '0';
1729 if (Index >= A.size())
1732 // Otherwise substitute with the token values, with spaces eliminated.
1733 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1734 ie = A[Index].end(); it != ie; ++it)
1735 OS << it->getString();
1741 unsigned I = Pos + 1;
1742 while (isIdentifierChar(Body[I]) && I + 1 != End)
1745 const char *Begin = Body.data() + Pos +1;
1746 StringRef Argument(Begin, I - (Pos +1));
1748 for (; Index < NParameters; ++Index)
1749 if (Parameters[Index].first == Argument)
1752 if (Index == NParameters) {
1753 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1756 OS << '\\' << Argument;
1760 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1761 ie = A[Index].end(); it != ie; ++it)
1762 if (it->getKind() == AsmToken::String)
1763 OS << it->getStringContents();
1765 OS << it->getString();
1767 Pos += 1 + Argument.size();
1770 // Update the scan point.
1771 Body = Body.substr(Pos);
1777 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
1780 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1785 static bool IsOperator(AsmToken::TokenKind kind)
1791 case AsmToken::Plus:
1792 case AsmToken::Minus:
1793 case AsmToken::Tilde:
1794 case AsmToken::Slash:
1795 case AsmToken::Star:
1797 case AsmToken::Equal:
1798 case AsmToken::EqualEqual:
1799 case AsmToken::Pipe:
1800 case AsmToken::PipePipe:
1801 case AsmToken::Caret:
1803 case AsmToken::AmpAmp:
1804 case AsmToken::Exclaim:
1805 case AsmToken::ExclaimEqual:
1806 case AsmToken::Percent:
1807 case AsmToken::Less:
1808 case AsmToken::LessEqual:
1809 case AsmToken::LessLess:
1810 case AsmToken::LessGreater:
1811 case AsmToken::Greater:
1812 case AsmToken::GreaterEqual:
1813 case AsmToken::GreaterGreater:
1818 bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
1819 AsmToken::TokenKind &ArgumentDelimiter) {
1820 unsigned ParenLevel = 0;
1821 unsigned AddTokens = 0;
1823 // gas accepts arguments separated by whitespace, except on Darwin
1825 Lexer.setSkipSpace(false);
1828 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1829 Lexer.setSkipSpace(true);
1830 return TokError("unexpected token in macro instantiation");
1833 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1834 // Spaces and commas cannot be mixed to delimit parameters
1835 if (ArgumentDelimiter == AsmToken::Eof)
1836 ArgumentDelimiter = AsmToken::Comma;
1837 else if (ArgumentDelimiter != AsmToken::Comma) {
1838 Lexer.setSkipSpace(true);
1839 return TokError("expected ' ' for macro argument separator");
1844 if (Lexer.is(AsmToken::Space)) {
1845 Lex(); // Eat spaces
1847 // Spaces can delimit parameters, but could also be part an expression.
1848 // If the token after a space is an operator, add the token and the next
1849 // one into this argument
1850 if (ArgumentDelimiter == AsmToken::Space ||
1851 ArgumentDelimiter == AsmToken::Eof) {
1852 if (IsOperator(Lexer.getKind())) {
1853 // Check to see whether the token is used as an operator,
1854 // or part of an identifier
1855 const char *NextChar = getTok().getEndLoc().getPointer();
1856 if (*NextChar == ' ')
1860 if (!AddTokens && ParenLevel == 0) {
1861 if (ArgumentDelimiter == AsmToken::Eof &&
1862 !IsOperator(Lexer.getKind()))
1863 ArgumentDelimiter = AsmToken::Space;
1869 // HandleMacroEntry relies on not advancing the lexer here
1870 // to be able to fill in the remaining default parameter values
1871 if (Lexer.is(AsmToken::EndOfStatement))
1874 // Adjust the current parentheses level.
1875 if (Lexer.is(AsmToken::LParen))
1877 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1880 // Append the token to the current argument list.
1881 MA.push_back(getTok());
1887 Lexer.setSkipSpace(true);
1888 if (ParenLevel != 0)
1889 return TokError("unbalanced parentheses in macro argument");
1893 // Parse the macro instantiation arguments.
1894 bool AsmParser::ParseMacroArguments(const MCAsmMacro *M,
1895 MCAsmMacroArguments &A) {
1896 const unsigned NParameters = M ? M->Parameters.size() : 0;
1897 // Argument delimiter is initially unknown. It will be set by
1898 // ParseMacroArgument()
1899 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1901 // Parse two kinds of macro invocations:
1902 // - macros defined without any parameters accept an arbitrary number of them
1903 // - macros defined with parameters accept at most that many of them
1904 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1906 MCAsmMacroArgument MA;
1908 if (ParseMacroArgument(MA, ArgumentDelimiter))
1911 if (!MA.empty() || !NParameters)
1913 else if (NParameters) {
1914 if (!M->Parameters[Parameter].second.empty())
1915 A.push_back(M->Parameters[Parameter].second);
1918 // At the end of the statement, fill in remaining arguments that have
1919 // default values. If there aren't any, then the next argument is
1920 // required but missing
1921 if (Lexer.is(AsmToken::EndOfStatement)) {
1922 if (NParameters && Parameter < NParameters - 1) {
1923 if (M->Parameters[Parameter + 1].second.empty())
1924 return TokError("macro argument '" +
1925 Twine(M->Parameters[Parameter + 1].first) +
1933 if (Lexer.is(AsmToken::Comma))
1936 return TokError("Too many arguments");
1939 const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1940 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1941 return (I == MacroMap.end()) ? NULL : I->getValue();
1944 void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1945 MacroMap[Name] = new MCAsmMacro(Macro);
1948 void AsmParser::UndefineMacro(StringRef Name) {
1949 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1950 if (I != MacroMap.end()) {
1951 delete I->getValue();
1956 bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1957 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1958 // this, although we should protect against infinite loops.
1959 if (ActiveMacros.size() == 20)
1960 return TokError("macros cannot be nested more than 20 levels deep");
1962 MCAsmMacroArguments A;
1963 if (ParseMacroArguments(M, A))
1966 // Remove any trailing empty arguments. Do this after-the-fact as we have
1967 // to keep empty arguments in the middle of the list or positionality
1968 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1969 while (!A.empty() && A.back().empty())
1972 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1973 // to hold the macro body with substitutions.
1974 SmallString<256> Buf;
1975 StringRef Body = M->Body;
1976 raw_svector_ostream OS(Buf);
1978 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1981 // We include the .endmacro in the buffer as our cue to exit the macro
1983 OS << ".endmacro\n";
1985 MemoryBuffer *Instantiation =
1986 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1988 // Create the macro instantiation object and add to the current macro
1989 // instantiation stack.
1990 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1994 ActiveMacros.push_back(MI);
1996 // Jump to the macro instantiation and prime the lexer.
1997 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1998 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2004 void AsmParser::HandleMacroExit() {
2005 // Jump to the EndOfStatement we should return to, and consume it.
2006 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2009 // Pop the instantiation entry.
2010 delete ActiveMacros.back();
2011 ActiveMacros.pop_back();
2014 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2015 switch (Value->getKind()) {
2016 case MCExpr::Binary: {
2017 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
2018 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
2020 case MCExpr::Target:
2021 case MCExpr::Constant:
2023 case MCExpr::SymbolRef: {
2024 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
2026 return IsUsedIn(Sym, S.getVariableValue());
2030 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
2033 llvm_unreachable("Unknown expr kind!");
2036 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2038 // FIXME: Use better location, we should use proper tokens.
2039 SMLoc EqualLoc = Lexer.getLoc();
2041 const MCExpr *Value;
2042 if (parseExpression(Value))
2045 // Note: we don't count b as used in "a = b". This is to allow
2049 if (Lexer.isNot(AsmToken::EndOfStatement))
2050 return TokError("unexpected token in assignment");
2052 // Error on assignment to '.'.
2054 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2055 "(use '.space' or '.org').)"));
2058 // Eat the end of statement marker.
2061 // Validate that the LHS is allowed to be a variable (either it has not been
2062 // used as a symbol, or it is an absolute symbol).
2063 MCSymbol *Sym = getContext().LookupSymbol(Name);
2065 // Diagnose assignment to a label.
2067 // FIXME: Diagnostics. Note the location of the definition as a label.
2068 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2069 if (IsUsedIn(Sym, Value))
2070 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2071 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2072 ; // Allow redefinitions of undefined symbols only used in directives.
2073 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2074 ; // Allow redefinitions of variables that haven't yet been used.
2075 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2076 return Error(EqualLoc, "redefinition of '" + Name + "'");
2077 else if (!Sym->isVariable())
2078 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2079 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2080 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2083 // Don't count these checks as uses.
2084 Sym->setUsed(false);
2086 Sym = getContext().GetOrCreateSymbol(Name);
2088 // FIXME: Handle '.'.
2090 // Do the assignment.
2091 Out.EmitAssignment(Sym, Value);
2093 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2099 /// parseIdentifier:
2102 bool AsmParser::parseIdentifier(StringRef &Res) {
2103 // The assembler has relaxed rules for accepting identifiers, in particular we
2104 // allow things like '.globl $foo', which would normally be separate
2105 // tokens. At this level, we have already lexed so we cannot (currently)
2106 // handle this as a context dependent token, instead we detect adjacent tokens
2107 // and return the combined identifier.
2108 if (Lexer.is(AsmToken::Dollar)) {
2109 SMLoc DollarLoc = getLexer().getLoc();
2111 // Consume the dollar sign, and check for a following identifier.
2113 if (Lexer.isNot(AsmToken::Identifier))
2116 // We have a '$' followed by an identifier, make sure they are adjacent.
2117 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2120 // Construct the joined identifier and consume the token.
2121 Res = StringRef(DollarLoc.getPointer(),
2122 getTok().getIdentifier().size() + 1);
2127 if (Lexer.isNot(AsmToken::Identifier) &&
2128 Lexer.isNot(AsmToken::String))
2131 Res = getTok().getIdentifier();
2133 Lex(); // Consume the identifier token.
2138 /// ParseDirectiveSet:
2139 /// ::= .equ identifier ',' expression
2140 /// ::= .equiv identifier ',' expression
2141 /// ::= .set identifier ',' expression
2142 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2145 if (parseIdentifier(Name))
2146 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2148 if (getLexer().isNot(AsmToken::Comma))
2149 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2152 return ParseAssignment(Name, allow_redef, true);
2155 bool AsmParser::parseEscapedString(std::string &Data) {
2156 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2159 StringRef Str = getTok().getStringContents();
2160 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2161 if (Str[i] != '\\') {
2166 // Recognize escaped characters. Note that this escape semantics currently
2167 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2170 return TokError("unexpected backslash at end of string");
2172 // Recognize octal sequences.
2173 if ((unsigned) (Str[i] - '0') <= 7) {
2174 // Consume up to three octal characters.
2175 unsigned Value = Str[i] - '0';
2177 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2179 Value = Value * 8 + (Str[i] - '0');
2181 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2183 Value = Value * 8 + (Str[i] - '0');
2188 return TokError("invalid octal escape sequence (out of range)");
2190 Data += (unsigned char) Value;
2194 // Otherwise recognize individual escapes.
2197 // Just reject invalid escape sequences for now.
2198 return TokError("invalid escape sequence (unrecognized character)");
2200 case 'b': Data += '\b'; break;
2201 case 'f': Data += '\f'; break;
2202 case 'n': Data += '\n'; break;
2203 case 'r': Data += '\r'; break;
2204 case 't': Data += '\t'; break;
2205 case '"': Data += '"'; break;
2206 case '\\': Data += '\\'; break;
2213 /// ParseDirectiveAscii:
2214 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2215 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2216 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2217 checkForValidSection();
2220 if (getLexer().isNot(AsmToken::String))
2221 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2224 if (parseEscapedString(Data))
2227 getStreamer().EmitBytes(Data);
2229 getStreamer().EmitBytes(StringRef("\0", 1));
2233 if (getLexer().is(AsmToken::EndOfStatement))
2236 if (getLexer().isNot(AsmToken::Comma))
2237 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2246 /// ParseDirectiveValue
2247 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2248 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2249 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2250 checkForValidSection();
2253 const MCExpr *Value;
2254 SMLoc ExprLoc = getLexer().getLoc();
2255 if (parseExpression(Value))
2258 // Special case constant expressions to match code generator.
2259 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2260 assert(Size <= 8 && "Invalid size");
2261 uint64_t IntValue = MCE->getValue();
2262 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2263 return Error(ExprLoc, "literal value out of range for directive");
2264 getStreamer().EmitIntValue(IntValue, Size);
2266 getStreamer().EmitValue(Value, Size);
2268 if (getLexer().is(AsmToken::EndOfStatement))
2271 // FIXME: Improve diagnostic.
2272 if (getLexer().isNot(AsmToken::Comma))
2273 return TokError("unexpected token in directive");
2282 /// ParseDirectiveRealValue
2283 /// ::= (.single | .double) [ expression (, expression)* ]
2284 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2285 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2286 checkForValidSection();
2289 // We don't truly support arithmetic on floating point expressions, so we
2290 // have to manually parse unary prefixes.
2292 if (getLexer().is(AsmToken::Minus)) {
2295 } else if (getLexer().is(AsmToken::Plus))
2298 if (getLexer().isNot(AsmToken::Integer) &&
2299 getLexer().isNot(AsmToken::Real) &&
2300 getLexer().isNot(AsmToken::Identifier))
2301 return TokError("unexpected token in directive");
2303 // Convert to an APFloat.
2304 APFloat Value(Semantics);
2305 StringRef IDVal = getTok().getString();
2306 if (getLexer().is(AsmToken::Identifier)) {
2307 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2308 Value = APFloat::getInf(Semantics);
2309 else if (!IDVal.compare_lower("nan"))
2310 Value = APFloat::getNaN(Semantics, false, ~0);
2312 return TokError("invalid floating point literal");
2313 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2314 APFloat::opInvalidOp)
2315 return TokError("invalid floating point literal");
2319 // Consume the numeric token.
2322 // Emit the value as an integer.
2323 APInt AsInt = Value.bitcastToAPInt();
2324 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2325 AsInt.getBitWidth() / 8);
2327 if (getLexer().is(AsmToken::EndOfStatement))
2330 if (getLexer().isNot(AsmToken::Comma))
2331 return TokError("unexpected token in directive");
2340 /// ParseDirectiveZero
2341 /// ::= .zero expression
2342 bool AsmParser::ParseDirectiveZero() {
2343 checkForValidSection();
2346 if (parseAbsoluteExpression(NumBytes))
2350 if (getLexer().is(AsmToken::Comma)) {
2352 if (parseAbsoluteExpression(Val))
2356 if (getLexer().isNot(AsmToken::EndOfStatement))
2357 return TokError("unexpected token in '.zero' directive");
2361 getStreamer().EmitFill(NumBytes, Val);
2366 /// ParseDirectiveFill
2367 /// ::= .fill expression , expression , expression
2368 bool AsmParser::ParseDirectiveFill() {
2369 checkForValidSection();
2372 if (parseAbsoluteExpression(NumValues))
2375 if (getLexer().isNot(AsmToken::Comma))
2376 return TokError("unexpected token in '.fill' directive");
2380 if (parseAbsoluteExpression(FillSize))
2383 if (getLexer().isNot(AsmToken::Comma))
2384 return TokError("unexpected token in '.fill' directive");
2388 if (parseAbsoluteExpression(FillExpr))
2391 if (getLexer().isNot(AsmToken::EndOfStatement))
2392 return TokError("unexpected token in '.fill' directive");
2396 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2397 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2399 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2400 getStreamer().EmitIntValue(FillExpr, FillSize);
2405 /// ParseDirectiveOrg
2406 /// ::= .org expression [ , expression ]
2407 bool AsmParser::ParseDirectiveOrg() {
2408 checkForValidSection();
2410 const MCExpr *Offset;
2411 SMLoc Loc = getTok().getLoc();
2412 if (parseExpression(Offset))
2415 // Parse optional fill expression.
2416 int64_t FillExpr = 0;
2417 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2418 if (getLexer().isNot(AsmToken::Comma))
2419 return TokError("unexpected token in '.org' directive");
2422 if (parseAbsoluteExpression(FillExpr))
2425 if (getLexer().isNot(AsmToken::EndOfStatement))
2426 return TokError("unexpected token in '.org' directive");
2431 // Only limited forms of relocatable expressions are accepted here, it
2432 // has to be relative to the current section. The streamer will return
2433 // 'true' if the expression wasn't evaluatable.
2434 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2435 return Error(Loc, "expected assembly-time absolute expression");
2440 /// ParseDirectiveAlign
2441 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2442 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2443 checkForValidSection();
2445 SMLoc AlignmentLoc = getLexer().getLoc();
2447 if (parseAbsoluteExpression(Alignment))
2451 bool HasFillExpr = false;
2452 int64_t FillExpr = 0;
2453 int64_t MaxBytesToFill = 0;
2454 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2455 if (getLexer().isNot(AsmToken::Comma))
2456 return TokError("unexpected token in directive");
2459 // The fill expression can be omitted while specifying a maximum number of
2460 // alignment bytes, e.g:
2462 if (getLexer().isNot(AsmToken::Comma)) {
2464 if (parseAbsoluteExpression(FillExpr))
2468 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2469 if (getLexer().isNot(AsmToken::Comma))
2470 return TokError("unexpected token in directive");
2473 MaxBytesLoc = getLexer().getLoc();
2474 if (parseAbsoluteExpression(MaxBytesToFill))
2477 if (getLexer().isNot(AsmToken::EndOfStatement))
2478 return TokError("unexpected token in directive");
2487 // Compute alignment in bytes.
2489 // FIXME: Diagnose overflow.
2490 if (Alignment >= 32) {
2491 Error(AlignmentLoc, "invalid alignment value");
2495 Alignment = 1ULL << Alignment;
2497 // Reject alignments that aren't a power of two, for gas compatibility.
2498 if (!isPowerOf2_64(Alignment))
2499 Error(AlignmentLoc, "alignment must be a power of 2");
2502 // Diagnose non-sensical max bytes to align.
2503 if (MaxBytesLoc.isValid()) {
2504 if (MaxBytesToFill < 1) {
2505 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2506 "many bytes, ignoring maximum bytes expression");
2510 if (MaxBytesToFill >= Alignment) {
2511 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2517 // Check whether we should use optimal code alignment for this .align
2519 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2520 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2521 ValueSize == 1 && UseCodeAlign) {
2522 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2524 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2525 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2532 /// ParseDirectiveFile
2533 /// ::= .file [number] filename
2534 /// ::= .file number directory filename
2535 bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2536 // FIXME: I'm not sure what this is.
2537 int64_t FileNumber = -1;
2538 SMLoc FileNumberLoc = getLexer().getLoc();
2539 if (getLexer().is(AsmToken::Integer)) {
2540 FileNumber = getTok().getIntVal();
2544 return TokError("file number less than one");
2547 if (getLexer().isNot(AsmToken::String))
2548 return TokError("unexpected token in '.file' directive");
2550 // Usually the directory and filename together, otherwise just the directory.
2551 StringRef Path = getTok().getString();
2552 Path = Path.substr(1, Path.size()-2);
2555 StringRef Directory;
2557 if (getLexer().is(AsmToken::String)) {
2558 if (FileNumber == -1)
2559 return TokError("explicit path specified, but no file number");
2560 Filename = getTok().getString();
2561 Filename = Filename.substr(1, Filename.size()-2);
2568 if (getLexer().isNot(AsmToken::EndOfStatement))
2569 return TokError("unexpected token in '.file' directive");
2571 if (FileNumber == -1)
2572 getStreamer().EmitFileDirective(Filename);
2574 if (getContext().getGenDwarfForAssembly() == true)
2575 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2576 "used to generate dwarf debug info for assembly code");
2578 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2579 Error(FileNumberLoc, "file number already allocated");
2585 /// ParseDirectiveLine
2586 /// ::= .line [number]
2587 bool AsmParser::ParseDirectiveLine() {
2588 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2589 if (getLexer().isNot(AsmToken::Integer))
2590 return TokError("unexpected token in '.line' directive");
2592 int64_t LineNumber = getTok().getIntVal();
2596 // FIXME: Do something with the .line.
2599 if (getLexer().isNot(AsmToken::EndOfStatement))
2600 return TokError("unexpected token in '.line' directive");
2605 /// ParseDirectiveLoc
2606 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2607 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2608 /// The first number is a file number, must have been previously assigned with
2609 /// a .file directive, the second number is the line number and optionally the
2610 /// third number is a column position (zero if not specified). The remaining
2611 /// optional items are .loc sub-directives.
2612 bool AsmParser::ParseDirectiveLoc() {
2613 if (getLexer().isNot(AsmToken::Integer))
2614 return TokError("unexpected token in '.loc' directive");
2615 int64_t FileNumber = getTok().getIntVal();
2617 return TokError("file number less than one in '.loc' directive");
2618 if (!getContext().isValidDwarfFileNumber(FileNumber))
2619 return TokError("unassigned file number in '.loc' directive");
2622 int64_t LineNumber = 0;
2623 if (getLexer().is(AsmToken::Integer)) {
2624 LineNumber = getTok().getIntVal();
2626 return TokError("line number less than one in '.loc' directive");
2630 int64_t ColumnPos = 0;
2631 if (getLexer().is(AsmToken::Integer)) {
2632 ColumnPos = getTok().getIntVal();
2634 return TokError("column position less than zero in '.loc' directive");
2638 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2640 int64_t Discriminator = 0;
2641 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2643 if (getLexer().is(AsmToken::EndOfStatement))
2647 SMLoc Loc = getTok().getLoc();
2648 if (parseIdentifier(Name))
2649 return TokError("unexpected token in '.loc' directive");
2651 if (Name == "basic_block")
2652 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2653 else if (Name == "prologue_end")
2654 Flags |= DWARF2_FLAG_PROLOGUE_END;
2655 else if (Name == "epilogue_begin")
2656 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2657 else if (Name == "is_stmt") {
2658 Loc = getTok().getLoc();
2659 const MCExpr *Value;
2660 if (parseExpression(Value))
2662 // The expression must be the constant 0 or 1.
2663 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2664 int Value = MCE->getValue();
2666 Flags &= ~DWARF2_FLAG_IS_STMT;
2667 else if (Value == 1)
2668 Flags |= DWARF2_FLAG_IS_STMT;
2670 return Error(Loc, "is_stmt value not 0 or 1");
2672 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2674 } else if (Name == "isa") {
2675 Loc = getTok().getLoc();
2676 const MCExpr *Value;
2677 if (parseExpression(Value))
2679 // The expression must be a constant greater or equal to 0.
2680 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2681 int Value = MCE->getValue();
2683 return Error(Loc, "isa number less than zero");
2686 return Error(Loc, "isa number not a constant value");
2688 } else if (Name == "discriminator") {
2689 if (parseAbsoluteExpression(Discriminator))
2692 return Error(Loc, "unknown sub-directive in '.loc' directive");
2695 if (getLexer().is(AsmToken::EndOfStatement))
2700 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2701 Isa, Discriminator, StringRef());
2706 /// ParseDirectiveStabs
2707 /// ::= .stabs string, number, number, number
2708 bool AsmParser::ParseDirectiveStabs() {
2709 return TokError("unsupported directive '.stabs'");
2712 /// ParseDirectiveCFISections
2713 /// ::= .cfi_sections section [, section]
2714 bool AsmParser::ParseDirectiveCFISections() {
2719 if (parseIdentifier(Name))
2720 return TokError("Expected an identifier");
2722 if (Name == ".eh_frame")
2724 else if (Name == ".debug_frame")
2727 if (getLexer().is(AsmToken::Comma)) {
2730 if (parseIdentifier(Name))
2731 return TokError("Expected an identifier");
2733 if (Name == ".eh_frame")
2735 else if (Name == ".debug_frame")
2739 getStreamer().EmitCFISections(EH, Debug);
2743 /// ParseDirectiveCFIStartProc
2744 /// ::= .cfi_startproc
2745 bool AsmParser::ParseDirectiveCFIStartProc() {
2746 getStreamer().EmitCFIStartProc();
2750 /// ParseDirectiveCFIEndProc
2751 /// ::= .cfi_endproc
2752 bool AsmParser::ParseDirectiveCFIEndProc() {
2753 getStreamer().EmitCFIEndProc();
2757 /// ParseRegisterOrRegisterNumber - parse register name or number.
2758 bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2759 SMLoc DirectiveLoc) {
2762 if (getLexer().isNot(AsmToken::Integer)) {
2763 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2765 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2767 return parseAbsoluteExpression(Register);
2772 /// ParseDirectiveCFIDefCfa
2773 /// ::= .cfi_def_cfa register, offset
2774 bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2775 int64_t Register = 0;
2776 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2779 if (getLexer().isNot(AsmToken::Comma))
2780 return TokError("unexpected token in directive");
2784 if (parseAbsoluteExpression(Offset))
2787 getStreamer().EmitCFIDefCfa(Register, Offset);
2791 /// ParseDirectiveCFIDefCfaOffset
2792 /// ::= .cfi_def_cfa_offset offset
2793 bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2795 if (parseAbsoluteExpression(Offset))
2798 getStreamer().EmitCFIDefCfaOffset(Offset);
2802 /// ParseDirectiveCFIRegister
2803 /// ::= .cfi_register register, register
2804 bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2805 int64_t Register1 = 0;
2806 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2809 if (getLexer().isNot(AsmToken::Comma))
2810 return TokError("unexpected token in directive");
2813 int64_t Register2 = 0;
2814 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2817 getStreamer().EmitCFIRegister(Register1, Register2);
2821 /// ParseDirectiveCFIAdjustCfaOffset
2822 /// ::= .cfi_adjust_cfa_offset adjustment
2823 bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2824 int64_t Adjustment = 0;
2825 if (parseAbsoluteExpression(Adjustment))
2828 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2832 /// ParseDirectiveCFIDefCfaRegister
2833 /// ::= .cfi_def_cfa_register register
2834 bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2835 int64_t Register = 0;
2836 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2839 getStreamer().EmitCFIDefCfaRegister(Register);
2843 /// ParseDirectiveCFIOffset
2844 /// ::= .cfi_offset register, offset
2845 bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2846 int64_t Register = 0;
2849 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2852 if (getLexer().isNot(AsmToken::Comma))
2853 return TokError("unexpected token in directive");
2856 if (parseAbsoluteExpression(Offset))
2859 getStreamer().EmitCFIOffset(Register, Offset);
2863 /// ParseDirectiveCFIRelOffset
2864 /// ::= .cfi_rel_offset register, offset
2865 bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2866 int64_t Register = 0;
2868 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2871 if (getLexer().isNot(AsmToken::Comma))
2872 return TokError("unexpected token in directive");
2876 if (parseAbsoluteExpression(Offset))
2879 getStreamer().EmitCFIRelOffset(Register, Offset);
2883 static bool isValidEncoding(int64_t Encoding) {
2884 if (Encoding & ~0xff)
2887 if (Encoding == dwarf::DW_EH_PE_omit)
2890 const unsigned Format = Encoding & 0xf;
2891 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2892 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2893 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2894 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2897 const unsigned Application = Encoding & 0x70;
2898 if (Application != dwarf::DW_EH_PE_absptr &&
2899 Application != dwarf::DW_EH_PE_pcrel)
2905 /// ParseDirectiveCFIPersonalityOrLsda
2906 /// IsPersonality true for cfi_personality, false for cfi_lsda
2907 /// ::= .cfi_personality encoding, [symbol_name]
2908 /// ::= .cfi_lsda encoding, [symbol_name]
2909 bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2910 int64_t Encoding = 0;
2911 if (parseAbsoluteExpression(Encoding))
2913 if (Encoding == dwarf::DW_EH_PE_omit)
2916 if (!isValidEncoding(Encoding))
2917 return TokError("unsupported encoding.");
2919 if (getLexer().isNot(AsmToken::Comma))
2920 return TokError("unexpected token in directive");
2924 if (parseIdentifier(Name))
2925 return TokError("expected identifier in directive");
2927 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2930 getStreamer().EmitCFIPersonality(Sym, Encoding);
2932 getStreamer().EmitCFILsda(Sym, Encoding);
2936 /// ParseDirectiveCFIRememberState
2937 /// ::= .cfi_remember_state
2938 bool AsmParser::ParseDirectiveCFIRememberState() {
2939 getStreamer().EmitCFIRememberState();
2943 /// ParseDirectiveCFIRestoreState
2944 /// ::= .cfi_remember_state
2945 bool AsmParser::ParseDirectiveCFIRestoreState() {
2946 getStreamer().EmitCFIRestoreState();
2950 /// ParseDirectiveCFISameValue
2951 /// ::= .cfi_same_value register
2952 bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2953 int64_t Register = 0;
2955 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2958 getStreamer().EmitCFISameValue(Register);
2962 /// ParseDirectiveCFIRestore
2963 /// ::= .cfi_restore register
2964 bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2965 int64_t Register = 0;
2966 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2969 getStreamer().EmitCFIRestore(Register);
2973 /// ParseDirectiveCFIEscape
2974 /// ::= .cfi_escape expression[,...]
2975 bool AsmParser::ParseDirectiveCFIEscape() {
2978 if (parseAbsoluteExpression(CurrValue))
2981 Values.push_back((uint8_t)CurrValue);
2983 while (getLexer().is(AsmToken::Comma)) {
2986 if (parseAbsoluteExpression(CurrValue))
2989 Values.push_back((uint8_t)CurrValue);
2992 getStreamer().EmitCFIEscape(Values);
2996 /// ParseDirectiveCFISignalFrame
2997 /// ::= .cfi_signal_frame
2998 bool AsmParser::ParseDirectiveCFISignalFrame() {
2999 if (getLexer().isNot(AsmToken::EndOfStatement))
3000 return Error(getLexer().getLoc(),
3001 "unexpected token in '.cfi_signal_frame'");
3003 getStreamer().EmitCFISignalFrame();
3007 /// ParseDirectiveCFIUndefined
3008 /// ::= .cfi_undefined register
3009 bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3010 int64_t Register = 0;
3012 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3015 getStreamer().EmitCFIUndefined(Register);
3019 /// ParseDirectiveMacrosOnOff
3022 bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
3023 if (getLexer().isNot(AsmToken::EndOfStatement))
3024 return Error(getLexer().getLoc(),
3025 "unexpected token in '" + Directive + "' directive");
3027 SetMacrosEnabled(Directive == ".macros_on");
3031 /// ParseDirectiveMacro
3032 /// ::= .macro name [parameters]
3033 bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
3035 if (parseIdentifier(Name))
3036 return TokError("expected identifier in '.macro' directive");
3038 MCAsmMacroParameters Parameters;
3039 // Argument delimiter is initially unknown. It will be set by
3040 // ParseMacroArgument()
3041 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3042 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3044 MCAsmMacroParameter Parameter;
3045 if (parseIdentifier(Parameter.first))
3046 return TokError("expected identifier in '.macro' directive");
3048 if (getLexer().is(AsmToken::Equal)) {
3050 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3054 Parameters.push_back(Parameter);
3056 if (getLexer().is(AsmToken::Comma))
3058 else if (getLexer().is(AsmToken::EndOfStatement))
3063 // Eat the end of statement.
3066 AsmToken EndToken, StartToken = getTok();
3068 // Lex the macro definition.
3070 // Check whether we have reached the end of the file.
3071 if (getLexer().is(AsmToken::Eof))
3072 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3074 // Otherwise, check whether we have reach the .endmacro.
3075 if (getLexer().is(AsmToken::Identifier) &&
3076 (getTok().getIdentifier() == ".endm" ||
3077 getTok().getIdentifier() == ".endmacro")) {
3078 EndToken = getTok();
3080 if (getLexer().isNot(AsmToken::EndOfStatement))
3081 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3086 // Otherwise, scan til the end of the statement.
3087 eatToEndOfStatement();
3090 if (LookupMacro(Name)) {
3091 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3094 const char *BodyStart = StartToken.getLoc().getPointer();
3095 const char *BodyEnd = EndToken.getLoc().getPointer();
3096 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3097 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
3098 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3102 /// CheckForBadMacro
3104 /// With the support added for named parameters there may be code out there that
3105 /// is transitioning from positional parameters. In versions of gas that did
3106 /// not support named parameters they would be ignored on the macro defintion.
3107 /// But to support both styles of parameters this is not possible so if a macro
3108 /// defintion has named parameters but does not use them and has what appears
3109 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3110 /// warning that the positional parameter found in body which have no effect.
3111 /// Hoping the developer will either remove the named parameters from the macro
3112 /// definiton so the positional parameters get used if that was what was
3113 /// intended or change the macro to use the named parameters. It is possible
3114 /// this warning will trigger when the none of the named parameters are used
3115 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3116 void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3118 MCAsmMacroParameters Parameters) {
3119 // If this macro is not defined with named parameters the warning we are
3120 // checking for here doesn't apply.
3121 unsigned NParameters = Parameters.size();
3122 if (NParameters == 0)
3125 bool NamedParametersFound = false;
3126 bool PositionalParametersFound = false;
3128 // Look at the body of the macro for use of both the named parameters and what
3129 // are likely to be positional parameters. This is what expandMacro() is
3130 // doing when it finds the parameters in the body.
3131 while (!Body.empty()) {
3132 // Scan for the next possible parameter.
3133 std::size_t End = Body.size(), Pos = 0;
3134 for (; Pos != End; ++Pos) {
3135 // Check for a substitution or escape.
3136 // This macro is defined with parameters, look for \foo, \bar, etc.
3137 if (Body[Pos] == '\\' && Pos + 1 != End)
3140 // This macro should have parameters, but look for $0, $1, ..., $n too.
3141 if (Body[Pos] != '$' || Pos + 1 == End)
3143 char Next = Body[Pos + 1];
3144 if (Next == '$' || Next == 'n' ||
3145 isdigit(static_cast<unsigned char>(Next)))
3149 // Check if we reached the end.
3153 if (Body[Pos] == '$') {
3154 switch (Body[Pos+1]) {
3159 // $n => number of arguments
3161 PositionalParametersFound = true;
3164 // $[0-9] => argument
3166 PositionalParametersFound = true;
3172 unsigned I = Pos + 1;
3173 while (isIdentifierChar(Body[I]) && I + 1 != End)
3176 const char *Begin = Body.data() + Pos +1;
3177 StringRef Argument(Begin, I - (Pos +1));
3179 for (; Index < NParameters; ++Index)
3180 if (Parameters[Index].first == Argument)
3183 if (Index == NParameters) {
3184 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3190 NamedParametersFound = true;
3191 Pos += 1 + Argument.size();
3194 // Update the scan point.
3195 Body = Body.substr(Pos);
3198 if (!NamedParametersFound && PositionalParametersFound)
3199 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3200 "used in macro body, possible positional parameter "
3201 "found in body which will have no effect");
3204 /// ParseDirectiveEndMacro
3207 bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3208 if (getLexer().isNot(AsmToken::EndOfStatement))
3209 return TokError("unexpected token in '" + Directive + "' directive");
3211 // If we are inside a macro instantiation, terminate the current
3213 if (InsideMacroInstantiation()) {
3218 // Otherwise, this .endmacro is a stray entry in the file; well formed
3219 // .endmacro directives are handled during the macro definition parsing.
3220 return TokError("unexpected '" + Directive + "' in file, "
3221 "no current macro definition");
3224 /// ParseDirectivePurgeMacro
3226 bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3228 if (parseIdentifier(Name))
3229 return TokError("expected identifier in '.purgem' directive");
3231 if (getLexer().isNot(AsmToken::EndOfStatement))
3232 return TokError("unexpected token in '.purgem' directive");
3234 if (!LookupMacro(Name))
3235 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3237 UndefineMacro(Name);
3241 /// ParseDirectiveBundleAlignMode
3242 /// ::= {.bundle_align_mode} expression
3243 bool AsmParser::ParseDirectiveBundleAlignMode() {
3244 checkForValidSection();
3246 // Expect a single argument: an expression that evaluates to a constant
3247 // in the inclusive range 0-30.
3248 SMLoc ExprLoc = getLexer().getLoc();
3249 int64_t AlignSizePow2;
3250 if (parseAbsoluteExpression(AlignSizePow2))
3252 else if (getLexer().isNot(AsmToken::EndOfStatement))
3253 return TokError("unexpected token after expression in"
3254 " '.bundle_align_mode' directive");
3255 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3256 return Error(ExprLoc,
3257 "invalid bundle alignment size (expected between 0 and 30)");
3261 // Because of AlignSizePow2's verified range we can safely truncate it to
3263 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3267 /// ParseDirectiveBundleLock
3268 /// ::= {.bundle_lock} [align_to_end]
3269 bool AsmParser::ParseDirectiveBundleLock() {
3270 checkForValidSection();
3271 bool AlignToEnd = false;
3273 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3275 SMLoc Loc = getTok().getLoc();
3276 const char *kInvalidOptionError =
3277 "invalid option for '.bundle_lock' directive";
3279 if (parseIdentifier(Option))
3280 return Error(Loc, kInvalidOptionError);
3282 if (Option != "align_to_end")
3283 return Error(Loc, kInvalidOptionError);
3284 else if (getLexer().isNot(AsmToken::EndOfStatement))
3286 "unexpected token after '.bundle_lock' directive option");
3292 getStreamer().EmitBundleLock(AlignToEnd);
3296 /// ParseDirectiveBundleLock
3297 /// ::= {.bundle_lock}
3298 bool AsmParser::ParseDirectiveBundleUnlock() {
3299 checkForValidSection();
3301 if (getLexer().isNot(AsmToken::EndOfStatement))
3302 return TokError("unexpected token in '.bundle_unlock' directive");
3305 getStreamer().EmitBundleUnlock();
3309 /// ParseDirectiveSpace
3310 /// ::= (.skip | .space) expression [ , expression ]
3311 bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3312 checkForValidSection();
3315 if (parseAbsoluteExpression(NumBytes))
3318 int64_t FillExpr = 0;
3319 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3320 if (getLexer().isNot(AsmToken::Comma))
3321 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3324 if (parseAbsoluteExpression(FillExpr))
3327 if (getLexer().isNot(AsmToken::EndOfStatement))
3328 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3334 return TokError("invalid number of bytes in '" +
3335 Twine(IDVal) + "' directive");
3337 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3338 getStreamer().EmitFill(NumBytes, FillExpr);
3343 /// ParseDirectiveLEB128
3344 /// ::= (.sleb128 | .uleb128) expression
3345 bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3346 checkForValidSection();
3347 const MCExpr *Value;
3349 if (parseExpression(Value))
3352 if (getLexer().isNot(AsmToken::EndOfStatement))
3353 return TokError("unexpected token in directive");
3356 getStreamer().EmitSLEB128Value(Value);
3358 getStreamer().EmitULEB128Value(Value);
3363 /// ParseDirectiveSymbolAttribute
3364 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3365 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3366 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3369 SMLoc Loc = getTok().getLoc();
3371 if (parseIdentifier(Name))
3372 return Error(Loc, "expected identifier in directive");
3374 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3376 // Assembler local symbols don't make any sense here. Complain loudly.
3377 if (Sym->isTemporary())
3378 return Error(Loc, "non-local symbol required in directive");
3380 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3381 return Error(Loc, "unable to emit symbol attribute");
3383 if (getLexer().is(AsmToken::EndOfStatement))
3386 if (getLexer().isNot(AsmToken::Comma))
3387 return TokError("unexpected token in directive");
3396 /// ParseDirectiveComm
3397 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3398 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
3399 checkForValidSection();
3401 SMLoc IDLoc = getLexer().getLoc();
3403 if (parseIdentifier(Name))
3404 return TokError("expected identifier in directive");
3406 // Handle the identifier as the key symbol.
3407 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3409 if (getLexer().isNot(AsmToken::Comma))
3410 return TokError("unexpected token in directive");
3414 SMLoc SizeLoc = getLexer().getLoc();
3415 if (parseAbsoluteExpression(Size))
3418 int64_t Pow2Alignment = 0;
3419 SMLoc Pow2AlignmentLoc;
3420 if (getLexer().is(AsmToken::Comma)) {
3422 Pow2AlignmentLoc = getLexer().getLoc();
3423 if (parseAbsoluteExpression(Pow2Alignment))
3426 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3427 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3428 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3430 // If this target takes alignments in bytes (not log) validate and convert.
3431 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3432 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3433 if (!isPowerOf2_64(Pow2Alignment))
3434 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3435 Pow2Alignment = Log2_64(Pow2Alignment);
3439 if (getLexer().isNot(AsmToken::EndOfStatement))
3440 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3444 // NOTE: a size of zero for a .comm should create a undefined symbol
3445 // but a size of .lcomm creates a bss symbol of size zero.
3447 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3448 "be less than zero");
3450 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3451 // may internally end up wanting an alignment in bytes.
3452 // FIXME: Diagnose overflow.
3453 if (Pow2Alignment < 0)
3454 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3455 "alignment, can't be less than zero");
3457 if (!Sym->isUndefined())
3458 return Error(IDLoc, "invalid symbol redefinition");
3460 // Create the Symbol as a common or local common with Size and Pow2Alignment
3462 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3466 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3470 /// ParseDirectiveAbort
3471 /// ::= .abort [... message ...]
3472 bool AsmParser::ParseDirectiveAbort() {
3473 // FIXME: Use loc from directive.
3474 SMLoc Loc = getLexer().getLoc();
3476 StringRef Str = parseStringToEndOfStatement();
3477 if (getLexer().isNot(AsmToken::EndOfStatement))
3478 return TokError("unexpected token in '.abort' directive");
3483 Error(Loc, ".abort detected. Assembly stopping.");
3485 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3486 // FIXME: Actually abort assembly here.
3491 /// ParseDirectiveInclude
3492 /// ::= .include "filename"
3493 bool AsmParser::ParseDirectiveInclude() {
3494 if (getLexer().isNot(AsmToken::String))
3495 return TokError("expected string in '.include' directive");
3497 std::string Filename = getTok().getString();
3498 SMLoc IncludeLoc = getLexer().getLoc();
3501 if (getLexer().isNot(AsmToken::EndOfStatement))
3502 return TokError("unexpected token in '.include' directive");
3504 // Strip the quotes.
3505 Filename = Filename.substr(1, Filename.size()-2);
3507 // Attempt to switch the lexer to the included file before consuming the end
3508 // of statement to avoid losing it when we switch.
3509 if (EnterIncludeFile(Filename)) {
3510 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3517 /// ParseDirectiveIncbin
3518 /// ::= .incbin "filename"
3519 bool AsmParser::ParseDirectiveIncbin() {
3520 if (getLexer().isNot(AsmToken::String))
3521 return TokError("expected string in '.incbin' directive");
3523 std::string Filename = getTok().getString();
3524 SMLoc IncbinLoc = getLexer().getLoc();
3527 if (getLexer().isNot(AsmToken::EndOfStatement))
3528 return TokError("unexpected token in '.incbin' directive");
3530 // Strip the quotes.
3531 Filename = Filename.substr(1, Filename.size()-2);
3533 // Attempt to process the included file.
3534 if (ProcessIncbinFile(Filename)) {
3535 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3542 /// ParseDirectiveIf
3543 /// ::= .if expression
3544 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
3545 TheCondStack.push_back(TheCondState);
3546 TheCondState.TheCond = AsmCond::IfCond;
3547 if (TheCondState.Ignore) {
3548 eatToEndOfStatement();
3551 if (parseAbsoluteExpression(ExprValue))
3554 if (getLexer().isNot(AsmToken::EndOfStatement))
3555 return TokError("unexpected token in '.if' directive");
3559 TheCondState.CondMet = ExprValue;
3560 TheCondState.Ignore = !TheCondState.CondMet;
3566 /// ParseDirectiveIfb
3568 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3569 TheCondStack.push_back(TheCondState);
3570 TheCondState.TheCond = AsmCond::IfCond;
3572 if (TheCondState.Ignore) {
3573 eatToEndOfStatement();
3575 StringRef Str = parseStringToEndOfStatement();
3577 if (getLexer().isNot(AsmToken::EndOfStatement))
3578 return TokError("unexpected token in '.ifb' directive");
3582 TheCondState.CondMet = ExpectBlank == Str.empty();
3583 TheCondState.Ignore = !TheCondState.CondMet;
3589 /// ParseDirectiveIfc
3590 /// ::= .ifc string1, string2
3591 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3592 TheCondStack.push_back(TheCondState);
3593 TheCondState.TheCond = AsmCond::IfCond;
3595 if (TheCondState.Ignore) {
3596 eatToEndOfStatement();
3598 StringRef Str1 = ParseStringToComma();
3600 if (getLexer().isNot(AsmToken::Comma))
3601 return TokError("unexpected token in '.ifc' directive");
3605 StringRef Str2 = parseStringToEndOfStatement();
3607 if (getLexer().isNot(AsmToken::EndOfStatement))
3608 return TokError("unexpected token in '.ifc' directive");
3612 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3613 TheCondState.Ignore = !TheCondState.CondMet;
3619 /// ParseDirectiveIfdef
3620 /// ::= .ifdef symbol
3621 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3623 TheCondStack.push_back(TheCondState);
3624 TheCondState.TheCond = AsmCond::IfCond;
3626 if (TheCondState.Ignore) {
3627 eatToEndOfStatement();
3629 if (parseIdentifier(Name))
3630 return TokError("expected identifier after '.ifdef'");
3634 MCSymbol *Sym = getContext().LookupSymbol(Name);
3637 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3639 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3640 TheCondState.Ignore = !TheCondState.CondMet;
3646 /// ParseDirectiveElseIf
3647 /// ::= .elseif expression
3648 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3649 if (TheCondState.TheCond != AsmCond::IfCond &&
3650 TheCondState.TheCond != AsmCond::ElseIfCond)
3651 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3653 TheCondState.TheCond = AsmCond::ElseIfCond;
3655 bool LastIgnoreState = false;
3656 if (!TheCondStack.empty())
3657 LastIgnoreState = TheCondStack.back().Ignore;
3658 if (LastIgnoreState || TheCondState.CondMet) {
3659 TheCondState.Ignore = true;
3660 eatToEndOfStatement();
3663 if (parseAbsoluteExpression(ExprValue))
3666 if (getLexer().isNot(AsmToken::EndOfStatement))
3667 return TokError("unexpected token in '.elseif' directive");
3670 TheCondState.CondMet = ExprValue;
3671 TheCondState.Ignore = !TheCondState.CondMet;
3677 /// ParseDirectiveElse
3679 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
3680 if (getLexer().isNot(AsmToken::EndOfStatement))
3681 return TokError("unexpected token in '.else' directive");
3685 if (TheCondState.TheCond != AsmCond::IfCond &&
3686 TheCondState.TheCond != AsmCond::ElseIfCond)
3687 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3689 TheCondState.TheCond = AsmCond::ElseCond;
3690 bool LastIgnoreState = false;
3691 if (!TheCondStack.empty())
3692 LastIgnoreState = TheCondStack.back().Ignore;
3693 if (LastIgnoreState || TheCondState.CondMet)
3694 TheCondState.Ignore = true;
3696 TheCondState.Ignore = false;
3701 /// ParseDirectiveEndIf
3703 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
3704 if (getLexer().isNot(AsmToken::EndOfStatement))
3705 return TokError("unexpected token in '.endif' directive");
3709 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3710 TheCondStack.empty())
3711 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3713 if (!TheCondStack.empty()) {
3714 TheCondState = TheCondStack.back();
3715 TheCondStack.pop_back();
3721 void AsmParser::initializeDirectiveKindMap() {
3722 DirectiveKindMap[".set"] = DK_SET;
3723 DirectiveKindMap[".equ"] = DK_EQU;
3724 DirectiveKindMap[".equiv"] = DK_EQUIV;
3725 DirectiveKindMap[".ascii"] = DK_ASCII;
3726 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3727 DirectiveKindMap[".string"] = DK_STRING;
3728 DirectiveKindMap[".byte"] = DK_BYTE;
3729 DirectiveKindMap[".short"] = DK_SHORT;
3730 DirectiveKindMap[".value"] = DK_VALUE;
3731 DirectiveKindMap[".2byte"] = DK_2BYTE;
3732 DirectiveKindMap[".long"] = DK_LONG;
3733 DirectiveKindMap[".int"] = DK_INT;
3734 DirectiveKindMap[".4byte"] = DK_4BYTE;
3735 DirectiveKindMap[".quad"] = DK_QUAD;
3736 DirectiveKindMap[".8byte"] = DK_8BYTE;
3737 DirectiveKindMap[".single"] = DK_SINGLE;
3738 DirectiveKindMap[".float"] = DK_FLOAT;
3739 DirectiveKindMap[".double"] = DK_DOUBLE;
3740 DirectiveKindMap[".align"] = DK_ALIGN;
3741 DirectiveKindMap[".align32"] = DK_ALIGN32;
3742 DirectiveKindMap[".balign"] = DK_BALIGN;
3743 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3744 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3745 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3746 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3747 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3748 DirectiveKindMap[".org"] = DK_ORG;
3749 DirectiveKindMap[".fill"] = DK_FILL;
3750 DirectiveKindMap[".zero"] = DK_ZERO;
3751 DirectiveKindMap[".extern"] = DK_EXTERN;
3752 DirectiveKindMap[".globl"] = DK_GLOBL;
3753 DirectiveKindMap[".global"] = DK_GLOBAL;
3754 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3755 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3756 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3757 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3758 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3759 DirectiveKindMap[".reference"] = DK_REFERENCE;
3760 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3761 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3762 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3763 DirectiveKindMap[".comm"] = DK_COMM;
3764 DirectiveKindMap[".common"] = DK_COMMON;
3765 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3766 DirectiveKindMap[".abort"] = DK_ABORT;
3767 DirectiveKindMap[".include"] = DK_INCLUDE;
3768 DirectiveKindMap[".incbin"] = DK_INCBIN;
3769 DirectiveKindMap[".code16"] = DK_CODE16;
3770 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3771 DirectiveKindMap[".rept"] = DK_REPT;
3772 DirectiveKindMap[".irp"] = DK_IRP;
3773 DirectiveKindMap[".irpc"] = DK_IRPC;
3774 DirectiveKindMap[".endr"] = DK_ENDR;
3775 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3776 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3777 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3778 DirectiveKindMap[".if"] = DK_IF;
3779 DirectiveKindMap[".ifb"] = DK_IFB;
3780 DirectiveKindMap[".ifnb"] = DK_IFNB;
3781 DirectiveKindMap[".ifc"] = DK_IFC;
3782 DirectiveKindMap[".ifnc"] = DK_IFNC;
3783 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3784 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3785 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3786 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3787 DirectiveKindMap[".else"] = DK_ELSE;
3788 DirectiveKindMap[".endif"] = DK_ENDIF;
3789 DirectiveKindMap[".skip"] = DK_SKIP;
3790 DirectiveKindMap[".space"] = DK_SPACE;
3791 DirectiveKindMap[".file"] = DK_FILE;
3792 DirectiveKindMap[".line"] = DK_LINE;
3793 DirectiveKindMap[".loc"] = DK_LOC;
3794 DirectiveKindMap[".stabs"] = DK_STABS;
3795 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3796 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3797 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3798 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3799 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3800 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3801 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3802 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3803 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3804 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3805 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3806 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3807 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3808 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3809 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3810 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3811 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3812 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3813 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3814 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3815 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3816 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3817 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3818 DirectiveKindMap[".macro"] = DK_MACRO;
3819 DirectiveKindMap[".endm"] = DK_ENDM;
3820 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3821 DirectiveKindMap[".purgem"] = DK_PURGEM;
3825 MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3826 AsmToken EndToken, StartToken = getTok();
3828 unsigned NestLevel = 0;
3830 // Check whether we have reached the end of the file.
3831 if (getLexer().is(AsmToken::Eof)) {
3832 Error(DirectiveLoc, "no matching '.endr' in definition");
3836 if (Lexer.is(AsmToken::Identifier) &&
3837 (getTok().getIdentifier() == ".rept")) {
3841 // Otherwise, check whether we have reached the .endr.
3842 if (Lexer.is(AsmToken::Identifier) &&
3843 getTok().getIdentifier() == ".endr") {
3844 if (NestLevel == 0) {
3845 EndToken = getTok();
3847 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3848 TokError("unexpected token in '.endr' directive");
3856 // Otherwise, scan till the end of the statement.
3857 eatToEndOfStatement();
3860 const char *BodyStart = StartToken.getLoc().getPointer();
3861 const char *BodyEnd = EndToken.getLoc().getPointer();
3862 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3864 // We Are Anonymous.
3866 MCAsmMacroParameters Parameters;
3867 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3868 return &MacroLikeBodies.back();
3871 void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3872 raw_svector_ostream &OS) {
3875 MemoryBuffer *Instantiation =
3876 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3878 // Create the macro instantiation object and add to the current macro
3879 // instantiation stack.
3880 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3884 ActiveMacros.push_back(MI);
3886 // Jump to the macro instantiation and prime the lexer.
3887 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3888 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3892 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3894 if (parseAbsoluteExpression(Count))
3895 return TokError("unexpected token in '.rept' directive");
3898 return TokError("Count is negative");
3900 if (Lexer.isNot(AsmToken::EndOfStatement))
3901 return TokError("unexpected token in '.rept' directive");
3903 // Eat the end of statement.
3906 // Lex the rept definition.
3907 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3911 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3912 // to hold the macro body with substitutions.
3913 SmallString<256> Buf;
3914 MCAsmMacroParameters Parameters;
3915 MCAsmMacroArguments A;
3916 raw_svector_ostream OS(Buf);
3918 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3921 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3926 /// ParseDirectiveIrp
3927 /// ::= .irp symbol,values
3928 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3929 MCAsmMacroParameters Parameters;
3930 MCAsmMacroParameter Parameter;
3932 if (parseIdentifier(Parameter.first))
3933 return TokError("expected identifier in '.irp' directive");
3935 Parameters.push_back(Parameter);
3937 if (Lexer.isNot(AsmToken::Comma))
3938 return TokError("expected comma in '.irp' directive");
3942 MCAsmMacroArguments A;
3943 if (ParseMacroArguments(0, A))
3946 // Eat the end of statement.
3949 // Lex the irp definition.
3950 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3954 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3955 // to hold the macro body with substitutions.
3956 SmallString<256> Buf;
3957 raw_svector_ostream OS(Buf);
3959 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3960 MCAsmMacroArguments Args;
3963 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3967 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3972 /// ParseDirectiveIrpc
3973 /// ::= .irpc symbol,values
3974 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3975 MCAsmMacroParameters Parameters;
3976 MCAsmMacroParameter Parameter;
3978 if (parseIdentifier(Parameter.first))
3979 return TokError("expected identifier in '.irpc' directive");
3981 Parameters.push_back(Parameter);
3983 if (Lexer.isNot(AsmToken::Comma))
3984 return TokError("expected comma in '.irpc' directive");
3988 MCAsmMacroArguments A;
3989 if (ParseMacroArguments(0, A))
3992 if (A.size() != 1 || A.front().size() != 1)
3993 return TokError("unexpected token in '.irpc' directive");
3995 // Eat the end of statement.
3998 // Lex the irpc definition.
3999 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
4003 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4004 // to hold the macro body with substitutions.
4005 SmallString<256> Buf;
4006 raw_svector_ostream OS(Buf);
4008 StringRef Values = A.front().front().getString();
4009 std::size_t I, End = Values.size();
4010 for (I = 0; I < End; ++I) {
4011 MCAsmMacroArgument Arg;
4012 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
4014 MCAsmMacroArguments Args;
4015 Args.push_back(Arg);
4017 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4021 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
4026 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
4027 if (ActiveMacros.empty())
4028 return TokError("unmatched '.endr' directive");
4030 // The only .repl that should get here are the ones created by
4031 // InstantiateMacroLikeBody.
4032 assert(getLexer().is(AsmToken::EndOfStatement));
4038 bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4040 const MCExpr *Value;
4041 SMLoc ExprLoc = getLexer().getLoc();
4042 if (parseExpression(Value))
4044 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4046 return Error(ExprLoc, "unexpected expression in _emit");
4047 uint64_t IntValue = MCE->getValue();
4048 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4049 return Error(ExprLoc, "literal value out of range for directive");
4051 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4055 bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4056 const MCExpr *Value;
4057 SMLoc ExprLoc = getLexer().getLoc();
4058 if (parseExpression(Value))
4060 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4062 return Error(ExprLoc, "unexpected expression in align");
4063 uint64_t IntValue = MCE->getValue();
4064 if (!isPowerOf2_64(IntValue))
4065 return Error(ExprLoc, "literal value not a power of two greater then zero");
4067 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4068 Log2_64(IntValue)));
4072 // We are comparing pointers, but the pointers are relative to a single string.
4073 // Thus, this should always be deterministic.
4074 static int RewritesSort(const void *A, const void *B) {
4075 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4076 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
4077 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4079 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4082 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4083 // rewrite to the same location. Make sure the SizeDirective rewrite is
4084 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4085 // ensures the sort algorithm is stable.
4086 if (AsmRewritePrecedence [AsmRewriteA->Kind] >
4087 AsmRewritePrecedence [AsmRewriteB->Kind])
4090 if (AsmRewritePrecedence [AsmRewriteA->Kind] <
4091 AsmRewritePrecedence [AsmRewriteB->Kind])
4093 llvm_unreachable ("Unstable rewrite sort.");
4097 AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
4098 unsigned &NumOutputs, unsigned &NumInputs,
4099 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4100 SmallVectorImpl<std::string> &Constraints,
4101 SmallVectorImpl<std::string> &Clobbers,
4102 const MCInstrInfo *MII,
4103 const MCInstPrinter *IP,
4104 MCAsmParserSemaCallback &SI) {
4105 SmallVector<void *, 4> InputDecls;
4106 SmallVector<void *, 4> OutputDecls;
4107 SmallVector<bool, 4> InputDeclsAddressOf;
4108 SmallVector<bool, 4> OutputDeclsAddressOf;
4109 SmallVector<std::string, 4> InputConstraints;
4110 SmallVector<std::string, 4> OutputConstraints;
4111 SmallVector<unsigned, 4> ClobberRegs;
4113 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4118 // While we have input, parse each statement.
4119 unsigned InputIdx = 0;
4120 unsigned OutputIdx = 0;
4121 while (getLexer().isNot(AsmToken::Eof)) {
4122 ParseStatementInfo Info(&AsmStrRewrites);
4123 if (ParseStatement(Info))
4126 if (Info.ParseError)
4129 if (Info.Opcode == ~0U)
4132 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4134 // Build the list of clobbers, outputs and inputs.
4135 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4136 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4139 if (Operand->isImm())
4142 // Register operand.
4143 if (Operand->isReg() && !Operand->needAddressOf()) {
4144 unsigned NumDefs = Desc.getNumDefs();
4146 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4147 ClobberRegs.push_back(Operand->getReg());
4151 // Expr/Input or Output.
4152 StringRef SymName = Operand->getSymName();
4153 if (SymName.empty())
4156 void *OpDecl = Operand->getOpDecl();
4160 bool isOutput = (i == 1) && Desc.mayStore();
4161 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4164 OutputDecls.push_back(OpDecl);
4165 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4166 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4167 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4169 InputDecls.push_back(OpDecl);
4170 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4171 InputConstraints.push_back(Operand->getConstraint().str());
4172 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4177 // Set the number of Outputs and Inputs.
4178 NumOutputs = OutputDecls.size();
4179 NumInputs = InputDecls.size();
4181 // Set the unique clobbers.
4182 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4183 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4185 Clobbers.assign(ClobberRegs.size(), std::string());
4186 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4187 raw_string_ostream OS(Clobbers[I]);
4188 IP->printRegName(OS, ClobberRegs[I]);
4191 // Merge the various outputs and inputs. Output are expected first.
4192 if (NumOutputs || NumInputs) {
4193 unsigned NumExprs = NumOutputs + NumInputs;
4194 OpDecls.resize(NumExprs);
4195 Constraints.resize(NumExprs);
4196 for (unsigned i = 0; i < NumOutputs; ++i) {
4197 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4198 Constraints[i] = OutputConstraints[i];
4200 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4201 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4202 Constraints[j] = InputConstraints[i];
4206 // Build the IR assembly string.
4207 std::string AsmStringIR;
4208 raw_string_ostream OS(AsmStringIR);
4209 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4210 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4211 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4212 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4213 E = AsmStrRewrites.end();
4215 AsmRewriteKind Kind = (*I).Kind;
4216 if (Kind == AOK_Delete)
4219 const char *Loc = (*I).Loc.getPointer();
4220 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4222 // Emit everything up to the immediate/expression.
4223 unsigned Len = Loc - AsmStart;
4225 OS << StringRef(AsmStart, Len);
4227 // Skip the original expression.
4228 if (Kind == AOK_Skip) {
4229 AsmStart = Loc + (*I).Len;
4233 unsigned AdditionalSkip = 0;
4234 // Rewrite expressions in $N notation.
4238 OS << "$$" << (*I).Val;
4244 OS << '$' << InputIdx++;
4247 OS << '$' << OutputIdx++;
4249 case AOK_SizeDirective:
4252 case 8: OS << "byte ptr "; break;
4253 case 16: OS << "word ptr "; break;
4254 case 32: OS << "dword ptr "; break;
4255 case 64: OS << "qword ptr "; break;
4256 case 80: OS << "xword ptr "; break;
4257 case 128: OS << "xmmword ptr "; break;
4258 case 256: OS << "ymmword ptr "; break;
4265 unsigned Val = (*I).Val;
4266 OS << ".align " << Val;
4268 // Skip the original immediate.
4269 assert(Val < 10 && "Expected alignment less then 2^10.");
4270 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4273 case AOK_DotOperator:
4278 // Skip the original expression.
4279 AsmStart = Loc + (*I).Len + AdditionalSkip;
4282 // Emit the remainder of the asm string.
4283 if (AsmStart != AsmEnd)
4284 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4286 AsmString = OS.str();
4290 /// \brief Create an MCAsmParser instance.
4291 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4292 MCContext &C, MCStreamer &Out,
4293 const MCAsmInfo &MAI) {
4294 return new AsmParser(SM, C, Out, MAI);