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/STLExtras.h"
16 #include "llvm/ADT/SmallString.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/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 FatalAssemblerWarnings("fatal-assembler-warnings",
49 cl::desc("Consider warnings as error"));
51 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
55 /// \brief Helper types for tracking macro definitions.
56 typedef std::vector<AsmToken> MCAsmMacroArgument;
57 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
59 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
64 MCAsmMacroParameters Parameters;
67 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
68 Name(N), Body(B), Parameters(P) {}
70 MCAsmMacro(const MCAsmMacro& Other)
71 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
74 /// \brief Helper class for storing information about an active macro
76 struct MacroInstantiation {
77 /// The macro being instantiated.
78 const MCAsmMacro *TheMacro;
80 /// The macro instantiation with substitutions.
81 MemoryBuffer *Instantiation;
83 /// The location of the instantiation.
84 SMLoc InstantiationLoc;
86 /// The buffer where parsing should resume upon instantiation completion.
89 /// The location where parsing should resume upon instantiation completion.
93 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
97 struct ParseStatementInfo {
98 /// \brief The parsed operands from the last parsed statement.
99 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
101 /// \brief The opcode from the last parsed instruction.
104 /// \brief Was there an error parsing the inline assembly?
107 SmallVectorImpl<AsmRewrite> *AsmRewrites;
109 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
110 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
111 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
113 ~ParseStatementInfo() {
114 // Free any parsed operands.
115 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
116 delete ParsedOperands[i];
117 ParsedOperands.clear();
121 /// \brief The concrete assembly parser instance.
122 class AsmParser : public MCAsmParser {
123 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
124 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
129 const MCAsmInfo &MAI;
131 SourceMgr::DiagHandlerTy SavedDiagHandler;
132 void *SavedDiagContext;
133 MCAsmParserExtension *PlatformParser;
135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
139 AsmCond TheCondState;
140 std::vector<AsmCond> TheCondStack;
142 /// \brief maps directive names to handler methods in parser
143 /// extensions. Extensions register themselves in this map by calling
144 /// addDirectiveHandler.
145 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
147 /// \brief Map of currently defined macros.
148 StringMap<MCAsmMacro*> MacroMap;
150 /// \brief Stack of active macro instantiations.
151 std::vector<MacroInstantiation*> ActiveMacros;
153 /// \brief List of bodies of anonymous macros.
154 std::deque<MCAsmMacro> MacroLikeBodies;
156 /// Boolean tracking whether macro substitution is enabled.
157 unsigned MacrosEnabledFlag : 1;
159 /// Flag tracking whether any errors have been encountered.
160 unsigned HadError : 1;
162 /// The values from the last parsed cpp hash file line comment if any.
163 StringRef CppHashFilename;
164 int64_t CppHashLineNumber;
167 /// When generating dwarf for assembly source files we need to calculate the
168 /// logical line number based on the last parsed cpp hash file line comment
169 /// and current line. Since this is slow and messes up the SourceMgr's
170 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
171 SMLoc LastQueryIDLoc;
173 unsigned LastQueryLine;
175 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
176 unsigned AssemblerDialect;
178 /// \brief is Darwin compatibility enabled?
181 /// \brief Are we parsing ms-style inline assembly?
182 bool ParsingInlineAsm;
185 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
186 const MCAsmInfo &MAI);
187 virtual ~AsmParser();
189 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
191 virtual void addDirectiveHandler(StringRef Directive,
192 ExtensionDirectiveHandler Handler) {
193 ExtensionDirectiveMap[Directive] = Handler;
197 /// @name MCAsmParser Interface
200 virtual SourceMgr &getSourceManager() { return SrcMgr; }
201 virtual MCAsmLexer &getLexer() { return Lexer; }
202 virtual MCContext &getContext() { return Ctx; }
203 virtual MCStreamer &getStreamer() { return Out; }
204 virtual unsigned getAssemblerDialect() {
205 if (AssemblerDialect == ~0U)
206 return MAI.getAssemblerDialect();
208 return AssemblerDialect;
210 virtual void setAssemblerDialect(unsigned i) {
211 AssemblerDialect = i;
214 virtual void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None);
215 virtual bool Warning(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None);
217 virtual bool Error(SMLoc L, const Twine &Msg,
218 ArrayRef<SMRange> Ranges = None);
220 virtual const AsmToken &Lex();
222 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
223 bool isParsingInlineAsm() { return ParsingInlineAsm; }
225 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
226 unsigned &NumOutputs, unsigned &NumInputs,
227 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
228 SmallVectorImpl<std::string> &Constraints,
229 SmallVectorImpl<std::string> &Clobbers,
230 const MCInstrInfo *MII,
231 const MCInstPrinter *IP,
232 MCAsmParserSemaCallback &SI);
234 bool parseExpression(const MCExpr *&Res);
235 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
236 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
237 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
238 virtual bool parseAbsoluteExpression(int64_t &Res);
240 /// \brief Parse an identifier or string (as a quoted identifier)
241 /// and set \p Res to the identifier contents.
242 virtual bool parseIdentifier(StringRef &Res);
243 virtual void eatToEndOfStatement();
245 virtual void checkForValidSection();
250 bool parseStatement(ParseStatementInfo &Info);
251 void eatToEndOfLine();
252 bool parseCppHashLineFilenameComment(const SMLoc &L);
254 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
255 MCAsmMacroParameters Parameters);
256 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
257 const MCAsmMacroParameters &Parameters,
258 const MCAsmMacroArguments &A,
261 /// \brief Are macros enabled in the parser?
262 bool areMacrosEnabled() {return MacrosEnabledFlag;}
264 /// \brief Control a flag in the parser that enables or disables macros.
265 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
267 /// \brief Lookup a previously defined macro.
268 /// \param Name Macro name.
269 /// \returns Pointer to macro. NULL if no such macro was defined.
270 const MCAsmMacro* lookupMacro(StringRef Name);
272 /// \brief Define a new macro with the given name and information.
273 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
275 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
276 void undefineMacro(StringRef Name);
278 /// \brief Are we inside a macro instantiation?
279 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
281 /// \brief Handle entry to macro instantiation.
283 /// \param M The macro.
284 /// \param NameLoc Instantiation location.
285 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
287 /// \brief Handle exit from macro instantiation.
288 void handleMacroExit();
290 /// \brief Extract AsmTokens for a macro argument.
291 bool parseMacroArgument(MCAsmMacroArgument &MA);
293 /// \brief Parse all macro arguments for a given macro.
294 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
296 void printMacroInstantiations();
297 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
298 ArrayRef<SMRange> Ranges = None) const {
299 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
301 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
303 /// \brief Enter the specified file. This returns true on failure.
304 bool enterIncludeFile(const std::string &Filename);
306 /// \brief 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 parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
331 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
332 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
334 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
336 // Generic (target and platform independent) directive parsing.
338 DK_NO_DIRECTIVE, // Placeholder
339 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
340 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
341 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
342 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
343 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
344 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
345 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
346 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
347 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
348 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
349 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
350 DK_ELSEIF, DK_ELSE, DK_ENDIF,
351 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
352 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
353 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
354 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
355 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
356 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
357 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
358 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
359 DK_SLEB128, DK_ULEB128,
363 /// \brief 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 parseDirectiveOctaValue(); // ".octa"
371 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
372 bool parseDirectiveFill(); // ".fill"
373 bool parseDirectiveZero(); // ".zero"
374 // ".set", ".equ", ".equiv"
375 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
376 bool parseDirectiveOrg(); // ".org"
377 // ".align{,32}", ".p2align{,w,l}"
378 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
380 // ".file", ".line", ".loc", ".stabs"
381 bool parseDirectiveFile(SMLoc DirectiveLoc);
382 bool parseDirectiveLine();
383 bool parseDirectiveLoc();
384 bool parseDirectiveStabs();
387 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
388 bool parseDirectiveCFIWindowSave();
389 bool parseDirectiveCFISections();
390 bool parseDirectiveCFIStartProc();
391 bool parseDirectiveCFIEndProc();
392 bool parseDirectiveCFIDefCfaOffset();
393 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
394 bool parseDirectiveCFIAdjustCfaOffset();
395 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
399 bool parseDirectiveCFIRememberState();
400 bool parseDirectiveCFIRestoreState();
401 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIEscape();
404 bool parseDirectiveCFISignalFrame();
405 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
408 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
409 bool parseDirectiveEndMacro(StringRef Directive);
410 bool parseDirectiveMacro(SMLoc DirectiveLoc);
411 bool parseDirectiveMacrosOnOff(StringRef Directive);
413 // ".bundle_align_mode"
414 bool parseDirectiveBundleAlignMode();
416 bool parseDirectiveBundleLock();
418 bool parseDirectiveBundleUnlock();
421 bool parseDirectiveSpace(StringRef IDVal);
423 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
424 bool parseDirectiveLEB128(bool Signed);
426 /// \brief Parse a directive like ".globl" which
427 /// accepts a single symbol (which should be a label or an external).
428 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
430 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
432 bool parseDirectiveAbort(); // ".abort"
433 bool parseDirectiveInclude(); // ".include"
434 bool parseDirectiveIncbin(); // ".incbin"
436 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
437 // ".ifb" or ".ifnb", depending on ExpectBlank.
438 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
439 // ".ifc" or ".ifnc", depending on ExpectEqual.
440 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
441 // ".ifdef" or ".ifndef", depending on expect_defined
442 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
443 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
444 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
445 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
446 virtual bool parseEscapedString(std::string &Data);
448 const MCExpr *applyModifierToExpr(const MCExpr *E,
449 MCSymbolRefExpr::VariantKind Variant);
451 // Macro-like directives
452 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
453 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
454 raw_svector_ostream &OS);
455 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
456 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
457 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
458 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
460 // "_emit" or "__emit"
461 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
465 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
468 bool parseDirectiveEnd(SMLoc DirectiveLoc);
470 void initializeDirectiveKindMap();
476 extern MCAsmParserExtension *createDarwinAsmParser();
477 extern MCAsmParserExtension *createELFAsmParser();
478 extern MCAsmParserExtension *createCOFFAsmParser();
482 enum { DEFAULT_ADDRSPACE = 0 };
484 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
485 const MCAsmInfo &_MAI)
486 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
487 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
488 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
489 ParsingInlineAsm(false) {
490 // Save the old handler.
491 SavedDiagHandler = SrcMgr.getDiagHandler();
492 SavedDiagContext = SrcMgr.getDiagContext();
493 // Set our own handler which calls the saved handler.
494 SrcMgr.setDiagHandler(DiagHandler, this);
495 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
497 // Initialize the platform / file format parser.
498 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
499 case MCObjectFileInfo::IsCOFF:
500 PlatformParser = createCOFFAsmParser();
501 PlatformParser->Initialize(*this);
503 case MCObjectFileInfo::IsMachO:
504 PlatformParser = createDarwinAsmParser();
505 PlatformParser->Initialize(*this);
508 case MCObjectFileInfo::IsELF:
509 PlatformParser = createELFAsmParser();
510 PlatformParser->Initialize(*this);
514 initializeDirectiveKindMap();
517 AsmParser::~AsmParser() {
518 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
520 // Destroy any macros.
521 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
524 delete it->getValue();
526 delete PlatformParser;
529 void AsmParser::printMacroInstantiations() {
530 // Print the active macro instantiation stack.
531 for (std::vector<MacroInstantiation *>::const_reverse_iterator
532 it = ActiveMacros.rbegin(),
533 ie = ActiveMacros.rend();
535 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
536 "while in macro instantiation");
539 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
540 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
541 printMacroInstantiations();
544 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
545 if (FatalAssemblerWarnings)
546 return Error(L, Msg, Ranges);
547 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
548 printMacroInstantiations();
552 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
554 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
555 printMacroInstantiations();
559 bool AsmParser::enterIncludeFile(const std::string &Filename) {
560 std::string IncludedFile;
561 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
567 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
572 /// Process the specified .incbin file by searching for it in the include paths
573 /// then just emitting the byte contents of the file to the streamer. This
574 /// returns true on failure.
575 bool AsmParser::processIncbinFile(const std::string &Filename) {
576 std::string IncludedFile;
577 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
581 // Pick up the bytes from the file and emit them.
582 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
586 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
587 if (InBuffer != -1) {
588 CurBuffer = InBuffer;
590 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
592 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
595 const AsmToken &AsmParser::Lex() {
596 const AsmToken *tok = &Lexer.Lex();
598 if (tok->is(AsmToken::Eof)) {
599 // If this is the end of an included file, pop the parent file off the
601 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
602 if (ParentIncludeLoc != SMLoc()) {
603 jumpToLoc(ParentIncludeLoc);
608 if (tok->is(AsmToken::Error))
609 Error(Lexer.getErrLoc(), Lexer.getErr());
614 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
615 // Create the initial section, if requested.
616 if (!NoInitialTextSection)
623 AsmCond StartingCondState = TheCondState;
625 // If we are generating dwarf for assembly source files save the initial text
626 // section and generate a .file directive.
627 if (getContext().getGenDwarfForAssembly()) {
628 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
629 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
630 getStreamer().EmitLabel(SectionStartSym);
631 getContext().setGenDwarfSectionStartSym(SectionStartSym);
632 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
634 getContext().getMainFileName());
637 // While we have input, parse each statement.
638 while (Lexer.isNot(AsmToken::Eof)) {
639 ParseStatementInfo Info;
640 if (!parseStatement(Info))
643 // We had an error, validate that one was emitted and recover by skipping to
645 assert(HadError && "Parse statement returned an error, but none emitted!");
646 eatToEndOfStatement();
649 if (TheCondState.TheCond != StartingCondState.TheCond ||
650 TheCondState.Ignore != StartingCondState.Ignore)
651 return TokError("unmatched .ifs or .elses");
653 // Check to see there are no empty DwarfFile slots.
654 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
655 getContext().getMCDwarfFiles();
656 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
657 if (!MCDwarfFiles[i])
658 TokError("unassigned file number: " + Twine(i) + " for .file directives");
661 // Check to see that all assembler local symbols were actually defined.
662 // Targets that don't do subsections via symbols may not want this, though,
663 // so conservatively exclude them. Only do this if we're finalizing, though,
664 // as otherwise we won't necessarilly have seen everything yet.
665 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
666 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
667 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
670 MCSymbol *Sym = i->getValue();
671 // Variable symbols may not be marked as defined, so check those
672 // explicitly. If we know it's a variable, we have a definition for
673 // the purposes of this check.
674 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
675 // FIXME: We would really like to refer back to where the symbol was
676 // first referenced for a source location. We need to add something
677 // to track that. Currently, we just point to the end of the file.
679 getLexer().getLoc(), SourceMgr::DK_Error,
680 "assembler local symbol '" + Sym->getName() + "' not defined");
684 // Callback to the target parser in case it needs to do anything.
686 getTargetParser().finishParse();
688 // Finalize the output stream if there are no errors and if the client wants
690 if (!HadError && !NoFinalize)
696 void AsmParser::checkForValidSection() {
697 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
698 TokError("expected section directive before assembly directive");
703 /// \brief Throw away the rest of the line for testing purposes.
704 void AsmParser::eatToEndOfStatement() {
705 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
709 if (Lexer.is(AsmToken::EndOfStatement))
713 StringRef AsmParser::parseStringToEndOfStatement() {
714 const char *Start = getTok().getLoc().getPointer();
716 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
719 const char *End = getTok().getLoc().getPointer();
720 return StringRef(Start, End - Start);
723 StringRef AsmParser::parseStringToComma() {
724 const char *Start = getTok().getLoc().getPointer();
726 while (Lexer.isNot(AsmToken::EndOfStatement) &&
727 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
730 const char *End = getTok().getLoc().getPointer();
731 return StringRef(Start, End - Start);
734 /// \brief Parse a paren expression and return it.
735 /// NOTE: This assumes the leading '(' has already been consumed.
737 /// parenexpr ::= expr)
739 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
740 if (parseExpression(Res))
742 if (Lexer.isNot(AsmToken::RParen))
743 return TokError("expected ')' in parentheses expression");
744 EndLoc = Lexer.getTok().getEndLoc();
749 /// \brief Parse a bracket expression and return it.
750 /// NOTE: This assumes the leading '[' has already been consumed.
752 /// bracketexpr ::= expr]
754 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
755 if (parseExpression(Res))
757 if (Lexer.isNot(AsmToken::RBrac))
758 return TokError("expected ']' in brackets expression");
759 EndLoc = Lexer.getTok().getEndLoc();
764 /// \brief Parse a primary expression and return it.
765 /// primaryexpr ::= (parenexpr
766 /// primaryexpr ::= symbol
767 /// primaryexpr ::= number
768 /// primaryexpr ::= '.'
769 /// primaryexpr ::= ~,+,- primaryexpr
770 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
771 SMLoc FirstTokenLoc = getLexer().getLoc();
772 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
773 switch (FirstTokenKind) {
775 return TokError("unknown token in expression");
776 // If we have an error assume that we've already handled it.
777 case AsmToken::Error:
779 case AsmToken::Exclaim:
780 Lex(); // Eat the operator.
781 if (parsePrimaryExpr(Res, EndLoc))
783 Res = MCUnaryExpr::CreateLNot(Res, getContext());
785 case AsmToken::Dollar:
787 case AsmToken::String:
788 case AsmToken::Identifier: {
789 StringRef Identifier;
790 if (parseIdentifier(Identifier)) {
791 if (FirstTokenKind == AsmToken::Dollar) {
792 if (Lexer.getMAI().getDollarIsPC()) {
793 // This is a '$' reference, which references the current PC. Emit a
794 // temporary label to the streamer and refer to it.
795 MCSymbol *Sym = Ctx.CreateTempSymbol();
797 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
799 EndLoc = FirstTokenLoc;
802 return Error(FirstTokenLoc, "invalid token in expression");
806 // Parse symbol variant
807 std::pair<StringRef, StringRef> Split;
808 if (!MAI.useParensForSymbolVariant()) {
809 Split = Identifier.split('@');
810 } else if (Lexer.is(AsmToken::LParen)) {
811 Lexer.Lex(); // eat (
813 parseIdentifier(VName);
814 if (Lexer.isNot(AsmToken::RParen)) {
815 return Error(Lexer.getTok().getLoc(),
816 "unexpected token in variant, expected ')'");
818 Lexer.Lex(); // eat )
819 Split = std::make_pair(Identifier, VName);
822 EndLoc = SMLoc::getFromPointer(Identifier.end());
824 // This is a symbol reference.
825 StringRef SymbolName = Identifier;
826 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
828 // Lookup the symbol variant if used.
829 if (Split.second.size()) {
830 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
831 if (Variant != MCSymbolRefExpr::VK_Invalid) {
832 SymbolName = Split.first;
833 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
834 Variant = MCSymbolRefExpr::VK_None;
836 Variant = MCSymbolRefExpr::VK_None;
837 return Error(SMLoc::getFromPointer(Split.second.begin()),
838 "invalid variant '" + Split.second + "'");
842 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
844 // If this is an absolute variable reference, substitute it now to preserve
845 // semantics in the face of reassignment.
846 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
848 return Error(EndLoc, "unexpected modifier on variable reference");
850 Res = Sym->getVariableValue();
854 // Otherwise create a symbol ref.
855 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
858 case AsmToken::BigNum:
859 return TokError("literal value out of range for directive");
860 case AsmToken::Integer: {
861 SMLoc Loc = getTok().getLoc();
862 int64_t IntVal = getTok().getIntVal();
863 Res = MCConstantExpr::Create(IntVal, getContext());
864 EndLoc = Lexer.getTok().getEndLoc();
866 // Look for 'b' or 'f' following an Integer as a directional label
867 if (Lexer.getKind() == AsmToken::Identifier) {
868 StringRef IDVal = getTok().getString();
869 // Lookup the symbol variant if used.
870 std::pair<StringRef, StringRef> Split = IDVal.split('@');
871 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
872 if (Split.first.size() != IDVal.size()) {
873 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
874 if (Variant == MCSymbolRefExpr::VK_Invalid) {
875 Variant = MCSymbolRefExpr::VK_None;
876 return TokError("invalid variant '" + Split.second + "'");
880 if (IDVal == "f" || IDVal == "b") {
882 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
883 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
884 if (IDVal == "b" && Sym->isUndefined())
885 return Error(Loc, "invalid reference to undefined symbol");
886 EndLoc = Lexer.getTok().getEndLoc();
887 Lex(); // Eat identifier.
892 case AsmToken::Real: {
893 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
894 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
895 Res = MCConstantExpr::Create(IntVal, getContext());
896 EndLoc = Lexer.getTok().getEndLoc();
900 case AsmToken::Dot: {
901 // This is a '.' reference, which references the current PC. Emit a
902 // temporary label to the streamer and refer to it.
903 MCSymbol *Sym = Ctx.CreateTempSymbol();
905 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
906 EndLoc = Lexer.getTok().getEndLoc();
907 Lex(); // Eat identifier.
910 case AsmToken::LParen:
911 Lex(); // Eat the '('.
912 return parseParenExpr(Res, EndLoc);
913 case AsmToken::LBrac:
914 if (!PlatformParser->HasBracketExpressions())
915 return TokError("brackets expression not supported on this target");
916 Lex(); // Eat the '['.
917 return parseBracketExpr(Res, EndLoc);
918 case AsmToken::Minus:
919 Lex(); // Eat the operator.
920 if (parsePrimaryExpr(Res, EndLoc))
922 Res = MCUnaryExpr::CreateMinus(Res, getContext());
925 Lex(); // Eat the operator.
926 if (parsePrimaryExpr(Res, EndLoc))
928 Res = MCUnaryExpr::CreatePlus(Res, getContext());
930 case AsmToken::Tilde:
931 Lex(); // Eat the operator.
932 if (parsePrimaryExpr(Res, EndLoc))
934 Res = MCUnaryExpr::CreateNot(Res, getContext());
939 bool AsmParser::parseExpression(const MCExpr *&Res) {
941 return parseExpression(Res, EndLoc);
945 AsmParser::applyModifierToExpr(const MCExpr *E,
946 MCSymbolRefExpr::VariantKind Variant) {
947 // Ask the target implementation about this expression first.
948 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
951 // Recurse over the given expression, rebuilding it to apply the given variant
952 // if there is exactly one symbol.
953 switch (E->getKind()) {
955 case MCExpr::Constant:
958 case MCExpr::SymbolRef: {
959 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
961 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
962 TokError("invalid variant on expression '" + getTok().getIdentifier() +
963 "' (already modified)");
967 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
970 case MCExpr::Unary: {
971 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
972 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
975 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
978 case MCExpr::Binary: {
979 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
980 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
981 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
991 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
995 llvm_unreachable("Invalid expression kind!");
998 /// \brief Parse an expression and return it.
1000 /// expr ::= expr &&,|| expr -> lowest.
1001 /// expr ::= expr |,^,&,! expr
1002 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1003 /// expr ::= expr <<,>> expr
1004 /// expr ::= expr +,- expr
1005 /// expr ::= expr *,/,% expr -> highest.
1006 /// expr ::= primaryexpr
1008 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1009 // Parse the expression.
1011 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1014 // As a special case, we support 'a op b @ modifier' by rewriting the
1015 // expression to include the modifier. This is inefficient, but in general we
1016 // expect users to use 'a@modifier op b'.
1017 if (Lexer.getKind() == AsmToken::At) {
1020 if (Lexer.isNot(AsmToken::Identifier))
1021 return TokError("unexpected symbol modifier following '@'");
1023 MCSymbolRefExpr::VariantKind Variant =
1024 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1025 if (Variant == MCSymbolRefExpr::VK_Invalid)
1026 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1028 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1030 return TokError("invalid modifier '" + getTok().getIdentifier() +
1031 "' (no symbols present)");
1038 // Try to constant fold it up front, if possible.
1040 if (Res->EvaluateAsAbsolute(Value))
1041 Res = MCConstantExpr::Create(Value, getContext());
1046 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1048 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1051 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1054 SMLoc StartLoc = Lexer.getLoc();
1055 if (parseExpression(Expr))
1058 if (!Expr->EvaluateAsAbsolute(Res))
1059 return Error(StartLoc, "expected absolute expression");
1064 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1065 MCBinaryExpr::Opcode &Kind) {
1068 return 0; // not a binop.
1070 // Lowest Precedence: &&, ||
1071 case AsmToken::AmpAmp:
1072 Kind = MCBinaryExpr::LAnd;
1074 case AsmToken::PipePipe:
1075 Kind = MCBinaryExpr::LOr;
1078 // Low Precedence: |, &, ^
1080 // FIXME: gas seems to support '!' as an infix operator?
1081 case AsmToken::Pipe:
1082 Kind = MCBinaryExpr::Or;
1084 case AsmToken::Caret:
1085 Kind = MCBinaryExpr::Xor;
1088 Kind = MCBinaryExpr::And;
1091 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1092 case AsmToken::EqualEqual:
1093 Kind = MCBinaryExpr::EQ;
1095 case AsmToken::ExclaimEqual:
1096 case AsmToken::LessGreater:
1097 Kind = MCBinaryExpr::NE;
1099 case AsmToken::Less:
1100 Kind = MCBinaryExpr::LT;
1102 case AsmToken::LessEqual:
1103 Kind = MCBinaryExpr::LTE;
1105 case AsmToken::Greater:
1106 Kind = MCBinaryExpr::GT;
1108 case AsmToken::GreaterEqual:
1109 Kind = MCBinaryExpr::GTE;
1112 // Intermediate Precedence: <<, >>
1113 case AsmToken::LessLess:
1114 Kind = MCBinaryExpr::Shl;
1116 case AsmToken::GreaterGreater:
1117 Kind = MCBinaryExpr::Shr;
1120 // High Intermediate Precedence: +, -
1121 case AsmToken::Plus:
1122 Kind = MCBinaryExpr::Add;
1124 case AsmToken::Minus:
1125 Kind = MCBinaryExpr::Sub;
1128 // Highest Precedence: *, /, %
1129 case AsmToken::Star:
1130 Kind = MCBinaryExpr::Mul;
1132 case AsmToken::Slash:
1133 Kind = MCBinaryExpr::Div;
1135 case AsmToken::Percent:
1136 Kind = MCBinaryExpr::Mod;
1141 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1142 /// Res contains the LHS of the expression on input.
1143 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1146 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1147 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1149 // If the next token is lower precedence than we are allowed to eat, return
1150 // successfully with what we ate already.
1151 if (TokPrec < Precedence)
1156 // Eat the next primary expression.
1158 if (parsePrimaryExpr(RHS, EndLoc))
1161 // If BinOp binds less tightly with RHS than the operator after RHS, let
1162 // the pending operator take RHS as its LHS.
1163 MCBinaryExpr::Opcode Dummy;
1164 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1165 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1168 // Merge LHS and RHS according to operator.
1169 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1174 /// ::= EndOfStatement
1175 /// ::= Label* Directive ...Operands... EndOfStatement
1176 /// ::= Label* Identifier OperandList* EndOfStatement
1177 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1178 if (Lexer.is(AsmToken::EndOfStatement)) {
1184 // Statements always start with an identifier or are a full line comment.
1185 AsmToken ID = getTok();
1186 SMLoc IDLoc = ID.getLoc();
1188 int64_t LocalLabelVal = -1;
1189 // A full line comment is a '#' as the first token.
1190 if (Lexer.is(AsmToken::Hash))
1191 return parseCppHashLineFilenameComment(IDLoc);
1193 // Allow an integer followed by a ':' as a directional local label.
1194 if (Lexer.is(AsmToken::Integer)) {
1195 LocalLabelVal = getTok().getIntVal();
1196 if (LocalLabelVal < 0) {
1197 if (!TheCondState.Ignore)
1198 return TokError("unexpected token at start of statement");
1201 IDVal = getTok().getString();
1202 Lex(); // Consume the integer token to be used as an identifier token.
1203 if (Lexer.getKind() != AsmToken::Colon) {
1204 if (!TheCondState.Ignore)
1205 return TokError("unexpected token at start of statement");
1208 } else if (Lexer.is(AsmToken::Dot)) {
1209 // Treat '.' as a valid identifier in this context.
1212 } else if (parseIdentifier(IDVal)) {
1213 if (!TheCondState.Ignore)
1214 return TokError("unexpected token at start of statement");
1218 // Handle conditional assembly here before checking for skipping. We
1219 // have to do this so that .endif isn't skipped in a ".if 0" block for
1221 StringMap<DirectiveKind>::const_iterator DirKindIt =
1222 DirectiveKindMap.find(IDVal);
1223 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1225 : DirKindIt->getValue();
1230 return parseDirectiveIf(IDLoc);
1232 return parseDirectiveIfb(IDLoc, true);
1234 return parseDirectiveIfb(IDLoc, false);
1236 return parseDirectiveIfc(IDLoc, true);
1238 return parseDirectiveIfc(IDLoc, false);
1240 return parseDirectiveIfdef(IDLoc, true);
1243 return parseDirectiveIfdef(IDLoc, false);
1245 return parseDirectiveElseIf(IDLoc);
1247 return parseDirectiveElse(IDLoc);
1249 return parseDirectiveEndIf(IDLoc);
1252 // Ignore the statement if in the middle of inactive conditional
1254 if (TheCondState.Ignore) {
1255 eatToEndOfStatement();
1259 // FIXME: Recurse on local labels?
1261 // See what kind of statement we have.
1262 switch (Lexer.getKind()) {
1263 case AsmToken::Colon: {
1264 checkForValidSection();
1266 // identifier ':' -> Label.
1269 // Diagnose attempt to use '.' as a label.
1271 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1273 // Diagnose attempt to use a variable as a label.
1275 // FIXME: Diagnostics. Note the location of the definition as a label.
1276 // FIXME: This doesn't diagnose assignment to a symbol which has been
1277 // implicitly marked as external.
1279 if (LocalLabelVal == -1)
1280 Sym = getContext().GetOrCreateSymbol(IDVal);
1282 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1283 if (!Sym->isUndefined() || Sym->isVariable())
1284 return Error(IDLoc, "invalid symbol redefinition");
1287 if (!ParsingInlineAsm)
1290 // If we are generating dwarf for assembly source files then gather the
1291 // info to make a dwarf label entry for this label if needed.
1292 if (getContext().getGenDwarfForAssembly())
1293 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1296 getTargetParser().onLabelParsed(Sym);
1298 // Consume any end of statement token, if present, to avoid spurious
1299 // AddBlankLine calls().
1300 if (Lexer.is(AsmToken::EndOfStatement)) {
1302 if (Lexer.is(AsmToken::Eof))
1309 case AsmToken::Equal:
1310 // identifier '=' ... -> assignment statement
1313 return parseAssignment(IDVal, true);
1315 default: // Normal instruction or directive.
1319 // If macros are enabled, check to see if this is a macro instantiation.
1320 if (areMacrosEnabled())
1321 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1322 return handleMacroEntry(M, IDLoc);
1325 // Otherwise, we have a normal instruction or directive.
1327 // Directives start with "."
1328 if (IDVal[0] == '.' && IDVal != ".") {
1329 // There are several entities interested in parsing directives:
1331 // 1. The target-specific assembly parser. Some directives are target
1332 // specific or may potentially behave differently on certain targets.
1333 // 2. Asm parser extensions. For example, platform-specific parsers
1334 // (like the ELF parser) register themselves as extensions.
1335 // 3. The generic directive parser implemented by this class. These are
1336 // all the directives that behave in a target and platform independent
1337 // manner, or at least have a default behavior that's shared between
1338 // all targets and platforms.
1340 // First query the target-specific parser. It will return 'true' if it
1341 // isn't interested in this directive.
1342 if (!getTargetParser().ParseDirective(ID))
1345 // Next, check the extension directive map to see if any extension has
1346 // registered itself to parse this directive.
1347 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1348 ExtensionDirectiveMap.lookup(IDVal);
1350 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1352 // Finally, if no one else is interested in this directive, it must be
1353 // generic and familiar to this class.
1359 return parseDirectiveSet(IDVal, true);
1361 return parseDirectiveSet(IDVal, false);
1363 return parseDirectiveAscii(IDVal, false);
1366 return parseDirectiveAscii(IDVal, true);
1368 return parseDirectiveValue(1);
1372 return parseDirectiveValue(2);
1376 return parseDirectiveValue(4);
1379 return parseDirectiveValue(8);
1381 return parseDirectiveOctaValue();
1384 return parseDirectiveRealValue(APFloat::IEEEsingle);
1386 return parseDirectiveRealValue(APFloat::IEEEdouble);
1388 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1389 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1392 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1393 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1396 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1398 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1400 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1402 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1404 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1406 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1408 return parseDirectiveOrg();
1410 return parseDirectiveFill();
1412 return parseDirectiveZero();
1414 eatToEndOfStatement(); // .extern is the default, ignore it.
1418 return parseDirectiveSymbolAttribute(MCSA_Global);
1419 case DK_LAZY_REFERENCE:
1420 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1421 case DK_NO_DEAD_STRIP:
1422 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1423 case DK_SYMBOL_RESOLVER:
1424 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1425 case DK_PRIVATE_EXTERN:
1426 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1428 return parseDirectiveSymbolAttribute(MCSA_Reference);
1429 case DK_WEAK_DEFINITION:
1430 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1431 case DK_WEAK_REFERENCE:
1432 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1433 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1434 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1437 return parseDirectiveComm(/*IsLocal=*/false);
1439 return parseDirectiveComm(/*IsLocal=*/true);
1441 return parseDirectiveAbort();
1443 return parseDirectiveInclude();
1445 return parseDirectiveIncbin();
1448 return TokError(Twine(IDVal) + " not supported yet");
1450 return parseDirectiveRept(IDLoc, IDVal);
1452 return parseDirectiveIrp(IDLoc);
1454 return parseDirectiveIrpc(IDLoc);
1456 return parseDirectiveEndr(IDLoc);
1457 case DK_BUNDLE_ALIGN_MODE:
1458 return parseDirectiveBundleAlignMode();
1459 case DK_BUNDLE_LOCK:
1460 return parseDirectiveBundleLock();
1461 case DK_BUNDLE_UNLOCK:
1462 return parseDirectiveBundleUnlock();
1464 return parseDirectiveLEB128(true);
1466 return parseDirectiveLEB128(false);
1469 return parseDirectiveSpace(IDVal);
1471 return parseDirectiveFile(IDLoc);
1473 return parseDirectiveLine();
1475 return parseDirectiveLoc();
1477 return parseDirectiveStabs();
1478 case DK_CFI_SECTIONS:
1479 return parseDirectiveCFISections();
1480 case DK_CFI_STARTPROC:
1481 return parseDirectiveCFIStartProc();
1482 case DK_CFI_ENDPROC:
1483 return parseDirectiveCFIEndProc();
1484 case DK_CFI_DEF_CFA:
1485 return parseDirectiveCFIDefCfa(IDLoc);
1486 case DK_CFI_DEF_CFA_OFFSET:
1487 return parseDirectiveCFIDefCfaOffset();
1488 case DK_CFI_ADJUST_CFA_OFFSET:
1489 return parseDirectiveCFIAdjustCfaOffset();
1490 case DK_CFI_DEF_CFA_REGISTER:
1491 return parseDirectiveCFIDefCfaRegister(IDLoc);
1493 return parseDirectiveCFIOffset(IDLoc);
1494 case DK_CFI_REL_OFFSET:
1495 return parseDirectiveCFIRelOffset(IDLoc);
1496 case DK_CFI_PERSONALITY:
1497 return parseDirectiveCFIPersonalityOrLsda(true);
1499 return parseDirectiveCFIPersonalityOrLsda(false);
1500 case DK_CFI_REMEMBER_STATE:
1501 return parseDirectiveCFIRememberState();
1502 case DK_CFI_RESTORE_STATE:
1503 return parseDirectiveCFIRestoreState();
1504 case DK_CFI_SAME_VALUE:
1505 return parseDirectiveCFISameValue(IDLoc);
1506 case DK_CFI_RESTORE:
1507 return parseDirectiveCFIRestore(IDLoc);
1509 return parseDirectiveCFIEscape();
1510 case DK_CFI_SIGNAL_FRAME:
1511 return parseDirectiveCFISignalFrame();
1512 case DK_CFI_UNDEFINED:
1513 return parseDirectiveCFIUndefined(IDLoc);
1514 case DK_CFI_REGISTER:
1515 return parseDirectiveCFIRegister(IDLoc);
1516 case DK_CFI_WINDOW_SAVE:
1517 return parseDirectiveCFIWindowSave();
1520 return parseDirectiveMacrosOnOff(IDVal);
1522 return parseDirectiveMacro(IDLoc);
1525 return parseDirectiveEndMacro(IDVal);
1527 return parseDirectivePurgeMacro(IDLoc);
1529 return parseDirectiveEnd(IDLoc);
1532 return Error(IDLoc, "unknown directive");
1535 // __asm _emit or __asm __emit
1536 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1537 IDVal == "_EMIT" || IDVal == "__EMIT"))
1538 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1541 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1542 return parseDirectiveMSAlign(IDLoc, Info);
1544 checkForValidSection();
1546 // Canonicalize the opcode to lower case.
1547 std::string OpcodeStr = IDVal.lower();
1548 ParseInstructionInfo IInfo(Info.AsmRewrites);
1549 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1550 Info.ParsedOperands);
1551 Info.ParseError = HadError;
1553 // Dump the parsed representation, if requested.
1554 if (getShowParsedOperands()) {
1555 SmallString<256> Str;
1556 raw_svector_ostream OS(Str);
1557 OS << "parsed instruction: [";
1558 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1561 Info.ParsedOperands[i]->print(OS);
1565 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1568 // If we are generating dwarf for assembly source files and the current
1569 // section is the initial text section then generate a .loc directive for
1571 if (!HadError && getContext().getGenDwarfForAssembly() &&
1572 getContext().getGenDwarfSection() ==
1573 getStreamer().getCurrentSection().first) {
1575 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1577 // If we previously parsed a cpp hash file line comment then make sure the
1578 // current Dwarf File is for the CppHashFilename if not then emit the
1579 // Dwarf File table for it and adjust the line number for the .loc.
1580 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1581 getContext().getMCDwarfFiles();
1582 if (CppHashFilename.size() != 0) {
1583 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1585 getStreamer().EmitDwarfFileDirective(
1586 getContext().nextGenDwarfFileNumber(), StringRef(),
1589 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1590 // cache with the different Loc from the call above we save the last
1591 // info we queried here with SrcMgr.FindLineNumber().
1592 unsigned CppHashLocLineNo;
1593 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1594 CppHashLocLineNo = LastQueryLine;
1596 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1597 LastQueryLine = CppHashLocLineNo;
1598 LastQueryIDLoc = CppHashLoc;
1599 LastQueryBuffer = CppHashBuf;
1601 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1604 getStreamer().EmitDwarfLocDirective(
1605 getContext().getGenDwarfFileNumber(), Line, 0,
1606 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1610 // If parsing succeeded, match the instruction.
1613 HadError = getTargetParser().MatchAndEmitInstruction(
1614 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1618 // Don't skip the rest of the line, the instruction parser is responsible for
1623 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1624 /// since they may not be able to be tokenized to get to the end of line token.
1625 void AsmParser::eatToEndOfLine() {
1626 if (!Lexer.is(AsmToken::EndOfStatement))
1627 Lexer.LexUntilEndOfLine();
1632 /// parseCppHashLineFilenameComment as this:
1633 /// ::= # number "filename"
1634 /// or just as a full line comment if it doesn't have a number and a string.
1635 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1636 Lex(); // Eat the hash token.
1638 if (getLexer().isNot(AsmToken::Integer)) {
1639 // Consume the line since in cases it is not a well-formed line directive,
1640 // as if were simply a full line comment.
1645 int64_t LineNumber = getTok().getIntVal();
1648 if (getLexer().isNot(AsmToken::String)) {
1653 StringRef Filename = getTok().getString();
1654 // Get rid of the enclosing quotes.
1655 Filename = Filename.substr(1, Filename.size() - 2);
1657 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1659 CppHashFilename = Filename;
1660 CppHashLineNumber = LineNumber;
1661 CppHashBuf = CurBuffer;
1663 // Ignore any trailing characters, they're just comment.
1668 /// \brief will use the last parsed cpp hash line filename comment
1669 /// for the Filename and LineNo if any in the diagnostic.
1670 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1671 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1672 raw_ostream &OS = errs();
1674 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1675 const SMLoc &DiagLoc = Diag.getLoc();
1676 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1677 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1679 // Like SourceMgr::printMessage() we need to print the include stack if any
1680 // before printing the message.
1681 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1682 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1683 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1684 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1687 // If we have not parsed a cpp hash line filename comment or the source
1688 // manager changed or buffer changed (like in a nested include) then just
1689 // print the normal diagnostic using its Filename and LineNo.
1690 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1691 DiagBuf != CppHashBuf) {
1692 if (Parser->SavedDiagHandler)
1693 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1699 // Use the CppHashFilename and calculate a line number based on the
1700 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1702 const std::string &Filename = Parser->CppHashFilename;
1704 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1705 int CppHashLocLineNo =
1706 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1708 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1710 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1711 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1712 Diag.getLineContents(), Diag.getRanges());
1714 if (Parser->SavedDiagHandler)
1715 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1717 NewDiag.print(0, OS);
1720 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1721 // difference being that that function accepts '@' as part of identifiers and
1722 // we can't do that. AsmLexer.cpp should probably be changed to handle
1723 // '@' as a special case when needed.
1724 static bool isIdentifierChar(char c) {
1725 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1729 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1730 const MCAsmMacroParameters &Parameters,
1731 const MCAsmMacroArguments &A, const SMLoc &L) {
1732 unsigned NParameters = Parameters.size();
1733 if (NParameters != 0 && NParameters != A.size())
1734 return Error(L, "Wrong number of arguments");
1736 // A macro without parameters is handled differently on Darwin:
1737 // gas accepts no arguments and does no substitutions
1738 while (!Body.empty()) {
1739 // Scan for the next substitution.
1740 std::size_t End = Body.size(), Pos = 0;
1741 for (; Pos != End; ++Pos) {
1742 // Check for a substitution or escape.
1744 // This macro has no parameters, look for $0, $1, etc.
1745 if (Body[Pos] != '$' || Pos + 1 == End)
1748 char Next = Body[Pos + 1];
1749 if (Next == '$' || Next == 'n' ||
1750 isdigit(static_cast<unsigned char>(Next)))
1753 // This macro has parameters, look for \foo, \bar, etc.
1754 if (Body[Pos] == '\\' && Pos + 1 != End)
1760 OS << Body.slice(0, Pos);
1762 // Check if we reached the end.
1767 switch (Body[Pos + 1]) {
1773 // $n => number of arguments
1778 // $[0-9] => argument
1780 // Missing arguments are ignored.
1781 unsigned Index = Body[Pos + 1] - '0';
1782 if (Index >= A.size())
1785 // Otherwise substitute with the token values, with spaces eliminated.
1786 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1787 ie = A[Index].end();
1789 OS << it->getString();
1795 unsigned I = Pos + 1;
1796 while (isIdentifierChar(Body[I]) && I + 1 != End)
1799 const char *Begin = Body.data() + Pos + 1;
1800 StringRef Argument(Begin, I - (Pos + 1));
1802 for (; Index < NParameters; ++Index)
1803 if (Parameters[Index].first == Argument)
1806 if (Index == NParameters) {
1807 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1810 OS << '\\' << Argument;
1814 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1815 ie = A[Index].end();
1817 if (it->getKind() == AsmToken::String)
1818 OS << it->getStringContents();
1820 OS << it->getString();
1822 Pos += 1 + Argument.size();
1825 // Update the scan point.
1826 Body = Body.substr(Pos);
1832 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1833 SMLoc EL, MemoryBuffer *I)
1834 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1837 static bool isOperator(AsmToken::TokenKind kind) {
1841 case AsmToken::Plus:
1842 case AsmToken::Minus:
1843 case AsmToken::Tilde:
1844 case AsmToken::Slash:
1845 case AsmToken::Star:
1847 case AsmToken::Equal:
1848 case AsmToken::EqualEqual:
1849 case AsmToken::Pipe:
1850 case AsmToken::PipePipe:
1851 case AsmToken::Caret:
1853 case AsmToken::AmpAmp:
1854 case AsmToken::Exclaim:
1855 case AsmToken::ExclaimEqual:
1856 case AsmToken::Percent:
1857 case AsmToken::Less:
1858 case AsmToken::LessEqual:
1859 case AsmToken::LessLess:
1860 case AsmToken::LessGreater:
1861 case AsmToken::Greater:
1862 case AsmToken::GreaterEqual:
1863 case AsmToken::GreaterGreater:
1869 class AsmLexerSkipSpaceRAII {
1871 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1872 Lexer.setSkipSpace(SkipSpace);
1875 ~AsmLexerSkipSpaceRAII() {
1876 Lexer.setSkipSpace(true);
1884 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA) {
1885 unsigned ParenLevel = 0;
1886 unsigned AddTokens = 0;
1888 // Darwin doesn't use spaces to delmit arguments.
1889 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1892 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1893 return TokError("unexpected token in macro instantiation");
1895 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1898 if (Lexer.is(AsmToken::Space)) {
1899 Lex(); // Eat spaces
1901 // Spaces can delimit parameters, but could also be part an expression.
1902 // If the token after a space is an operator, add the token and the next
1903 // one into this argument
1905 if (isOperator(Lexer.getKind())) {
1906 // Check to see whether the token is used as an operator,
1907 // or part of an identifier
1908 const char *NextChar = getTok().getEndLoc().getPointer();
1909 if (*NextChar == ' ')
1913 if (!AddTokens && ParenLevel == 0) {
1919 // handleMacroEntry relies on not advancing the lexer here
1920 // to be able to fill in the remaining default parameter values
1921 if (Lexer.is(AsmToken::EndOfStatement))
1924 // Adjust the current parentheses level.
1925 if (Lexer.is(AsmToken::LParen))
1927 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1930 // Append the token to the current argument list.
1931 MA.push_back(getTok());
1937 if (ParenLevel != 0)
1938 return TokError("unbalanced parentheses in macro argument");
1942 // Parse the macro instantiation arguments.
1943 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1944 MCAsmMacroArguments &A) {
1945 const unsigned NParameters = M ? M->Parameters.size() : 0;
1947 // Parse two kinds of macro invocations:
1948 // - macros defined without any parameters accept an arbitrary number of them
1949 // - macros defined with parameters accept at most that many of them
1950 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1952 MCAsmMacroArgument MA;
1954 if (parseMacroArgument(MA))
1957 if (!MA.empty() || (!NParameters && !Lexer.is(AsmToken::EndOfStatement)))
1959 else if (NParameters) {
1960 if (!M->Parameters[Parameter].second.empty())
1961 A.push_back(M->Parameters[Parameter].second);
1966 // At the end of the statement, fill in remaining arguments that have
1967 // default values. If there aren't any, then the next argument is
1968 // required but missing
1969 if (Lexer.is(AsmToken::EndOfStatement)) {
1970 if (NParameters && Parameter < NParameters - 1) {
1976 if (Lexer.is(AsmToken::Comma))
1979 return TokError("Too many arguments");
1982 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
1983 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1984 return (I == MacroMap.end()) ? NULL : I->getValue();
1987 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
1988 MacroMap[Name] = new MCAsmMacro(Macro);
1991 void AsmParser::undefineMacro(StringRef Name) {
1992 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1993 if (I != MacroMap.end()) {
1994 delete I->getValue();
1999 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2000 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2001 // this, although we should protect against infinite loops.
2002 if (ActiveMacros.size() == 20)
2003 return TokError("macros cannot be nested more than 20 levels deep");
2005 MCAsmMacroArguments A;
2006 if (parseMacroArguments(M, A))
2009 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2010 // to hold the macro body with substitutions.
2011 SmallString<256> Buf;
2012 StringRef Body = M->Body;
2013 raw_svector_ostream OS(Buf);
2015 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2018 // We include the .endmacro in the buffer as our cue to exit the macro
2020 OS << ".endmacro\n";
2022 MemoryBuffer *Instantiation =
2023 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2025 // Create the macro instantiation object and add to the current macro
2026 // instantiation stack.
2027 MacroInstantiation *MI = new MacroInstantiation(
2028 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2029 ActiveMacros.push_back(MI);
2031 // Jump to the macro instantiation and prime the lexer.
2032 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2033 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2039 void AsmParser::handleMacroExit() {
2040 // Jump to the EndOfStatement we should return to, and consume it.
2041 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2044 // Pop the instantiation entry.
2045 delete ActiveMacros.back();
2046 ActiveMacros.pop_back();
2049 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2050 switch (Value->getKind()) {
2051 case MCExpr::Binary: {
2052 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2053 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2055 case MCExpr::Target:
2056 case MCExpr::Constant:
2058 case MCExpr::SymbolRef: {
2060 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2062 return isUsedIn(Sym, S.getVariableValue());
2066 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2069 llvm_unreachable("Unknown expr kind!");
2072 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2074 // FIXME: Use better location, we should use proper tokens.
2075 SMLoc EqualLoc = Lexer.getLoc();
2077 const MCExpr *Value;
2078 if (parseExpression(Value))
2081 // Note: we don't count b as used in "a = b". This is to allow
2085 if (Lexer.isNot(AsmToken::EndOfStatement))
2086 return TokError("unexpected token in assignment");
2088 // Error on assignment to '.'.
2090 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2091 "(use '.space' or '.org').)"));
2094 // Eat the end of statement marker.
2097 // Validate that the LHS is allowed to be a variable (either it has not been
2098 // used as a symbol, or it is an absolute symbol).
2099 MCSymbol *Sym = getContext().LookupSymbol(Name);
2101 // Diagnose assignment to a label.
2103 // FIXME: Diagnostics. Note the location of the definition as a label.
2104 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2105 if (isUsedIn(Sym, Value))
2106 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2107 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2108 ; // Allow redefinitions of undefined symbols only used in directives.
2109 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2110 ; // Allow redefinitions of variables that haven't yet been used.
2111 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2112 return Error(EqualLoc, "redefinition of '" + Name + "'");
2113 else if (!Sym->isVariable())
2114 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2115 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2116 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2119 // Don't count these checks as uses.
2120 Sym->setUsed(false);
2122 Sym = getContext().GetOrCreateSymbol(Name);
2124 // FIXME: Handle '.'.
2126 // Do the assignment.
2127 Out.EmitAssignment(Sym, Value);
2129 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2134 /// parseIdentifier:
2137 bool AsmParser::parseIdentifier(StringRef &Res) {
2138 // The assembler has relaxed rules for accepting identifiers, in particular we
2139 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2140 // separate tokens. At this level, we have already lexed so we cannot (currently)
2141 // handle this as a context dependent token, instead we detect adjacent tokens
2142 // and return the combined identifier.
2143 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2144 SMLoc PrefixLoc = getLexer().getLoc();
2146 // Consume the prefix character, and check for a following identifier.
2148 if (Lexer.isNot(AsmToken::Identifier))
2151 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2152 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2155 // Construct the joined identifier and consume the token.
2157 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2162 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2165 Res = getTok().getIdentifier();
2167 Lex(); // Consume the identifier token.
2172 /// parseDirectiveSet:
2173 /// ::= .equ identifier ',' expression
2174 /// ::= .equiv identifier ',' expression
2175 /// ::= .set identifier ',' expression
2176 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2179 if (parseIdentifier(Name))
2180 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2182 if (getLexer().isNot(AsmToken::Comma))
2183 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2186 return parseAssignment(Name, allow_redef, true);
2189 bool AsmParser::parseEscapedString(std::string &Data) {
2190 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2193 StringRef Str = getTok().getStringContents();
2194 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2195 if (Str[i] != '\\') {
2200 // Recognize escaped characters. Note that this escape semantics currently
2201 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2204 return TokError("unexpected backslash at end of string");
2206 // Recognize octal sequences.
2207 if ((unsigned)(Str[i] - '0') <= 7) {
2208 // Consume up to three octal characters.
2209 unsigned Value = Str[i] - '0';
2211 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2213 Value = Value * 8 + (Str[i] - '0');
2215 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2217 Value = Value * 8 + (Str[i] - '0');
2222 return TokError("invalid octal escape sequence (out of range)");
2224 Data += (unsigned char)Value;
2228 // Otherwise recognize individual escapes.
2231 // Just reject invalid escape sequences for now.
2232 return TokError("invalid escape sequence (unrecognized character)");
2234 case 'b': Data += '\b'; break;
2235 case 'f': Data += '\f'; break;
2236 case 'n': Data += '\n'; break;
2237 case 'r': Data += '\r'; break;
2238 case 't': Data += '\t'; break;
2239 case '"': Data += '"'; break;
2240 case '\\': Data += '\\'; break;
2247 /// parseDirectiveAscii:
2248 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2249 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2250 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2251 checkForValidSection();
2254 if (getLexer().isNot(AsmToken::String))
2255 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2258 if (parseEscapedString(Data))
2261 getStreamer().EmitBytes(Data);
2263 getStreamer().EmitBytes(StringRef("\0", 1));
2267 if (getLexer().is(AsmToken::EndOfStatement))
2270 if (getLexer().isNot(AsmToken::Comma))
2271 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2280 /// parseDirectiveValue
2281 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2282 bool AsmParser::parseDirectiveValue(unsigned Size) {
2283 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2284 checkForValidSection();
2287 const MCExpr *Value;
2288 SMLoc ExprLoc = getLexer().getLoc();
2289 if (parseExpression(Value))
2292 // Special case constant expressions to match code generator.
2293 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2294 assert(Size <= 8 && "Invalid size");
2295 uint64_t IntValue = MCE->getValue();
2296 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2297 return Error(ExprLoc, "literal value out of range for directive");
2298 getStreamer().EmitIntValue(IntValue, Size);
2300 getStreamer().EmitValue(Value, Size);
2302 if (getLexer().is(AsmToken::EndOfStatement))
2305 // FIXME: Improve diagnostic.
2306 if (getLexer().isNot(AsmToken::Comma))
2307 return TokError("unexpected token in directive");
2316 /// ParseDirectiveOctaValue
2317 /// ::= .octa [ hexconstant (, hexconstant)* ]
2318 bool AsmParser::parseDirectiveOctaValue() {
2319 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2320 checkForValidSection();
2323 if (Lexer.getKind() == AsmToken::Error)
2325 if (Lexer.getKind() != AsmToken::Integer &&
2326 Lexer.getKind() != AsmToken::BigNum)
2327 return TokError("unknown token in expression");
2329 SMLoc ExprLoc = getLexer().getLoc();
2330 APInt IntValue = getTok().getAPIntVal();
2334 if (IntValue.isIntN(64)) {
2336 lo = IntValue.getZExtValue();
2337 } else if (IntValue.isIntN(128)) {
2338 // It might actually have more than 128 bits, but the top ones are zero.
2339 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2340 lo = IntValue.getLoBits(64).getZExtValue();
2342 return Error(ExprLoc, "literal value out of range for directive");
2344 if (MAI.isLittleEndian()) {
2345 getStreamer().EmitIntValue(lo, 8);
2346 getStreamer().EmitIntValue(hi, 8);
2348 getStreamer().EmitIntValue(hi, 8);
2349 getStreamer().EmitIntValue(lo, 8);
2352 if (getLexer().is(AsmToken::EndOfStatement))
2355 // FIXME: Improve diagnostic.
2356 if (getLexer().isNot(AsmToken::Comma))
2357 return TokError("unexpected token in directive");
2366 /// parseDirectiveRealValue
2367 /// ::= (.single | .double) [ expression (, expression)* ]
2368 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2369 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2370 checkForValidSection();
2373 // We don't truly support arithmetic on floating point expressions, so we
2374 // have to manually parse unary prefixes.
2376 if (getLexer().is(AsmToken::Minus)) {
2379 } else if (getLexer().is(AsmToken::Plus))
2382 if (getLexer().isNot(AsmToken::Integer) &&
2383 getLexer().isNot(AsmToken::Real) &&
2384 getLexer().isNot(AsmToken::Identifier))
2385 return TokError("unexpected token in directive");
2387 // Convert to an APFloat.
2388 APFloat Value(Semantics);
2389 StringRef IDVal = getTok().getString();
2390 if (getLexer().is(AsmToken::Identifier)) {
2391 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2392 Value = APFloat::getInf(Semantics);
2393 else if (!IDVal.compare_lower("nan"))
2394 Value = APFloat::getNaN(Semantics, false, ~0);
2396 return TokError("invalid floating point literal");
2397 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2398 APFloat::opInvalidOp)
2399 return TokError("invalid floating point literal");
2403 // Consume the numeric token.
2406 // Emit the value as an integer.
2407 APInt AsInt = Value.bitcastToAPInt();
2408 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2409 AsInt.getBitWidth() / 8);
2411 if (getLexer().is(AsmToken::EndOfStatement))
2414 if (getLexer().isNot(AsmToken::Comma))
2415 return TokError("unexpected token in directive");
2424 /// parseDirectiveZero
2425 /// ::= .zero expression
2426 bool AsmParser::parseDirectiveZero() {
2427 checkForValidSection();
2430 if (parseAbsoluteExpression(NumBytes))
2434 if (getLexer().is(AsmToken::Comma)) {
2436 if (parseAbsoluteExpression(Val))
2440 if (getLexer().isNot(AsmToken::EndOfStatement))
2441 return TokError("unexpected token in '.zero' directive");
2445 getStreamer().EmitFill(NumBytes, Val);
2450 /// parseDirectiveFill
2451 /// ::= .fill expression [ , expression [ , expression ] ]
2452 bool AsmParser::parseDirectiveFill() {
2453 checkForValidSection();
2455 SMLoc RepeatLoc = getLexer().getLoc();
2457 if (parseAbsoluteExpression(NumValues))
2460 if (NumValues < 0) {
2462 "'.fill' directive with negative repeat count has no effect");
2466 int64_t FillSize = 1;
2467 int64_t FillExpr = 0;
2469 SMLoc SizeLoc, ExprLoc;
2470 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2471 if (getLexer().isNot(AsmToken::Comma))
2472 return TokError("unexpected token in '.fill' directive");
2475 SizeLoc = getLexer().getLoc();
2476 if (parseAbsoluteExpression(FillSize))
2479 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2480 if (getLexer().isNot(AsmToken::Comma))
2481 return TokError("unexpected token in '.fill' directive");
2484 ExprLoc = getLexer().getLoc();
2485 if (parseAbsoluteExpression(FillExpr))
2488 if (getLexer().isNot(AsmToken::EndOfStatement))
2489 return TokError("unexpected token in '.fill' directive");
2496 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2500 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2504 if (!isUInt<32>(FillExpr) && FillSize > 4)
2505 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2507 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2508 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2510 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2511 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2512 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2518 /// parseDirectiveOrg
2519 /// ::= .org expression [ , expression ]
2520 bool AsmParser::parseDirectiveOrg() {
2521 checkForValidSection();
2523 const MCExpr *Offset;
2524 SMLoc Loc = getTok().getLoc();
2525 if (parseExpression(Offset))
2528 // Parse optional fill expression.
2529 int64_t FillExpr = 0;
2530 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2531 if (getLexer().isNot(AsmToken::Comma))
2532 return TokError("unexpected token in '.org' directive");
2535 if (parseAbsoluteExpression(FillExpr))
2538 if (getLexer().isNot(AsmToken::EndOfStatement))
2539 return TokError("unexpected token in '.org' directive");
2544 // Only limited forms of relocatable expressions are accepted here, it
2545 // has to be relative to the current section. The streamer will return
2546 // 'true' if the expression wasn't evaluatable.
2547 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2548 return Error(Loc, "expected assembly-time absolute expression");
2553 /// parseDirectiveAlign
2554 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2555 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2556 checkForValidSection();
2558 SMLoc AlignmentLoc = getLexer().getLoc();
2560 if (parseAbsoluteExpression(Alignment))
2564 bool HasFillExpr = false;
2565 int64_t FillExpr = 0;
2566 int64_t MaxBytesToFill = 0;
2567 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2568 if (getLexer().isNot(AsmToken::Comma))
2569 return TokError("unexpected token in directive");
2572 // The fill expression can be omitted while specifying a maximum number of
2573 // alignment bytes, e.g:
2575 if (getLexer().isNot(AsmToken::Comma)) {
2577 if (parseAbsoluteExpression(FillExpr))
2581 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2582 if (getLexer().isNot(AsmToken::Comma))
2583 return TokError("unexpected token in directive");
2586 MaxBytesLoc = getLexer().getLoc();
2587 if (parseAbsoluteExpression(MaxBytesToFill))
2590 if (getLexer().isNot(AsmToken::EndOfStatement))
2591 return TokError("unexpected token in directive");
2600 // Compute alignment in bytes.
2602 // FIXME: Diagnose overflow.
2603 if (Alignment >= 32) {
2604 Error(AlignmentLoc, "invalid alignment value");
2608 Alignment = 1ULL << Alignment;
2610 // Reject alignments that aren't a power of two, for gas compatibility.
2611 if (!isPowerOf2_64(Alignment))
2612 Error(AlignmentLoc, "alignment must be a power of 2");
2615 // Diagnose non-sensical max bytes to align.
2616 if (MaxBytesLoc.isValid()) {
2617 if (MaxBytesToFill < 1) {
2618 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2619 "many bytes, ignoring maximum bytes expression");
2623 if (MaxBytesToFill >= Alignment) {
2624 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2630 // Check whether we should use optimal code alignment for this .align
2632 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2633 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2634 ValueSize == 1 && UseCodeAlign) {
2635 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2637 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2638 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2645 /// parseDirectiveFile
2646 /// ::= .file [number] filename
2647 /// ::= .file number directory filename
2648 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2649 // FIXME: I'm not sure what this is.
2650 int64_t FileNumber = -1;
2651 SMLoc FileNumberLoc = getLexer().getLoc();
2652 if (getLexer().is(AsmToken::Integer)) {
2653 FileNumber = getTok().getIntVal();
2657 return TokError("file number less than one");
2660 if (getLexer().isNot(AsmToken::String))
2661 return TokError("unexpected token in '.file' directive");
2663 // Usually the directory and filename together, otherwise just the directory.
2664 // Allow the strings to have escaped octal character sequence.
2665 std::string Path = getTok().getString();
2666 if (parseEscapedString(Path))
2670 StringRef Directory;
2672 std::string FilenameData;
2673 if (getLexer().is(AsmToken::String)) {
2674 if (FileNumber == -1)
2675 return TokError("explicit path specified, but no file number");
2676 if (parseEscapedString(FilenameData))
2678 Filename = FilenameData;
2685 if (getLexer().isNot(AsmToken::EndOfStatement))
2686 return TokError("unexpected token in '.file' directive");
2688 if (FileNumber == -1)
2689 getStreamer().EmitFileDirective(Filename);
2691 if (getContext().getGenDwarfForAssembly() == true)
2693 "input can't have .file dwarf directives when -g is "
2694 "used to generate dwarf debug info for assembly code");
2696 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2697 Error(FileNumberLoc, "file number already allocated");
2703 /// parseDirectiveLine
2704 /// ::= .line [number]
2705 bool AsmParser::parseDirectiveLine() {
2706 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2707 if (getLexer().isNot(AsmToken::Integer))
2708 return TokError("unexpected token in '.line' directive");
2710 int64_t LineNumber = getTok().getIntVal();
2714 // FIXME: Do something with the .line.
2717 if (getLexer().isNot(AsmToken::EndOfStatement))
2718 return TokError("unexpected token in '.line' directive");
2723 /// parseDirectiveLoc
2724 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2725 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2726 /// The first number is a file number, must have been previously assigned with
2727 /// a .file directive, the second number is the line number and optionally the
2728 /// third number is a column position (zero if not specified). The remaining
2729 /// optional items are .loc sub-directives.
2730 bool AsmParser::parseDirectiveLoc() {
2731 if (getLexer().isNot(AsmToken::Integer))
2732 return TokError("unexpected token in '.loc' directive");
2733 int64_t FileNumber = getTok().getIntVal();
2735 return TokError("file number less than one in '.loc' directive");
2736 if (!getContext().isValidDwarfFileNumber(FileNumber))
2737 return TokError("unassigned file number in '.loc' directive");
2740 int64_t LineNumber = 0;
2741 if (getLexer().is(AsmToken::Integer)) {
2742 LineNumber = getTok().getIntVal();
2744 return TokError("line number less than zero in '.loc' directive");
2748 int64_t ColumnPos = 0;
2749 if (getLexer().is(AsmToken::Integer)) {
2750 ColumnPos = getTok().getIntVal();
2752 return TokError("column position less than zero in '.loc' directive");
2756 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2758 int64_t Discriminator = 0;
2759 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2761 if (getLexer().is(AsmToken::EndOfStatement))
2765 SMLoc Loc = getTok().getLoc();
2766 if (parseIdentifier(Name))
2767 return TokError("unexpected token in '.loc' directive");
2769 if (Name == "basic_block")
2770 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2771 else if (Name == "prologue_end")
2772 Flags |= DWARF2_FLAG_PROLOGUE_END;
2773 else if (Name == "epilogue_begin")
2774 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2775 else if (Name == "is_stmt") {
2776 Loc = getTok().getLoc();
2777 const MCExpr *Value;
2778 if (parseExpression(Value))
2780 // The expression must be the constant 0 or 1.
2781 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2782 int Value = MCE->getValue();
2784 Flags &= ~DWARF2_FLAG_IS_STMT;
2785 else if (Value == 1)
2786 Flags |= DWARF2_FLAG_IS_STMT;
2788 return Error(Loc, "is_stmt value not 0 or 1");
2790 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2792 } else if (Name == "isa") {
2793 Loc = getTok().getLoc();
2794 const MCExpr *Value;
2795 if (parseExpression(Value))
2797 // The expression must be a constant greater or equal to 0.
2798 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2799 int Value = MCE->getValue();
2801 return Error(Loc, "isa number less than zero");
2804 return Error(Loc, "isa number not a constant value");
2806 } else if (Name == "discriminator") {
2807 if (parseAbsoluteExpression(Discriminator))
2810 return Error(Loc, "unknown sub-directive in '.loc' directive");
2813 if (getLexer().is(AsmToken::EndOfStatement))
2818 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2819 Isa, Discriminator, StringRef());
2824 /// parseDirectiveStabs
2825 /// ::= .stabs string, number, number, number
2826 bool AsmParser::parseDirectiveStabs() {
2827 return TokError("unsupported directive '.stabs'");
2830 /// parseDirectiveCFISections
2831 /// ::= .cfi_sections section [, section]
2832 bool AsmParser::parseDirectiveCFISections() {
2837 if (parseIdentifier(Name))
2838 return TokError("Expected an identifier");
2840 if (Name == ".eh_frame")
2842 else if (Name == ".debug_frame")
2845 if (getLexer().is(AsmToken::Comma)) {
2848 if (parseIdentifier(Name))
2849 return TokError("Expected an identifier");
2851 if (Name == ".eh_frame")
2853 else if (Name == ".debug_frame")
2857 getStreamer().EmitCFISections(EH, Debug);
2861 /// parseDirectiveCFIStartProc
2862 /// ::= .cfi_startproc [simple]
2863 bool AsmParser::parseDirectiveCFIStartProc() {
2865 if (getLexer().isNot(AsmToken::EndOfStatement))
2866 if (parseIdentifier(Simple) || Simple != "simple")
2867 return TokError("unexpected token in .cfi_startproc directive");
2869 getStreamer().EmitCFIStartProc(!Simple.empty());
2873 /// parseDirectiveCFIEndProc
2874 /// ::= .cfi_endproc
2875 bool AsmParser::parseDirectiveCFIEndProc() {
2876 getStreamer().EmitCFIEndProc();
2880 /// \brief parse register name or number.
2881 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2882 SMLoc DirectiveLoc) {
2885 if (getLexer().isNot(AsmToken::Integer)) {
2886 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2888 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2890 return parseAbsoluteExpression(Register);
2895 /// parseDirectiveCFIDefCfa
2896 /// ::= .cfi_def_cfa register, offset
2897 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2898 int64_t Register = 0;
2899 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2902 if (getLexer().isNot(AsmToken::Comma))
2903 return TokError("unexpected token in directive");
2907 if (parseAbsoluteExpression(Offset))
2910 getStreamer().EmitCFIDefCfa(Register, Offset);
2914 /// parseDirectiveCFIDefCfaOffset
2915 /// ::= .cfi_def_cfa_offset offset
2916 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2918 if (parseAbsoluteExpression(Offset))
2921 getStreamer().EmitCFIDefCfaOffset(Offset);
2925 /// parseDirectiveCFIRegister
2926 /// ::= .cfi_register register, register
2927 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2928 int64_t Register1 = 0;
2929 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2932 if (getLexer().isNot(AsmToken::Comma))
2933 return TokError("unexpected token in directive");
2936 int64_t Register2 = 0;
2937 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2940 getStreamer().EmitCFIRegister(Register1, Register2);
2944 /// parseDirectiveCFIWindowSave
2945 /// ::= .cfi_window_save
2946 bool AsmParser::parseDirectiveCFIWindowSave() {
2947 getStreamer().EmitCFIWindowSave();
2951 /// parseDirectiveCFIAdjustCfaOffset
2952 /// ::= .cfi_adjust_cfa_offset adjustment
2953 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2954 int64_t Adjustment = 0;
2955 if (parseAbsoluteExpression(Adjustment))
2958 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2962 /// parseDirectiveCFIDefCfaRegister
2963 /// ::= .cfi_def_cfa_register register
2964 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2965 int64_t Register = 0;
2966 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2969 getStreamer().EmitCFIDefCfaRegister(Register);
2973 /// parseDirectiveCFIOffset
2974 /// ::= .cfi_offset register, offset
2975 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2976 int64_t Register = 0;
2979 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2982 if (getLexer().isNot(AsmToken::Comma))
2983 return TokError("unexpected token in directive");
2986 if (parseAbsoluteExpression(Offset))
2989 getStreamer().EmitCFIOffset(Register, Offset);
2993 /// parseDirectiveCFIRelOffset
2994 /// ::= .cfi_rel_offset register, offset
2995 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2996 int64_t Register = 0;
2998 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3001 if (getLexer().isNot(AsmToken::Comma))
3002 return TokError("unexpected token in directive");
3006 if (parseAbsoluteExpression(Offset))
3009 getStreamer().EmitCFIRelOffset(Register, Offset);
3013 static bool isValidEncoding(int64_t Encoding) {
3014 if (Encoding & ~0xff)
3017 if (Encoding == dwarf::DW_EH_PE_omit)
3020 const unsigned Format = Encoding & 0xf;
3021 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3022 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3023 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3024 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3027 const unsigned Application = Encoding & 0x70;
3028 if (Application != dwarf::DW_EH_PE_absptr &&
3029 Application != dwarf::DW_EH_PE_pcrel)
3035 /// parseDirectiveCFIPersonalityOrLsda
3036 /// IsPersonality true for cfi_personality, false for cfi_lsda
3037 /// ::= .cfi_personality encoding, [symbol_name]
3038 /// ::= .cfi_lsda encoding, [symbol_name]
3039 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3040 int64_t Encoding = 0;
3041 if (parseAbsoluteExpression(Encoding))
3043 if (Encoding == dwarf::DW_EH_PE_omit)
3046 if (!isValidEncoding(Encoding))
3047 return TokError("unsupported encoding.");
3049 if (getLexer().isNot(AsmToken::Comma))
3050 return TokError("unexpected token in directive");
3054 if (parseIdentifier(Name))
3055 return TokError("expected identifier in directive");
3057 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3060 getStreamer().EmitCFIPersonality(Sym, Encoding);
3062 getStreamer().EmitCFILsda(Sym, Encoding);
3066 /// parseDirectiveCFIRememberState
3067 /// ::= .cfi_remember_state
3068 bool AsmParser::parseDirectiveCFIRememberState() {
3069 getStreamer().EmitCFIRememberState();
3073 /// parseDirectiveCFIRestoreState
3074 /// ::= .cfi_remember_state
3075 bool AsmParser::parseDirectiveCFIRestoreState() {
3076 getStreamer().EmitCFIRestoreState();
3080 /// parseDirectiveCFISameValue
3081 /// ::= .cfi_same_value register
3082 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3083 int64_t Register = 0;
3085 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3088 getStreamer().EmitCFISameValue(Register);
3092 /// parseDirectiveCFIRestore
3093 /// ::= .cfi_restore register
3094 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3095 int64_t Register = 0;
3096 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3099 getStreamer().EmitCFIRestore(Register);
3103 /// parseDirectiveCFIEscape
3104 /// ::= .cfi_escape expression[,...]
3105 bool AsmParser::parseDirectiveCFIEscape() {
3108 if (parseAbsoluteExpression(CurrValue))
3111 Values.push_back((uint8_t)CurrValue);
3113 while (getLexer().is(AsmToken::Comma)) {
3116 if (parseAbsoluteExpression(CurrValue))
3119 Values.push_back((uint8_t)CurrValue);
3122 getStreamer().EmitCFIEscape(Values);
3126 /// parseDirectiveCFISignalFrame
3127 /// ::= .cfi_signal_frame
3128 bool AsmParser::parseDirectiveCFISignalFrame() {
3129 if (getLexer().isNot(AsmToken::EndOfStatement))
3130 return Error(getLexer().getLoc(),
3131 "unexpected token in '.cfi_signal_frame'");
3133 getStreamer().EmitCFISignalFrame();
3137 /// parseDirectiveCFIUndefined
3138 /// ::= .cfi_undefined register
3139 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3140 int64_t Register = 0;
3142 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3145 getStreamer().EmitCFIUndefined(Register);
3149 /// parseDirectiveMacrosOnOff
3152 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3153 if (getLexer().isNot(AsmToken::EndOfStatement))
3154 return Error(getLexer().getLoc(),
3155 "unexpected token in '" + Directive + "' directive");
3157 setMacrosEnabled(Directive == ".macros_on");
3161 /// parseDirectiveMacro
3162 /// ::= .macro name [parameters]
3163 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3165 if (parseIdentifier(Name))
3166 return TokError("expected identifier in '.macro' directive");
3168 MCAsmMacroParameters Parameters;
3169 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3170 MCAsmMacroParameter Parameter;
3171 if (parseIdentifier(Parameter.first))
3172 return TokError("expected identifier in '.macro' directive");
3174 if (getLexer().is(AsmToken::Equal)) {
3176 if (parseMacroArgument(Parameter.second))
3180 Parameters.push_back(Parameter);
3182 if (getLexer().is(AsmToken::Comma))
3186 // Eat the end of statement.
3189 AsmToken EndToken, StartToken = getTok();
3191 // Lex the macro definition.
3193 // Check whether we have reached the end of the file.
3194 if (getLexer().is(AsmToken::Eof))
3195 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3197 // Otherwise, check whether we have reach the .endmacro.
3198 if (getLexer().is(AsmToken::Identifier) &&
3199 (getTok().getIdentifier() == ".endm" ||
3200 getTok().getIdentifier() == ".endmacro")) {
3201 EndToken = getTok();
3203 if (getLexer().isNot(AsmToken::EndOfStatement))
3204 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3209 // Otherwise, scan til the end of the statement.
3210 eatToEndOfStatement();
3213 if (lookupMacro(Name)) {
3214 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3217 const char *BodyStart = StartToken.getLoc().getPointer();
3218 const char *BodyEnd = EndToken.getLoc().getPointer();
3219 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3220 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3221 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3225 /// checkForBadMacro
3227 /// With the support added for named parameters there may be code out there that
3228 /// is transitioning from positional parameters. In versions of gas that did
3229 /// not support named parameters they would be ignored on the macro definition.
3230 /// But to support both styles of parameters this is not possible so if a macro
3231 /// definition has named parameters but does not use them and has what appears
3232 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3233 /// warning that the positional parameter found in body which have no effect.
3234 /// Hoping the developer will either remove the named parameters from the macro
3235 /// definition so the positional parameters get used if that was what was
3236 /// intended or change the macro to use the named parameters. It is possible
3237 /// this warning will trigger when the none of the named parameters are used
3238 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3239 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3241 MCAsmMacroParameters Parameters) {
3242 // If this macro is not defined with named parameters the warning we are
3243 // checking for here doesn't apply.
3244 unsigned NParameters = Parameters.size();
3245 if (NParameters == 0)
3248 bool NamedParametersFound = false;
3249 bool PositionalParametersFound = false;
3251 // Look at the body of the macro for use of both the named parameters and what
3252 // are likely to be positional parameters. This is what expandMacro() is
3253 // doing when it finds the parameters in the body.
3254 while (!Body.empty()) {
3255 // Scan for the next possible parameter.
3256 std::size_t End = Body.size(), Pos = 0;
3257 for (; Pos != End; ++Pos) {
3258 // Check for a substitution or escape.
3259 // This macro is defined with parameters, look for \foo, \bar, etc.
3260 if (Body[Pos] == '\\' && Pos + 1 != End)
3263 // This macro should have parameters, but look for $0, $1, ..., $n too.
3264 if (Body[Pos] != '$' || Pos + 1 == End)
3266 char Next = Body[Pos + 1];
3267 if (Next == '$' || Next == 'n' ||
3268 isdigit(static_cast<unsigned char>(Next)))
3272 // Check if we reached the end.
3276 if (Body[Pos] == '$') {
3277 switch (Body[Pos + 1]) {
3282 // $n => number of arguments
3284 PositionalParametersFound = true;
3287 // $[0-9] => argument
3289 PositionalParametersFound = true;
3295 unsigned I = Pos + 1;
3296 while (isIdentifierChar(Body[I]) && I + 1 != End)
3299 const char *Begin = Body.data() + Pos + 1;
3300 StringRef Argument(Begin, I - (Pos + 1));
3302 for (; Index < NParameters; ++Index)
3303 if (Parameters[Index].first == Argument)
3306 if (Index == NParameters) {
3307 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3313 NamedParametersFound = true;
3314 Pos += 1 + Argument.size();
3317 // Update the scan point.
3318 Body = Body.substr(Pos);
3321 if (!NamedParametersFound && PositionalParametersFound)
3322 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3323 "used in macro body, possible positional parameter "
3324 "found in body which will have no effect");
3327 /// parseDirectiveEndMacro
3330 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3331 if (getLexer().isNot(AsmToken::EndOfStatement))
3332 return TokError("unexpected token in '" + Directive + "' directive");
3334 // If we are inside a macro instantiation, terminate the current
3336 if (isInsideMacroInstantiation()) {
3341 // Otherwise, this .endmacro is a stray entry in the file; well formed
3342 // .endmacro directives are handled during the macro definition parsing.
3343 return TokError("unexpected '" + Directive + "' in file, "
3344 "no current macro definition");
3347 /// parseDirectivePurgeMacro
3349 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3351 if (parseIdentifier(Name))
3352 return TokError("expected identifier in '.purgem' directive");
3354 if (getLexer().isNot(AsmToken::EndOfStatement))
3355 return TokError("unexpected token in '.purgem' directive");
3357 if (!lookupMacro(Name))
3358 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3360 undefineMacro(Name);
3364 /// parseDirectiveBundleAlignMode
3365 /// ::= {.bundle_align_mode} expression
3366 bool AsmParser::parseDirectiveBundleAlignMode() {
3367 checkForValidSection();
3369 // Expect a single argument: an expression that evaluates to a constant
3370 // in the inclusive range 0-30.
3371 SMLoc ExprLoc = getLexer().getLoc();
3372 int64_t AlignSizePow2;
3373 if (parseAbsoluteExpression(AlignSizePow2))
3375 else if (getLexer().isNot(AsmToken::EndOfStatement))
3376 return TokError("unexpected token after expression in"
3377 " '.bundle_align_mode' directive");
3378 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3379 return Error(ExprLoc,
3380 "invalid bundle alignment size (expected between 0 and 30)");
3384 // Because of AlignSizePow2's verified range we can safely truncate it to
3386 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3390 /// parseDirectiveBundleLock
3391 /// ::= {.bundle_lock} [align_to_end]
3392 bool AsmParser::parseDirectiveBundleLock() {
3393 checkForValidSection();
3394 bool AlignToEnd = false;
3396 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3398 SMLoc Loc = getTok().getLoc();
3399 const char *kInvalidOptionError =
3400 "invalid option for '.bundle_lock' directive";
3402 if (parseIdentifier(Option))
3403 return Error(Loc, kInvalidOptionError);
3405 if (Option != "align_to_end")
3406 return Error(Loc, kInvalidOptionError);
3407 else if (getLexer().isNot(AsmToken::EndOfStatement))
3409 "unexpected token after '.bundle_lock' directive option");
3415 getStreamer().EmitBundleLock(AlignToEnd);
3419 /// parseDirectiveBundleLock
3420 /// ::= {.bundle_lock}
3421 bool AsmParser::parseDirectiveBundleUnlock() {
3422 checkForValidSection();
3424 if (getLexer().isNot(AsmToken::EndOfStatement))
3425 return TokError("unexpected token in '.bundle_unlock' directive");
3428 getStreamer().EmitBundleUnlock();
3432 /// parseDirectiveSpace
3433 /// ::= (.skip | .space) expression [ , expression ]
3434 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3435 checkForValidSection();
3438 if (parseAbsoluteExpression(NumBytes))
3441 int64_t FillExpr = 0;
3442 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3443 if (getLexer().isNot(AsmToken::Comma))
3444 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3447 if (parseAbsoluteExpression(FillExpr))
3450 if (getLexer().isNot(AsmToken::EndOfStatement))
3451 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3457 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3460 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3461 getStreamer().EmitFill(NumBytes, FillExpr);
3466 /// parseDirectiveLEB128
3467 /// ::= (.sleb128 | .uleb128) expression
3468 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3469 checkForValidSection();
3470 const MCExpr *Value;
3472 if (parseExpression(Value))
3475 if (getLexer().isNot(AsmToken::EndOfStatement))
3476 return TokError("unexpected token in directive");
3479 getStreamer().EmitSLEB128Value(Value);
3481 getStreamer().EmitULEB128Value(Value);
3486 /// parseDirectiveSymbolAttribute
3487 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3488 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3489 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3492 SMLoc Loc = getTok().getLoc();
3494 if (parseIdentifier(Name))
3495 return Error(Loc, "expected identifier in directive");
3497 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3499 // Assembler local symbols don't make any sense here. Complain loudly.
3500 if (Sym->isTemporary())
3501 return Error(Loc, "non-local symbol required in directive");
3503 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3504 return Error(Loc, "unable to emit symbol attribute");
3506 if (getLexer().is(AsmToken::EndOfStatement))
3509 if (getLexer().isNot(AsmToken::Comma))
3510 return TokError("unexpected token in directive");
3519 /// parseDirectiveComm
3520 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3521 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3522 checkForValidSection();
3524 SMLoc IDLoc = getLexer().getLoc();
3526 if (parseIdentifier(Name))
3527 return TokError("expected identifier in directive");
3529 // Handle the identifier as the key symbol.
3530 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3532 if (getLexer().isNot(AsmToken::Comma))
3533 return TokError("unexpected token in directive");
3537 SMLoc SizeLoc = getLexer().getLoc();
3538 if (parseAbsoluteExpression(Size))
3541 int64_t Pow2Alignment = 0;
3542 SMLoc Pow2AlignmentLoc;
3543 if (getLexer().is(AsmToken::Comma)) {
3545 Pow2AlignmentLoc = getLexer().getLoc();
3546 if (parseAbsoluteExpression(Pow2Alignment))
3549 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3550 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3551 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3553 // If this target takes alignments in bytes (not log) validate and convert.
3554 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3555 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3556 if (!isPowerOf2_64(Pow2Alignment))
3557 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3558 Pow2Alignment = Log2_64(Pow2Alignment);
3562 if (getLexer().isNot(AsmToken::EndOfStatement))
3563 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3567 // NOTE: a size of zero for a .comm should create a undefined symbol
3568 // but a size of .lcomm creates a bss symbol of size zero.
3570 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3571 "be less than zero");
3573 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3574 // may internally end up wanting an alignment in bytes.
3575 // FIXME: Diagnose overflow.
3576 if (Pow2Alignment < 0)
3577 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3578 "alignment, can't be less than zero");
3580 if (!Sym->isUndefined())
3581 return Error(IDLoc, "invalid symbol redefinition");
3583 // Create the Symbol as a common or local common with Size and Pow2Alignment
3585 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3589 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3593 /// parseDirectiveAbort
3594 /// ::= .abort [... message ...]
3595 bool AsmParser::parseDirectiveAbort() {
3596 // FIXME: Use loc from directive.
3597 SMLoc Loc = getLexer().getLoc();
3599 StringRef Str = parseStringToEndOfStatement();
3600 if (getLexer().isNot(AsmToken::EndOfStatement))
3601 return TokError("unexpected token in '.abort' directive");
3606 Error(Loc, ".abort detected. Assembly stopping.");
3608 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3609 // FIXME: Actually abort assembly here.
3614 /// parseDirectiveInclude
3615 /// ::= .include "filename"
3616 bool AsmParser::parseDirectiveInclude() {
3617 if (getLexer().isNot(AsmToken::String))
3618 return TokError("expected string in '.include' directive");
3620 // Allow the strings to have escaped octal character sequence.
3621 std::string Filename;
3622 if (parseEscapedString(Filename))
3624 SMLoc IncludeLoc = getLexer().getLoc();
3627 if (getLexer().isNot(AsmToken::EndOfStatement))
3628 return TokError("unexpected token in '.include' directive");
3630 // Attempt to switch the lexer to the included file before consuming the end
3631 // of statement to avoid losing it when we switch.
3632 if (enterIncludeFile(Filename)) {
3633 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3640 /// parseDirectiveIncbin
3641 /// ::= .incbin "filename"
3642 bool AsmParser::parseDirectiveIncbin() {
3643 if (getLexer().isNot(AsmToken::String))
3644 return TokError("expected string in '.incbin' directive");
3646 // Allow the strings to have escaped octal character sequence.
3647 std::string Filename;
3648 if (parseEscapedString(Filename))
3650 SMLoc IncbinLoc = getLexer().getLoc();
3653 if (getLexer().isNot(AsmToken::EndOfStatement))
3654 return TokError("unexpected token in '.incbin' directive");
3656 // Attempt to process the included file.
3657 if (processIncbinFile(Filename)) {
3658 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3665 /// parseDirectiveIf
3666 /// ::= .if expression
3667 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3668 TheCondStack.push_back(TheCondState);
3669 TheCondState.TheCond = AsmCond::IfCond;
3670 if (TheCondState.Ignore) {
3671 eatToEndOfStatement();
3674 if (parseAbsoluteExpression(ExprValue))
3677 if (getLexer().isNot(AsmToken::EndOfStatement))
3678 return TokError("unexpected token in '.if' directive");
3682 TheCondState.CondMet = ExprValue;
3683 TheCondState.Ignore = !TheCondState.CondMet;
3689 /// parseDirectiveIfb
3691 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3692 TheCondStack.push_back(TheCondState);
3693 TheCondState.TheCond = AsmCond::IfCond;
3695 if (TheCondState.Ignore) {
3696 eatToEndOfStatement();
3698 StringRef Str = parseStringToEndOfStatement();
3700 if (getLexer().isNot(AsmToken::EndOfStatement))
3701 return TokError("unexpected token in '.ifb' directive");
3705 TheCondState.CondMet = ExpectBlank == Str.empty();
3706 TheCondState.Ignore = !TheCondState.CondMet;
3712 /// parseDirectiveIfc
3713 /// ::= .ifc string1, string2
3714 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3715 TheCondStack.push_back(TheCondState);
3716 TheCondState.TheCond = AsmCond::IfCond;
3718 if (TheCondState.Ignore) {
3719 eatToEndOfStatement();
3721 StringRef Str1 = parseStringToComma();
3723 if (getLexer().isNot(AsmToken::Comma))
3724 return TokError("unexpected token in '.ifc' directive");
3728 StringRef Str2 = parseStringToEndOfStatement();
3730 if (getLexer().isNot(AsmToken::EndOfStatement))
3731 return TokError("unexpected token in '.ifc' directive");
3735 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3736 TheCondState.Ignore = !TheCondState.CondMet;
3742 /// parseDirectiveIfdef
3743 /// ::= .ifdef symbol
3744 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3746 TheCondStack.push_back(TheCondState);
3747 TheCondState.TheCond = AsmCond::IfCond;
3749 if (TheCondState.Ignore) {
3750 eatToEndOfStatement();
3752 if (parseIdentifier(Name))
3753 return TokError("expected identifier after '.ifdef'");
3757 MCSymbol *Sym = getContext().LookupSymbol(Name);
3760 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3762 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3763 TheCondState.Ignore = !TheCondState.CondMet;
3769 /// parseDirectiveElseIf
3770 /// ::= .elseif expression
3771 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3772 if (TheCondState.TheCond != AsmCond::IfCond &&
3773 TheCondState.TheCond != AsmCond::ElseIfCond)
3774 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3776 TheCondState.TheCond = AsmCond::ElseIfCond;
3778 bool LastIgnoreState = false;
3779 if (!TheCondStack.empty())
3780 LastIgnoreState = TheCondStack.back().Ignore;
3781 if (LastIgnoreState || TheCondState.CondMet) {
3782 TheCondState.Ignore = true;
3783 eatToEndOfStatement();
3786 if (parseAbsoluteExpression(ExprValue))
3789 if (getLexer().isNot(AsmToken::EndOfStatement))
3790 return TokError("unexpected token in '.elseif' directive");
3793 TheCondState.CondMet = ExprValue;
3794 TheCondState.Ignore = !TheCondState.CondMet;
3800 /// parseDirectiveElse
3802 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3803 if (getLexer().isNot(AsmToken::EndOfStatement))
3804 return TokError("unexpected token in '.else' directive");
3808 if (TheCondState.TheCond != AsmCond::IfCond &&
3809 TheCondState.TheCond != AsmCond::ElseIfCond)
3810 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3812 TheCondState.TheCond = AsmCond::ElseCond;
3813 bool LastIgnoreState = false;
3814 if (!TheCondStack.empty())
3815 LastIgnoreState = TheCondStack.back().Ignore;
3816 if (LastIgnoreState || TheCondState.CondMet)
3817 TheCondState.Ignore = true;
3819 TheCondState.Ignore = false;
3824 /// parseDirectiveEnd
3826 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3827 if (getLexer().isNot(AsmToken::EndOfStatement))
3828 return TokError("unexpected token in '.end' directive");
3832 while (Lexer.isNot(AsmToken::Eof))
3838 /// parseDirectiveEndIf
3840 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3841 if (getLexer().isNot(AsmToken::EndOfStatement))
3842 return TokError("unexpected token in '.endif' directive");
3846 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3847 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3849 if (!TheCondStack.empty()) {
3850 TheCondState = TheCondStack.back();
3851 TheCondStack.pop_back();
3857 void AsmParser::initializeDirectiveKindMap() {
3858 DirectiveKindMap[".set"] = DK_SET;
3859 DirectiveKindMap[".equ"] = DK_EQU;
3860 DirectiveKindMap[".equiv"] = DK_EQUIV;
3861 DirectiveKindMap[".ascii"] = DK_ASCII;
3862 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3863 DirectiveKindMap[".string"] = DK_STRING;
3864 DirectiveKindMap[".byte"] = DK_BYTE;
3865 DirectiveKindMap[".short"] = DK_SHORT;
3866 DirectiveKindMap[".value"] = DK_VALUE;
3867 DirectiveKindMap[".2byte"] = DK_2BYTE;
3868 DirectiveKindMap[".long"] = DK_LONG;
3869 DirectiveKindMap[".int"] = DK_INT;
3870 DirectiveKindMap[".4byte"] = DK_4BYTE;
3871 DirectiveKindMap[".quad"] = DK_QUAD;
3872 DirectiveKindMap[".8byte"] = DK_8BYTE;
3873 DirectiveKindMap[".octa"] = DK_OCTA;
3874 DirectiveKindMap[".single"] = DK_SINGLE;
3875 DirectiveKindMap[".float"] = DK_FLOAT;
3876 DirectiveKindMap[".double"] = DK_DOUBLE;
3877 DirectiveKindMap[".align"] = DK_ALIGN;
3878 DirectiveKindMap[".align32"] = DK_ALIGN32;
3879 DirectiveKindMap[".balign"] = DK_BALIGN;
3880 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3881 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3882 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3883 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3884 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3885 DirectiveKindMap[".org"] = DK_ORG;
3886 DirectiveKindMap[".fill"] = DK_FILL;
3887 DirectiveKindMap[".zero"] = DK_ZERO;
3888 DirectiveKindMap[".extern"] = DK_EXTERN;
3889 DirectiveKindMap[".globl"] = DK_GLOBL;
3890 DirectiveKindMap[".global"] = DK_GLOBAL;
3891 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3892 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3893 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3894 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3895 DirectiveKindMap[".reference"] = DK_REFERENCE;
3896 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3897 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3898 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3899 DirectiveKindMap[".comm"] = DK_COMM;
3900 DirectiveKindMap[".common"] = DK_COMMON;
3901 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3902 DirectiveKindMap[".abort"] = DK_ABORT;
3903 DirectiveKindMap[".include"] = DK_INCLUDE;
3904 DirectiveKindMap[".incbin"] = DK_INCBIN;
3905 DirectiveKindMap[".code16"] = DK_CODE16;
3906 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3907 DirectiveKindMap[".rept"] = DK_REPT;
3908 DirectiveKindMap[".rep"] = DK_REPT;
3909 DirectiveKindMap[".irp"] = DK_IRP;
3910 DirectiveKindMap[".irpc"] = DK_IRPC;
3911 DirectiveKindMap[".endr"] = DK_ENDR;
3912 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3913 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3914 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3915 DirectiveKindMap[".if"] = DK_IF;
3916 DirectiveKindMap[".ifb"] = DK_IFB;
3917 DirectiveKindMap[".ifnb"] = DK_IFNB;
3918 DirectiveKindMap[".ifc"] = DK_IFC;
3919 DirectiveKindMap[".ifnc"] = DK_IFNC;
3920 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3921 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3922 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3923 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3924 DirectiveKindMap[".else"] = DK_ELSE;
3925 DirectiveKindMap[".end"] = DK_END;
3926 DirectiveKindMap[".endif"] = DK_ENDIF;
3927 DirectiveKindMap[".skip"] = DK_SKIP;
3928 DirectiveKindMap[".space"] = DK_SPACE;
3929 DirectiveKindMap[".file"] = DK_FILE;
3930 DirectiveKindMap[".line"] = DK_LINE;
3931 DirectiveKindMap[".loc"] = DK_LOC;
3932 DirectiveKindMap[".stabs"] = DK_STABS;
3933 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3934 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3935 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3936 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3937 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3938 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3939 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3940 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3941 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3942 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3943 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3944 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3945 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3946 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3947 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3948 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3949 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3950 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3951 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3952 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3953 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3954 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
3955 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3956 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3957 DirectiveKindMap[".macro"] = DK_MACRO;
3958 DirectiveKindMap[".endm"] = DK_ENDM;
3959 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3960 DirectiveKindMap[".purgem"] = DK_PURGEM;
3963 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
3964 AsmToken EndToken, StartToken = getTok();
3966 unsigned NestLevel = 0;
3968 // Check whether we have reached the end of the file.
3969 if (getLexer().is(AsmToken::Eof)) {
3970 Error(DirectiveLoc, "no matching '.endr' in definition");
3974 if (Lexer.is(AsmToken::Identifier) &&
3975 (getTok().getIdentifier() == ".rept")) {
3979 // Otherwise, check whether we have reached the .endr.
3980 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
3981 if (NestLevel == 0) {
3982 EndToken = getTok();
3984 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3985 TokError("unexpected token in '.endr' directive");
3993 // Otherwise, scan till the end of the statement.
3994 eatToEndOfStatement();
3997 const char *BodyStart = StartToken.getLoc().getPointer();
3998 const char *BodyEnd = EndToken.getLoc().getPointer();
3999 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4001 // We Are Anonymous.
4003 MCAsmMacroParameters Parameters;
4004 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
4005 return &MacroLikeBodies.back();
4008 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4009 raw_svector_ostream &OS) {
4012 MemoryBuffer *Instantiation =
4013 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4015 // Create the macro instantiation object and add to the current macro
4016 // instantiation stack.
4017 MacroInstantiation *MI = new MacroInstantiation(
4018 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4019 ActiveMacros.push_back(MI);
4021 // Jump to the macro instantiation and prime the lexer.
4022 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4023 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4027 /// parseDirectiveRept
4028 /// ::= .rep | .rept count
4029 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4030 const MCExpr *CountExpr;
4031 SMLoc CountLoc = getTok().getLoc();
4032 if (parseExpression(CountExpr))
4036 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4037 eatToEndOfStatement();
4038 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4042 return Error(CountLoc, "Count is negative");
4044 if (Lexer.isNot(AsmToken::EndOfStatement))
4045 return TokError("unexpected token in '" + Dir + "' directive");
4047 // Eat the end of statement.
4050 // Lex the rept definition.
4051 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4055 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4056 // to hold the macro body with substitutions.
4057 SmallString<256> Buf;
4058 MCAsmMacroParameters Parameters;
4059 MCAsmMacroArguments A;
4060 raw_svector_ostream OS(Buf);
4062 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
4065 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4070 /// parseDirectiveIrp
4071 /// ::= .irp symbol,values
4072 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4073 MCAsmMacroParameters Parameters;
4074 MCAsmMacroParameter Parameter;
4076 if (parseIdentifier(Parameter.first))
4077 return TokError("expected identifier in '.irp' directive");
4079 Parameters.push_back(Parameter);
4081 if (Lexer.isNot(AsmToken::Comma))
4082 return TokError("expected comma in '.irp' directive");
4086 MCAsmMacroArguments A;
4087 if (parseMacroArguments(0, A))
4090 // Eat the end of statement.
4093 // Lex the irp definition.
4094 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4098 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4099 // to hold the macro body with substitutions.
4100 SmallString<256> Buf;
4101 raw_svector_ostream OS(Buf);
4103 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4104 MCAsmMacroArguments Args;
4107 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4111 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4116 /// parseDirectiveIrpc
4117 /// ::= .irpc symbol,values
4118 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4119 MCAsmMacroParameters Parameters;
4120 MCAsmMacroParameter Parameter;
4122 if (parseIdentifier(Parameter.first))
4123 return TokError("expected identifier in '.irpc' directive");
4125 Parameters.push_back(Parameter);
4127 if (Lexer.isNot(AsmToken::Comma))
4128 return TokError("expected comma in '.irpc' directive");
4132 MCAsmMacroArguments A;
4133 if (parseMacroArguments(0, A))
4136 if (A.size() != 1 || A.front().size() != 1)
4137 return TokError("unexpected token in '.irpc' directive");
4139 // Eat the end of statement.
4142 // Lex the irpc definition.
4143 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4147 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4148 // to hold the macro body with substitutions.
4149 SmallString<256> Buf;
4150 raw_svector_ostream OS(Buf);
4152 StringRef Values = A.front().front().getString();
4153 std::size_t I, End = Values.size();
4154 for (I = 0; I < End; ++I) {
4155 MCAsmMacroArgument Arg;
4156 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4158 MCAsmMacroArguments Args;
4159 Args.push_back(Arg);
4161 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4165 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4170 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4171 if (ActiveMacros.empty())
4172 return TokError("unmatched '.endr' directive");
4174 // The only .repl that should get here are the ones created by
4175 // instantiateMacroLikeBody.
4176 assert(getLexer().is(AsmToken::EndOfStatement));
4182 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4184 const MCExpr *Value;
4185 SMLoc ExprLoc = getLexer().getLoc();
4186 if (parseExpression(Value))
4188 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4190 return Error(ExprLoc, "unexpected expression in _emit");
4191 uint64_t IntValue = MCE->getValue();
4192 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4193 return Error(ExprLoc, "literal value out of range for directive");
4195 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4199 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4200 const MCExpr *Value;
4201 SMLoc ExprLoc = getLexer().getLoc();
4202 if (parseExpression(Value))
4204 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4206 return Error(ExprLoc, "unexpected expression in align");
4207 uint64_t IntValue = MCE->getValue();
4208 if (!isPowerOf2_64(IntValue))
4209 return Error(ExprLoc, "literal value not a power of two greater then zero");
4211 Info.AsmRewrites->push_back(
4212 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4216 // We are comparing pointers, but the pointers are relative to a single string.
4217 // Thus, this should always be deterministic.
4218 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4219 const AsmRewrite *AsmRewriteB) {
4220 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4222 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4225 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4226 // rewrite to the same location. Make sure the SizeDirective rewrite is
4227 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4228 // ensures the sort algorithm is stable.
4229 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4230 AsmRewritePrecedence[AsmRewriteB->Kind])
4233 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4234 AsmRewritePrecedence[AsmRewriteB->Kind])
4236 llvm_unreachable("Unstable rewrite sort.");
4239 bool AsmParser::parseMSInlineAsm(
4240 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4241 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4242 SmallVectorImpl<std::string> &Constraints,
4243 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4244 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4245 SmallVector<void *, 4> InputDecls;
4246 SmallVector<void *, 4> OutputDecls;
4247 SmallVector<bool, 4> InputDeclsAddressOf;
4248 SmallVector<bool, 4> OutputDeclsAddressOf;
4249 SmallVector<std::string, 4> InputConstraints;
4250 SmallVector<std::string, 4> OutputConstraints;
4251 SmallVector<unsigned, 4> ClobberRegs;
4253 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4258 // While we have input, parse each statement.
4259 unsigned InputIdx = 0;
4260 unsigned OutputIdx = 0;
4261 while (getLexer().isNot(AsmToken::Eof)) {
4262 ParseStatementInfo Info(&AsmStrRewrites);
4263 if (parseStatement(Info))
4266 if (Info.ParseError)
4269 if (Info.Opcode == ~0U)
4272 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4274 // Build the list of clobbers, outputs and inputs.
4275 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4276 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4279 if (Operand->isImm())
4282 // Register operand.
4283 if (Operand->isReg() && !Operand->needAddressOf()) {
4284 unsigned NumDefs = Desc.getNumDefs();
4286 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4287 ClobberRegs.push_back(Operand->getReg());
4291 // Expr/Input or Output.
4292 StringRef SymName = Operand->getSymName();
4293 if (SymName.empty())
4296 void *OpDecl = Operand->getOpDecl();
4300 bool isOutput = (i == 1) && Desc.mayStore();
4301 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4304 OutputDecls.push_back(OpDecl);
4305 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4306 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4307 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4309 InputDecls.push_back(OpDecl);
4310 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4311 InputConstraints.push_back(Operand->getConstraint().str());
4312 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4316 // Consider implicit defs to be clobbers. Think of cpuid and push.
4317 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4318 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4319 ClobberRegs.push_back(ImpDefs[I]);
4322 // Set the number of Outputs and Inputs.
4323 NumOutputs = OutputDecls.size();
4324 NumInputs = InputDecls.size();
4326 // Set the unique clobbers.
4327 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4328 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4330 Clobbers.assign(ClobberRegs.size(), std::string());
4331 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4332 raw_string_ostream OS(Clobbers[I]);
4333 IP->printRegName(OS, ClobberRegs[I]);
4336 // Merge the various outputs and inputs. Output are expected first.
4337 if (NumOutputs || NumInputs) {
4338 unsigned NumExprs = NumOutputs + NumInputs;
4339 OpDecls.resize(NumExprs);
4340 Constraints.resize(NumExprs);
4341 for (unsigned i = 0; i < NumOutputs; ++i) {
4342 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4343 Constraints[i] = OutputConstraints[i];
4345 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4346 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4347 Constraints[j] = InputConstraints[i];
4351 // Build the IR assembly string.
4352 std::string AsmStringIR;
4353 raw_string_ostream OS(AsmStringIR);
4354 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4355 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4356 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4357 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4358 E = AsmStrRewrites.end();
4360 AsmRewriteKind Kind = (*I).Kind;
4361 if (Kind == AOK_Delete)
4364 const char *Loc = (*I).Loc.getPointer();
4365 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4367 // Emit everything up to the immediate/expression.
4368 unsigned Len = Loc - AsmStart;
4370 OS << StringRef(AsmStart, Len);
4372 // Skip the original expression.
4373 if (Kind == AOK_Skip) {
4374 AsmStart = Loc + (*I).Len;
4378 unsigned AdditionalSkip = 0;
4379 // Rewrite expressions in $N notation.
4384 OS << "$$" << (*I).Val;
4390 OS << '$' << InputIdx++;
4393 OS << '$' << OutputIdx++;
4395 case AOK_SizeDirective:
4398 case 8: OS << "byte ptr "; break;
4399 case 16: OS << "word ptr "; break;
4400 case 32: OS << "dword ptr "; break;
4401 case 64: OS << "qword ptr "; break;
4402 case 80: OS << "xword ptr "; break;
4403 case 128: OS << "xmmword ptr "; break;
4404 case 256: OS << "ymmword ptr "; break;
4411 unsigned Val = (*I).Val;
4412 OS << ".align " << Val;
4414 // Skip the original immediate.
4415 assert(Val < 10 && "Expected alignment less then 2^10.");
4416 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4419 case AOK_DotOperator:
4424 // Skip the original expression.
4425 AsmStart = Loc + (*I).Len + AdditionalSkip;
4428 // Emit the remainder of the asm string.
4429 if (AsmStart != AsmEnd)
4430 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4432 AsmString = OS.str();
4436 /// \brief Create an MCAsmParser instance.
4437 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4438 MCStreamer &Out, const MCAsmInfo &MAI) {
4439 return new AsmParser(SM, C, Out, MAI);