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, ArrayRef<MCAsmMacroParameter> P) :
68 Name(N), Body(B), Parameters(P) {}
71 /// \brief Helper class for storing information about an active macro
73 struct MacroInstantiation {
74 /// The macro being instantiated.
75 const MCAsmMacro *TheMacro;
77 /// The macro instantiation with substitutions.
78 MemoryBuffer *Instantiation;
80 /// The location of the instantiation.
81 SMLoc InstantiationLoc;
83 /// The buffer where parsing should resume upon instantiation completion.
86 /// The location where parsing should resume upon instantiation completion.
90 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
94 struct ParseStatementInfo {
95 /// \brief The parsed operands from the last parsed statement.
96 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
98 /// \brief The opcode from the last parsed instruction.
101 /// \brief Was there an error parsing the inline assembly?
104 SmallVectorImpl<AsmRewrite> *AsmRewrites;
106 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
107 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
108 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
110 ~ParseStatementInfo() {
111 // Free any parsed operands.
112 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
113 delete ParsedOperands[i];
114 ParsedOperands.clear();
118 /// \brief The concrete assembly parser instance.
119 class AsmParser : public MCAsmParser {
120 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
121 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
126 const MCAsmInfo &MAI;
128 SourceMgr::DiagHandlerTy SavedDiagHandler;
129 void *SavedDiagContext;
130 MCAsmParserExtension *PlatformParser;
132 /// This is the current buffer index we're lexing from as managed by the
133 /// SourceMgr object.
136 AsmCond TheCondState;
137 std::vector<AsmCond> TheCondStack;
139 /// \brief maps directive names to handler methods in parser
140 /// extensions. Extensions register themselves in this map by calling
141 /// addDirectiveHandler.
142 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
144 /// \brief Map of currently defined macros.
145 StringMap<MCAsmMacro*> MacroMap;
147 /// \brief Stack of active macro instantiations.
148 std::vector<MacroInstantiation*> ActiveMacros;
150 /// \brief List of bodies of anonymous macros.
151 std::deque<MCAsmMacro> MacroLikeBodies;
153 /// Boolean tracking whether macro substitution is enabled.
154 unsigned MacrosEnabledFlag : 1;
156 /// Flag tracking whether any errors have been encountered.
157 unsigned HadError : 1;
159 /// The values from the last parsed cpp hash file line comment if any.
160 StringRef CppHashFilename;
161 int64_t CppHashLineNumber;
164 /// When generating dwarf for assembly source files we need to calculate the
165 /// logical line number based on the last parsed cpp hash file line comment
166 /// and current line. Since this is slow and messes up the SourceMgr's
167 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
168 SMLoc LastQueryIDLoc;
170 unsigned LastQueryLine;
172 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
173 unsigned AssemblerDialect;
175 /// \brief is Darwin compatibility enabled?
178 /// \brief Are we parsing ms-style inline assembly?
179 bool ParsingInlineAsm;
182 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
183 const MCAsmInfo &MAI);
184 virtual ~AsmParser();
186 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
188 virtual void addDirectiveHandler(StringRef Directive,
189 ExtensionDirectiveHandler Handler) {
190 ExtensionDirectiveMap[Directive] = Handler;
194 /// @name MCAsmParser Interface
197 virtual SourceMgr &getSourceManager() { return SrcMgr; }
198 virtual MCAsmLexer &getLexer() { return Lexer; }
199 virtual MCContext &getContext() { return Ctx; }
200 virtual MCStreamer &getStreamer() { return Out; }
201 virtual unsigned getAssemblerDialect() {
202 if (AssemblerDialect == ~0U)
203 return MAI.getAssemblerDialect();
205 return AssemblerDialect;
207 virtual void setAssemblerDialect(unsigned i) {
208 AssemblerDialect = i;
211 virtual void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None);
212 virtual bool Warning(SMLoc L, const Twine &Msg,
213 ArrayRef<SMRange> Ranges = None);
214 virtual bool Error(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None);
217 virtual const AsmToken &Lex();
219 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
220 bool isParsingInlineAsm() { return ParsingInlineAsm; }
222 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
223 unsigned &NumOutputs, unsigned &NumInputs,
224 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
225 SmallVectorImpl<std::string> &Constraints,
226 SmallVectorImpl<std::string> &Clobbers,
227 const MCInstrInfo *MII,
228 const MCInstPrinter *IP,
229 MCAsmParserSemaCallback &SI);
231 bool parseExpression(const MCExpr *&Res);
232 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
233 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
234 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
235 virtual bool parseAbsoluteExpression(int64_t &Res);
237 /// \brief Parse an identifier or string (as a quoted identifier)
238 /// and set \p Res to the identifier contents.
239 virtual bool parseIdentifier(StringRef &Res);
240 virtual void eatToEndOfStatement();
242 virtual void checkForValidSection();
247 bool parseStatement(ParseStatementInfo &Info);
248 void eatToEndOfLine();
249 bool parseCppHashLineFilenameComment(const SMLoc &L);
251 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
252 ArrayRef<MCAsmMacroParameter> Parameters);
253 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
254 ArrayRef<MCAsmMacroParameter> Parameters,
255 ArrayRef<MCAsmMacroArgument> A,
258 /// \brief Are macros enabled in the parser?
259 bool areMacrosEnabled() {return MacrosEnabledFlag;}
261 /// \brief Control a flag in the parser that enables or disables macros.
262 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
264 /// \brief Lookup a previously defined macro.
265 /// \param Name Macro name.
266 /// \returns Pointer to macro. NULL if no such macro was defined.
267 const MCAsmMacro* lookupMacro(StringRef Name);
269 /// \brief Define a new macro with the given name and information.
270 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
272 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
273 void undefineMacro(StringRef Name);
275 /// \brief Are we inside a macro instantiation?
276 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
278 /// \brief Handle entry to macro instantiation.
280 /// \param M The macro.
281 /// \param NameLoc Instantiation location.
282 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
284 /// \brief Handle exit from macro instantiation.
285 void handleMacroExit();
287 /// \brief Extract AsmTokens for a macro argument.
288 bool parseMacroArgument(MCAsmMacroArgument &MA);
290 /// \brief Parse all macro arguments for a given macro.
291 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
293 void printMacroInstantiations();
294 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
295 ArrayRef<SMRange> Ranges = None) const {
296 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
298 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
300 /// \brief Enter the specified file. This returns true on failure.
301 bool enterIncludeFile(const std::string &Filename);
303 /// \brief Process the specified file for the .incbin directive.
304 /// This returns true on failure.
305 bool processIncbinFile(const std::string &Filename);
307 /// \brief Reset the current lexer position to that given by \p Loc. The
308 /// current token is not set; clients should ensure Lex() is called
311 /// \param InBuffer If not -1, should be the known buffer id that contains the
313 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
315 /// \brief Parse up to the end of statement and a return the contents from the
316 /// current token until the end of the statement; the current token on exit
317 /// will be either the EndOfStatement or EOF.
318 virtual StringRef parseStringToEndOfStatement();
320 /// \brief Parse until the end of a statement or a comma is encountered,
321 /// return the contents from the current token up to the end or comma.
322 StringRef parseStringToComma();
324 bool parseAssignment(StringRef Name, bool allow_redef,
325 bool NoDeadStrip = false);
327 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
328 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
329 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
331 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
333 // Generic (target and platform independent) directive parsing.
335 DK_NO_DIRECTIVE, // Placeholder
336 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
337 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
338 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
339 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
340 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
341 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
342 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
343 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
344 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
345 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
346 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
347 DK_ELSEIF, DK_ELSE, DK_ENDIF,
348 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
349 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
350 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
351 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
352 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
353 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
354 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
355 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
356 DK_SLEB128, DK_ULEB128,
360 /// \brief Maps directive name --> DirectiveKind enum, for
361 /// directives parsed by this class.
362 StringMap<DirectiveKind> DirectiveKindMap;
364 // ".ascii", ".asciz", ".string"
365 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
366 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
367 bool parseDirectiveOctaValue(); // ".octa"
368 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
369 bool parseDirectiveFill(); // ".fill"
370 bool parseDirectiveZero(); // ".zero"
371 // ".set", ".equ", ".equiv"
372 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
373 bool parseDirectiveOrg(); // ".org"
374 // ".align{,32}", ".p2align{,w,l}"
375 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
377 // ".file", ".line", ".loc", ".stabs"
378 bool parseDirectiveFile(SMLoc DirectiveLoc);
379 bool parseDirectiveLine();
380 bool parseDirectiveLoc();
381 bool parseDirectiveStabs();
384 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
385 bool parseDirectiveCFIWindowSave();
386 bool parseDirectiveCFISections();
387 bool parseDirectiveCFIStartProc();
388 bool parseDirectiveCFIEndProc();
389 bool parseDirectiveCFIDefCfaOffset();
390 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
391 bool parseDirectiveCFIAdjustCfaOffset();
392 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
394 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
395 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
396 bool parseDirectiveCFIRememberState();
397 bool parseDirectiveCFIRestoreState();
398 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
400 bool parseDirectiveCFIEscape();
401 bool parseDirectiveCFISignalFrame();
402 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
405 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
406 bool parseDirectiveEndMacro(StringRef Directive);
407 bool parseDirectiveMacro(SMLoc DirectiveLoc);
408 bool parseDirectiveMacrosOnOff(StringRef Directive);
410 // ".bundle_align_mode"
411 bool parseDirectiveBundleAlignMode();
413 bool parseDirectiveBundleLock();
415 bool parseDirectiveBundleUnlock();
418 bool parseDirectiveSpace(StringRef IDVal);
420 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
421 bool parseDirectiveLEB128(bool Signed);
423 /// \brief Parse a directive like ".globl" which
424 /// accepts a single symbol (which should be a label or an external).
425 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
427 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
429 bool parseDirectiveAbort(); // ".abort"
430 bool parseDirectiveInclude(); // ".include"
431 bool parseDirectiveIncbin(); // ".incbin"
433 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
434 // ".ifb" or ".ifnb", depending on ExpectBlank.
435 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
436 // ".ifc" or ".ifnc", depending on ExpectEqual.
437 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
438 // ".ifdef" or ".ifndef", depending on expect_defined
439 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
440 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
441 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
442 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
443 virtual bool parseEscapedString(std::string &Data);
445 const MCExpr *applyModifierToExpr(const MCExpr *E,
446 MCSymbolRefExpr::VariantKind Variant);
448 // Macro-like directives
449 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
450 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
451 raw_svector_ostream &OS);
452 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
453 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
454 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
455 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
457 // "_emit" or "__emit"
458 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
462 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
465 bool parseDirectiveEnd(SMLoc DirectiveLoc);
467 void initializeDirectiveKindMap();
473 extern MCAsmParserExtension *createDarwinAsmParser();
474 extern MCAsmParserExtension *createELFAsmParser();
475 extern MCAsmParserExtension *createCOFFAsmParser();
479 enum { DEFAULT_ADDRSPACE = 0 };
481 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
482 const MCAsmInfo &_MAI)
483 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
484 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
485 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
486 ParsingInlineAsm(false) {
487 // Save the old handler.
488 SavedDiagHandler = SrcMgr.getDiagHandler();
489 SavedDiagContext = SrcMgr.getDiagContext();
490 // Set our own handler which calls the saved handler.
491 SrcMgr.setDiagHandler(DiagHandler, this);
492 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
494 // Initialize the platform / file format parser.
495 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
496 case MCObjectFileInfo::IsCOFF:
497 PlatformParser = createCOFFAsmParser();
498 PlatformParser->Initialize(*this);
500 case MCObjectFileInfo::IsMachO:
501 PlatformParser = createDarwinAsmParser();
502 PlatformParser->Initialize(*this);
505 case MCObjectFileInfo::IsELF:
506 PlatformParser = createELFAsmParser();
507 PlatformParser->Initialize(*this);
511 initializeDirectiveKindMap();
514 AsmParser::~AsmParser() {
515 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
517 // Destroy any macros.
518 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
521 delete it->getValue();
523 delete PlatformParser;
526 void AsmParser::printMacroInstantiations() {
527 // Print the active macro instantiation stack.
528 for (std::vector<MacroInstantiation *>::const_reverse_iterator
529 it = ActiveMacros.rbegin(),
530 ie = ActiveMacros.rend();
532 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
533 "while in macro instantiation");
536 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
537 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
538 printMacroInstantiations();
541 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
542 if (FatalAssemblerWarnings)
543 return Error(L, Msg, Ranges);
544 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
545 printMacroInstantiations();
549 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
551 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
552 printMacroInstantiations();
556 bool AsmParser::enterIncludeFile(const std::string &Filename) {
557 std::string IncludedFile;
558 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
564 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
569 /// Process the specified .incbin file by searching for it in the include paths
570 /// then just emitting the byte contents of the file to the streamer. This
571 /// returns true on failure.
572 bool AsmParser::processIncbinFile(const std::string &Filename) {
573 std::string IncludedFile;
574 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
578 // Pick up the bytes from the file and emit them.
579 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
583 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
584 if (InBuffer != -1) {
585 CurBuffer = InBuffer;
587 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
589 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
592 const AsmToken &AsmParser::Lex() {
593 const AsmToken *tok = &Lexer.Lex();
595 if (tok->is(AsmToken::Eof)) {
596 // If this is the end of an included file, pop the parent file off the
598 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
599 if (ParentIncludeLoc != SMLoc()) {
600 jumpToLoc(ParentIncludeLoc);
605 if (tok->is(AsmToken::Error))
606 Error(Lexer.getErrLoc(), Lexer.getErr());
611 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
612 // Create the initial section, if requested.
613 if (!NoInitialTextSection)
620 AsmCond StartingCondState = TheCondState;
622 // If we are generating dwarf for assembly source files save the initial text
623 // section and generate a .file directive.
624 if (getContext().getGenDwarfForAssembly()) {
625 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
626 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
627 getStreamer().EmitLabel(SectionStartSym);
628 getContext().setGenDwarfSectionStartSym(SectionStartSym);
629 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
631 getContext().getMainFileName());
634 // While we have input, parse each statement.
635 while (Lexer.isNot(AsmToken::Eof)) {
636 ParseStatementInfo Info;
637 if (!parseStatement(Info))
640 // We had an error, validate that one was emitted and recover by skipping to
642 assert(HadError && "Parse statement returned an error, but none emitted!");
643 eatToEndOfStatement();
646 if (TheCondState.TheCond != StartingCondState.TheCond ||
647 TheCondState.Ignore != StartingCondState.Ignore)
648 return TokError("unmatched .ifs or .elses");
650 // Check to see there are no empty DwarfFile slots.
651 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
652 getContext().getMCDwarfFiles();
653 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
654 if (!MCDwarfFiles[i])
655 TokError("unassigned file number: " + Twine(i) + " for .file directives");
658 // Check to see that all assembler local symbols were actually defined.
659 // Targets that don't do subsections via symbols may not want this, though,
660 // so conservatively exclude them. Only do this if we're finalizing, though,
661 // as otherwise we won't necessarilly have seen everything yet.
662 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
663 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
664 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
667 MCSymbol *Sym = i->getValue();
668 // Variable symbols may not be marked as defined, so check those
669 // explicitly. If we know it's a variable, we have a definition for
670 // the purposes of this check.
671 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
672 // FIXME: We would really like to refer back to where the symbol was
673 // first referenced for a source location. We need to add something
674 // to track that. Currently, we just point to the end of the file.
676 getLexer().getLoc(), SourceMgr::DK_Error,
677 "assembler local symbol '" + Sym->getName() + "' not defined");
681 // Finalize the output stream if there are no errors and if the client wants
683 if (!HadError && !NoFinalize)
689 void AsmParser::checkForValidSection() {
690 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
691 TokError("expected section directive before assembly directive");
696 /// \brief Throw away the rest of the line for testing purposes.
697 void AsmParser::eatToEndOfStatement() {
698 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
702 if (Lexer.is(AsmToken::EndOfStatement))
706 StringRef AsmParser::parseStringToEndOfStatement() {
707 const char *Start = getTok().getLoc().getPointer();
709 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
712 const char *End = getTok().getLoc().getPointer();
713 return StringRef(Start, End - Start);
716 StringRef AsmParser::parseStringToComma() {
717 const char *Start = getTok().getLoc().getPointer();
719 while (Lexer.isNot(AsmToken::EndOfStatement) &&
720 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
723 const char *End = getTok().getLoc().getPointer();
724 return StringRef(Start, End - Start);
727 /// \brief Parse a paren expression and return it.
728 /// NOTE: This assumes the leading '(' has already been consumed.
730 /// parenexpr ::= expr)
732 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
733 if (parseExpression(Res))
735 if (Lexer.isNot(AsmToken::RParen))
736 return TokError("expected ')' in parentheses expression");
737 EndLoc = Lexer.getTok().getEndLoc();
742 /// \brief Parse a bracket expression and return it.
743 /// NOTE: This assumes the leading '[' has already been consumed.
745 /// bracketexpr ::= expr]
747 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
748 if (parseExpression(Res))
750 if (Lexer.isNot(AsmToken::RBrac))
751 return TokError("expected ']' in brackets expression");
752 EndLoc = Lexer.getTok().getEndLoc();
757 /// \brief Parse a primary expression and return it.
758 /// primaryexpr ::= (parenexpr
759 /// primaryexpr ::= symbol
760 /// primaryexpr ::= number
761 /// primaryexpr ::= '.'
762 /// primaryexpr ::= ~,+,- primaryexpr
763 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
764 SMLoc FirstTokenLoc = getLexer().getLoc();
765 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
766 switch (FirstTokenKind) {
768 return TokError("unknown token in expression");
769 // If we have an error assume that we've already handled it.
770 case AsmToken::Error:
772 case AsmToken::Exclaim:
773 Lex(); // Eat the operator.
774 if (parsePrimaryExpr(Res, EndLoc))
776 Res = MCUnaryExpr::CreateLNot(Res, getContext());
778 case AsmToken::Dollar:
780 case AsmToken::String:
781 case AsmToken::Identifier: {
782 StringRef Identifier;
783 if (parseIdentifier(Identifier)) {
784 if (FirstTokenKind == AsmToken::Dollar) {
785 if (Lexer.getMAI().getDollarIsPC()) {
786 // This is a '$' reference, which references the current PC. Emit a
787 // temporary label to the streamer and refer to it.
788 MCSymbol *Sym = Ctx.CreateTempSymbol();
790 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
792 EndLoc = FirstTokenLoc;
795 return Error(FirstTokenLoc, "invalid token in expression");
799 // Parse symbol variant
800 std::pair<StringRef, StringRef> Split;
801 if (!MAI.useParensForSymbolVariant()) {
802 Split = Identifier.split('@');
803 } else if (Lexer.is(AsmToken::LParen)) {
804 Lexer.Lex(); // eat (
806 parseIdentifier(VName);
807 if (Lexer.isNot(AsmToken::RParen)) {
808 return Error(Lexer.getTok().getLoc(),
809 "unexpected token in variant, expected ')'");
811 Lexer.Lex(); // eat )
812 Split = std::make_pair(Identifier, VName);
815 EndLoc = SMLoc::getFromPointer(Identifier.end());
817 // This is a symbol reference.
818 StringRef SymbolName = Identifier;
819 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
821 // Lookup the symbol variant if used.
822 if (Split.second.size()) {
823 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
824 if (Variant != MCSymbolRefExpr::VK_Invalid) {
825 SymbolName = Split.first;
826 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
827 Variant = MCSymbolRefExpr::VK_None;
829 Variant = MCSymbolRefExpr::VK_None;
830 return Error(SMLoc::getFromPointer(Split.second.begin()),
831 "invalid variant '" + Split.second + "'");
835 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
837 // If this is an absolute variable reference, substitute it now to preserve
838 // semantics in the face of reassignment.
839 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
841 return Error(EndLoc, "unexpected modifier on variable reference");
843 Res = Sym->getVariableValue();
847 // Otherwise create a symbol ref.
848 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
851 case AsmToken::BigNum:
852 return TokError("literal value out of range for directive");
853 case AsmToken::Integer: {
854 SMLoc Loc = getTok().getLoc();
855 int64_t IntVal = getTok().getIntVal();
856 Res = MCConstantExpr::Create(IntVal, getContext());
857 EndLoc = Lexer.getTok().getEndLoc();
859 // Look for 'b' or 'f' following an Integer as a directional label
860 if (Lexer.getKind() == AsmToken::Identifier) {
861 StringRef IDVal = getTok().getString();
862 // Lookup the symbol variant if used.
863 std::pair<StringRef, StringRef> Split = IDVal.split('@');
864 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
865 if (Split.first.size() != IDVal.size()) {
866 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
867 if (Variant == MCSymbolRefExpr::VK_Invalid) {
868 Variant = MCSymbolRefExpr::VK_None;
869 return TokError("invalid variant '" + Split.second + "'");
873 if (IDVal == "f" || IDVal == "b") {
875 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
876 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
877 if (IDVal == "b" && Sym->isUndefined())
878 return Error(Loc, "invalid reference to undefined symbol");
879 EndLoc = Lexer.getTok().getEndLoc();
880 Lex(); // Eat identifier.
885 case AsmToken::Real: {
886 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
887 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
888 Res = MCConstantExpr::Create(IntVal, getContext());
889 EndLoc = Lexer.getTok().getEndLoc();
893 case AsmToken::Dot: {
894 // This is a '.' reference, which references the current PC. Emit a
895 // temporary label to the streamer and refer to it.
896 MCSymbol *Sym = Ctx.CreateTempSymbol();
898 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
899 EndLoc = Lexer.getTok().getEndLoc();
900 Lex(); // Eat identifier.
903 case AsmToken::LParen:
904 Lex(); // Eat the '('.
905 return parseParenExpr(Res, EndLoc);
906 case AsmToken::LBrac:
907 if (!PlatformParser->HasBracketExpressions())
908 return TokError("brackets expression not supported on this target");
909 Lex(); // Eat the '['.
910 return parseBracketExpr(Res, EndLoc);
911 case AsmToken::Minus:
912 Lex(); // Eat the operator.
913 if (parsePrimaryExpr(Res, EndLoc))
915 Res = MCUnaryExpr::CreateMinus(Res, getContext());
918 Lex(); // Eat the operator.
919 if (parsePrimaryExpr(Res, EndLoc))
921 Res = MCUnaryExpr::CreatePlus(Res, getContext());
923 case AsmToken::Tilde:
924 Lex(); // Eat the operator.
925 if (parsePrimaryExpr(Res, EndLoc))
927 Res = MCUnaryExpr::CreateNot(Res, getContext());
932 bool AsmParser::parseExpression(const MCExpr *&Res) {
934 return parseExpression(Res, EndLoc);
938 AsmParser::applyModifierToExpr(const MCExpr *E,
939 MCSymbolRefExpr::VariantKind Variant) {
940 // Ask the target implementation about this expression first.
941 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
944 // Recurse over the given expression, rebuilding it to apply the given variant
945 // if there is exactly one symbol.
946 switch (E->getKind()) {
948 case MCExpr::Constant:
951 case MCExpr::SymbolRef: {
952 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
954 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
955 TokError("invalid variant on expression '" + getTok().getIdentifier() +
956 "' (already modified)");
960 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
963 case MCExpr::Unary: {
964 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
965 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
968 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
971 case MCExpr::Binary: {
972 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
973 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
974 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
984 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
988 llvm_unreachable("Invalid expression kind!");
991 /// \brief Parse an expression and return it.
993 /// expr ::= expr &&,|| expr -> lowest.
994 /// expr ::= expr |,^,&,! expr
995 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
996 /// expr ::= expr <<,>> expr
997 /// expr ::= expr +,- expr
998 /// expr ::= expr *,/,% expr -> highest.
999 /// expr ::= primaryexpr
1001 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1002 // Parse the expression.
1004 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1007 // As a special case, we support 'a op b @ modifier' by rewriting the
1008 // expression to include the modifier. This is inefficient, but in general we
1009 // expect users to use 'a@modifier op b'.
1010 if (Lexer.getKind() == AsmToken::At) {
1013 if (Lexer.isNot(AsmToken::Identifier))
1014 return TokError("unexpected symbol modifier following '@'");
1016 MCSymbolRefExpr::VariantKind Variant =
1017 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1018 if (Variant == MCSymbolRefExpr::VK_Invalid)
1019 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1021 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1023 return TokError("invalid modifier '" + getTok().getIdentifier() +
1024 "' (no symbols present)");
1031 // Try to constant fold it up front, if possible.
1033 if (Res->EvaluateAsAbsolute(Value))
1034 Res = MCConstantExpr::Create(Value, getContext());
1039 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1041 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1044 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1047 SMLoc StartLoc = Lexer.getLoc();
1048 if (parseExpression(Expr))
1051 if (!Expr->EvaluateAsAbsolute(Res))
1052 return Error(StartLoc, "expected absolute expression");
1057 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1058 MCBinaryExpr::Opcode &Kind) {
1061 return 0; // not a binop.
1063 // Lowest Precedence: &&, ||
1064 case AsmToken::AmpAmp:
1065 Kind = MCBinaryExpr::LAnd;
1067 case AsmToken::PipePipe:
1068 Kind = MCBinaryExpr::LOr;
1071 // Low Precedence: |, &, ^
1073 // FIXME: gas seems to support '!' as an infix operator?
1074 case AsmToken::Pipe:
1075 Kind = MCBinaryExpr::Or;
1077 case AsmToken::Caret:
1078 Kind = MCBinaryExpr::Xor;
1081 Kind = MCBinaryExpr::And;
1084 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1085 case AsmToken::EqualEqual:
1086 Kind = MCBinaryExpr::EQ;
1088 case AsmToken::ExclaimEqual:
1089 case AsmToken::LessGreater:
1090 Kind = MCBinaryExpr::NE;
1092 case AsmToken::Less:
1093 Kind = MCBinaryExpr::LT;
1095 case AsmToken::LessEqual:
1096 Kind = MCBinaryExpr::LTE;
1098 case AsmToken::Greater:
1099 Kind = MCBinaryExpr::GT;
1101 case AsmToken::GreaterEqual:
1102 Kind = MCBinaryExpr::GTE;
1105 // Intermediate Precedence: <<, >>
1106 case AsmToken::LessLess:
1107 Kind = MCBinaryExpr::Shl;
1109 case AsmToken::GreaterGreater:
1110 Kind = MCBinaryExpr::Shr;
1113 // High Intermediate Precedence: +, -
1114 case AsmToken::Plus:
1115 Kind = MCBinaryExpr::Add;
1117 case AsmToken::Minus:
1118 Kind = MCBinaryExpr::Sub;
1121 // Highest Precedence: *, /, %
1122 case AsmToken::Star:
1123 Kind = MCBinaryExpr::Mul;
1125 case AsmToken::Slash:
1126 Kind = MCBinaryExpr::Div;
1128 case AsmToken::Percent:
1129 Kind = MCBinaryExpr::Mod;
1134 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1135 /// Res contains the LHS of the expression on input.
1136 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1139 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1140 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1142 // If the next token is lower precedence than we are allowed to eat, return
1143 // successfully with what we ate already.
1144 if (TokPrec < Precedence)
1149 // Eat the next primary expression.
1151 if (parsePrimaryExpr(RHS, EndLoc))
1154 // If BinOp binds less tightly with RHS than the operator after RHS, let
1155 // the pending operator take RHS as its LHS.
1156 MCBinaryExpr::Opcode Dummy;
1157 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1158 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1161 // Merge LHS and RHS according to operator.
1162 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1167 /// ::= EndOfStatement
1168 /// ::= Label* Directive ...Operands... EndOfStatement
1169 /// ::= Label* Identifier OperandList* EndOfStatement
1170 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1171 if (Lexer.is(AsmToken::EndOfStatement)) {
1177 // Statements always start with an identifier or are a full line comment.
1178 AsmToken ID = getTok();
1179 SMLoc IDLoc = ID.getLoc();
1181 int64_t LocalLabelVal = -1;
1182 // A full line comment is a '#' as the first token.
1183 if (Lexer.is(AsmToken::Hash))
1184 return parseCppHashLineFilenameComment(IDLoc);
1186 // Allow an integer followed by a ':' as a directional local label.
1187 if (Lexer.is(AsmToken::Integer)) {
1188 LocalLabelVal = getTok().getIntVal();
1189 if (LocalLabelVal < 0) {
1190 if (!TheCondState.Ignore)
1191 return TokError("unexpected token at start of statement");
1194 IDVal = getTok().getString();
1195 Lex(); // Consume the integer token to be used as an identifier token.
1196 if (Lexer.getKind() != AsmToken::Colon) {
1197 if (!TheCondState.Ignore)
1198 return TokError("unexpected token at start of statement");
1201 } else if (Lexer.is(AsmToken::Dot)) {
1202 // Treat '.' as a valid identifier in this context.
1205 } else if (parseIdentifier(IDVal)) {
1206 if (!TheCondState.Ignore)
1207 return TokError("unexpected token at start of statement");
1211 // Handle conditional assembly here before checking for skipping. We
1212 // have to do this so that .endif isn't skipped in a ".if 0" block for
1214 StringMap<DirectiveKind>::const_iterator DirKindIt =
1215 DirectiveKindMap.find(IDVal);
1216 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1218 : DirKindIt->getValue();
1223 return parseDirectiveIf(IDLoc);
1225 return parseDirectiveIfb(IDLoc, true);
1227 return parseDirectiveIfb(IDLoc, false);
1229 return parseDirectiveIfc(IDLoc, true);
1231 return parseDirectiveIfc(IDLoc, false);
1233 return parseDirectiveIfdef(IDLoc, true);
1236 return parseDirectiveIfdef(IDLoc, false);
1238 return parseDirectiveElseIf(IDLoc);
1240 return parseDirectiveElse(IDLoc);
1242 return parseDirectiveEndIf(IDLoc);
1245 // Ignore the statement if in the middle of inactive conditional
1247 if (TheCondState.Ignore) {
1248 eatToEndOfStatement();
1252 // FIXME: Recurse on local labels?
1254 // See what kind of statement we have.
1255 switch (Lexer.getKind()) {
1256 case AsmToken::Colon: {
1257 checkForValidSection();
1259 // identifier ':' -> Label.
1262 // Diagnose attempt to use '.' as a label.
1264 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1266 // Diagnose attempt to use a variable as a label.
1268 // FIXME: Diagnostics. Note the location of the definition as a label.
1269 // FIXME: This doesn't diagnose assignment to a symbol which has been
1270 // implicitly marked as external.
1272 if (LocalLabelVal == -1)
1273 Sym = getContext().GetOrCreateSymbol(IDVal);
1275 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1276 if (!Sym->isUndefined() || Sym->isVariable())
1277 return Error(IDLoc, "invalid symbol redefinition");
1280 if (!ParsingInlineAsm)
1283 // If we are generating dwarf for assembly source files then gather the
1284 // info to make a dwarf label entry for this label if needed.
1285 if (getContext().getGenDwarfForAssembly())
1286 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1289 getTargetParser().onLabelParsed(Sym);
1291 // Consume any end of statement token, if present, to avoid spurious
1292 // AddBlankLine calls().
1293 if (Lexer.is(AsmToken::EndOfStatement)) {
1295 if (Lexer.is(AsmToken::Eof))
1302 case AsmToken::Equal:
1303 // identifier '=' ... -> assignment statement
1306 return parseAssignment(IDVal, true);
1308 default: // Normal instruction or directive.
1312 // If macros are enabled, check to see if this is a macro instantiation.
1313 if (areMacrosEnabled())
1314 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1315 return handleMacroEntry(M, IDLoc);
1318 // Otherwise, we have a normal instruction or directive.
1320 // Directives start with "."
1321 if (IDVal[0] == '.' && IDVal != ".") {
1322 // There are several entities interested in parsing directives:
1324 // 1. The target-specific assembly parser. Some directives are target
1325 // specific or may potentially behave differently on certain targets.
1326 // 2. Asm parser extensions. For example, platform-specific parsers
1327 // (like the ELF parser) register themselves as extensions.
1328 // 3. The generic directive parser implemented by this class. These are
1329 // all the directives that behave in a target and platform independent
1330 // manner, or at least have a default behavior that's shared between
1331 // all targets and platforms.
1333 // First query the target-specific parser. It will return 'true' if it
1334 // isn't interested in this directive.
1335 if (!getTargetParser().ParseDirective(ID))
1338 // Next, check the extension directive map to see if any extension has
1339 // registered itself to parse this directive.
1340 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1341 ExtensionDirectiveMap.lookup(IDVal);
1343 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1345 // Finally, if no one else is interested in this directive, it must be
1346 // generic and familiar to this class.
1352 return parseDirectiveSet(IDVal, true);
1354 return parseDirectiveSet(IDVal, false);
1356 return parseDirectiveAscii(IDVal, false);
1359 return parseDirectiveAscii(IDVal, true);
1361 return parseDirectiveValue(1);
1365 return parseDirectiveValue(2);
1369 return parseDirectiveValue(4);
1372 return parseDirectiveValue(8);
1374 return parseDirectiveOctaValue();
1377 return parseDirectiveRealValue(APFloat::IEEEsingle);
1379 return parseDirectiveRealValue(APFloat::IEEEdouble);
1381 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1382 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1385 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1386 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1389 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1391 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1393 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1395 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1397 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1399 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1401 return parseDirectiveOrg();
1403 return parseDirectiveFill();
1405 return parseDirectiveZero();
1407 eatToEndOfStatement(); // .extern is the default, ignore it.
1411 return parseDirectiveSymbolAttribute(MCSA_Global);
1412 case DK_LAZY_REFERENCE:
1413 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1414 case DK_NO_DEAD_STRIP:
1415 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1416 case DK_SYMBOL_RESOLVER:
1417 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1418 case DK_PRIVATE_EXTERN:
1419 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1421 return parseDirectiveSymbolAttribute(MCSA_Reference);
1422 case DK_WEAK_DEFINITION:
1423 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1424 case DK_WEAK_REFERENCE:
1425 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1426 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1427 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1430 return parseDirectiveComm(/*IsLocal=*/false);
1432 return parseDirectiveComm(/*IsLocal=*/true);
1434 return parseDirectiveAbort();
1436 return parseDirectiveInclude();
1438 return parseDirectiveIncbin();
1441 return TokError(Twine(IDVal) + " not supported yet");
1443 return parseDirectiveRept(IDLoc, IDVal);
1445 return parseDirectiveIrp(IDLoc);
1447 return parseDirectiveIrpc(IDLoc);
1449 return parseDirectiveEndr(IDLoc);
1450 case DK_BUNDLE_ALIGN_MODE:
1451 return parseDirectiveBundleAlignMode();
1452 case DK_BUNDLE_LOCK:
1453 return parseDirectiveBundleLock();
1454 case DK_BUNDLE_UNLOCK:
1455 return parseDirectiveBundleUnlock();
1457 return parseDirectiveLEB128(true);
1459 return parseDirectiveLEB128(false);
1462 return parseDirectiveSpace(IDVal);
1464 return parseDirectiveFile(IDLoc);
1466 return parseDirectiveLine();
1468 return parseDirectiveLoc();
1470 return parseDirectiveStabs();
1471 case DK_CFI_SECTIONS:
1472 return parseDirectiveCFISections();
1473 case DK_CFI_STARTPROC:
1474 return parseDirectiveCFIStartProc();
1475 case DK_CFI_ENDPROC:
1476 return parseDirectiveCFIEndProc();
1477 case DK_CFI_DEF_CFA:
1478 return parseDirectiveCFIDefCfa(IDLoc);
1479 case DK_CFI_DEF_CFA_OFFSET:
1480 return parseDirectiveCFIDefCfaOffset();
1481 case DK_CFI_ADJUST_CFA_OFFSET:
1482 return parseDirectiveCFIAdjustCfaOffset();
1483 case DK_CFI_DEF_CFA_REGISTER:
1484 return parseDirectiveCFIDefCfaRegister(IDLoc);
1486 return parseDirectiveCFIOffset(IDLoc);
1487 case DK_CFI_REL_OFFSET:
1488 return parseDirectiveCFIRelOffset(IDLoc);
1489 case DK_CFI_PERSONALITY:
1490 return parseDirectiveCFIPersonalityOrLsda(true);
1492 return parseDirectiveCFIPersonalityOrLsda(false);
1493 case DK_CFI_REMEMBER_STATE:
1494 return parseDirectiveCFIRememberState();
1495 case DK_CFI_RESTORE_STATE:
1496 return parseDirectiveCFIRestoreState();
1497 case DK_CFI_SAME_VALUE:
1498 return parseDirectiveCFISameValue(IDLoc);
1499 case DK_CFI_RESTORE:
1500 return parseDirectiveCFIRestore(IDLoc);
1502 return parseDirectiveCFIEscape();
1503 case DK_CFI_SIGNAL_FRAME:
1504 return parseDirectiveCFISignalFrame();
1505 case DK_CFI_UNDEFINED:
1506 return parseDirectiveCFIUndefined(IDLoc);
1507 case DK_CFI_REGISTER:
1508 return parseDirectiveCFIRegister(IDLoc);
1509 case DK_CFI_WINDOW_SAVE:
1510 return parseDirectiveCFIWindowSave();
1513 return parseDirectiveMacrosOnOff(IDVal);
1515 return parseDirectiveMacro(IDLoc);
1518 return parseDirectiveEndMacro(IDVal);
1520 return parseDirectivePurgeMacro(IDLoc);
1522 return parseDirectiveEnd(IDLoc);
1525 return Error(IDLoc, "unknown directive");
1528 // __asm _emit or __asm __emit
1529 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1530 IDVal == "_EMIT" || IDVal == "__EMIT"))
1531 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1534 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1535 return parseDirectiveMSAlign(IDLoc, Info);
1537 checkForValidSection();
1539 // Canonicalize the opcode to lower case.
1540 std::string OpcodeStr = IDVal.lower();
1541 ParseInstructionInfo IInfo(Info.AsmRewrites);
1542 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1543 Info.ParsedOperands);
1544 Info.ParseError = HadError;
1546 // Dump the parsed representation, if requested.
1547 if (getShowParsedOperands()) {
1548 SmallString<256> Str;
1549 raw_svector_ostream OS(Str);
1550 OS << "parsed instruction: [";
1551 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1554 Info.ParsedOperands[i]->print(OS);
1558 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1561 // If we are generating dwarf for assembly source files and the current
1562 // section is the initial text section then generate a .loc directive for
1564 if (!HadError && getContext().getGenDwarfForAssembly() &&
1565 getContext().getGenDwarfSection() ==
1566 getStreamer().getCurrentSection().first) {
1568 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1570 // If we previously parsed a cpp hash file line comment then make sure the
1571 // current Dwarf File is for the CppHashFilename if not then emit the
1572 // Dwarf File table for it and adjust the line number for the .loc.
1573 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1574 getContext().getMCDwarfFiles();
1575 if (CppHashFilename.size() != 0) {
1576 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1578 getStreamer().EmitDwarfFileDirective(
1579 getContext().nextGenDwarfFileNumber(), StringRef(),
1582 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1583 // cache with the different Loc from the call above we save the last
1584 // info we queried here with SrcMgr.FindLineNumber().
1585 unsigned CppHashLocLineNo;
1586 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1587 CppHashLocLineNo = LastQueryLine;
1589 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1590 LastQueryLine = CppHashLocLineNo;
1591 LastQueryIDLoc = CppHashLoc;
1592 LastQueryBuffer = CppHashBuf;
1594 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1597 getStreamer().EmitDwarfLocDirective(
1598 getContext().getGenDwarfFileNumber(), Line, 0,
1599 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1603 // If parsing succeeded, match the instruction.
1606 HadError = getTargetParser().MatchAndEmitInstruction(
1607 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1611 // Don't skip the rest of the line, the instruction parser is responsible for
1616 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1617 /// since they may not be able to be tokenized to get to the end of line token.
1618 void AsmParser::eatToEndOfLine() {
1619 if (!Lexer.is(AsmToken::EndOfStatement))
1620 Lexer.LexUntilEndOfLine();
1625 /// parseCppHashLineFilenameComment as this:
1626 /// ::= # number "filename"
1627 /// or just as a full line comment if it doesn't have a number and a string.
1628 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1629 Lex(); // Eat the hash token.
1631 if (getLexer().isNot(AsmToken::Integer)) {
1632 // Consume the line since in cases it is not a well-formed line directive,
1633 // as if were simply a full line comment.
1638 int64_t LineNumber = getTok().getIntVal();
1641 if (getLexer().isNot(AsmToken::String)) {
1646 StringRef Filename = getTok().getString();
1647 // Get rid of the enclosing quotes.
1648 Filename = Filename.substr(1, Filename.size() - 2);
1650 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1652 CppHashFilename = Filename;
1653 CppHashLineNumber = LineNumber;
1654 CppHashBuf = CurBuffer;
1656 // Ignore any trailing characters, they're just comment.
1661 /// \brief will use the last parsed cpp hash line filename comment
1662 /// for the Filename and LineNo if any in the diagnostic.
1663 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1664 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1665 raw_ostream &OS = errs();
1667 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1668 const SMLoc &DiagLoc = Diag.getLoc();
1669 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1670 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1672 // Like SourceMgr::printMessage() we need to print the include stack if any
1673 // before printing the message.
1674 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1675 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1676 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1677 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1680 // If we have not parsed a cpp hash line filename comment or the source
1681 // manager changed or buffer changed (like in a nested include) then just
1682 // print the normal diagnostic using its Filename and LineNo.
1683 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1684 DiagBuf != CppHashBuf) {
1685 if (Parser->SavedDiagHandler)
1686 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1692 // Use the CppHashFilename and calculate a line number based on the
1693 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1695 const std::string &Filename = Parser->CppHashFilename;
1697 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1698 int CppHashLocLineNo =
1699 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1701 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1703 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1704 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1705 Diag.getLineContents(), Diag.getRanges());
1707 if (Parser->SavedDiagHandler)
1708 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1710 NewDiag.print(0, OS);
1713 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1714 // difference being that that function accepts '@' as part of identifiers and
1715 // we can't do that. AsmLexer.cpp should probably be changed to handle
1716 // '@' as a special case when needed.
1717 static bool isIdentifierChar(char c) {
1718 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1722 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1723 ArrayRef<MCAsmMacroParameter> Parameters,
1724 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1725 unsigned NParameters = Parameters.size();
1726 if (NParameters != 0 && NParameters != A.size())
1727 return Error(L, "Wrong number of arguments");
1729 // A macro without parameters is handled differently on Darwin:
1730 // gas accepts no arguments and does no substitutions
1731 while (!Body.empty()) {
1732 // Scan for the next substitution.
1733 std::size_t End = Body.size(), Pos = 0;
1734 for (; Pos != End; ++Pos) {
1735 // Check for a substitution or escape.
1737 // This macro has no parameters, look for $0, $1, etc.
1738 if (Body[Pos] != '$' || Pos + 1 == End)
1741 char Next = Body[Pos + 1];
1742 if (Next == '$' || Next == 'n' ||
1743 isdigit(static_cast<unsigned char>(Next)))
1746 // This macro has parameters, look for \foo, \bar, etc.
1747 if (Body[Pos] == '\\' && Pos + 1 != End)
1753 OS << Body.slice(0, Pos);
1755 // Check if we reached the end.
1760 switch (Body[Pos + 1]) {
1766 // $n => number of arguments
1771 // $[0-9] => argument
1773 // Missing arguments are ignored.
1774 unsigned Index = Body[Pos + 1] - '0';
1775 if (Index >= A.size())
1778 // Otherwise substitute with the token values, with spaces eliminated.
1779 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1780 ie = A[Index].end();
1782 OS << it->getString();
1788 unsigned I = Pos + 1;
1789 while (isIdentifierChar(Body[I]) && I + 1 != End)
1792 const char *Begin = Body.data() + Pos + 1;
1793 StringRef Argument(Begin, I - (Pos + 1));
1795 for (; Index < NParameters; ++Index)
1796 if (Parameters[Index].first == Argument)
1799 if (Index == NParameters) {
1800 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1803 OS << '\\' << Argument;
1807 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1808 ie = A[Index].end();
1810 if (it->getKind() == AsmToken::String)
1811 OS << it->getStringContents();
1813 OS << it->getString();
1815 Pos += 1 + Argument.size();
1818 // Update the scan point.
1819 Body = Body.substr(Pos);
1825 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1826 SMLoc EL, MemoryBuffer *I)
1827 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1830 static bool isOperator(AsmToken::TokenKind kind) {
1834 case AsmToken::Plus:
1835 case AsmToken::Minus:
1836 case AsmToken::Tilde:
1837 case AsmToken::Slash:
1838 case AsmToken::Star:
1840 case AsmToken::Equal:
1841 case AsmToken::EqualEqual:
1842 case AsmToken::Pipe:
1843 case AsmToken::PipePipe:
1844 case AsmToken::Caret:
1846 case AsmToken::AmpAmp:
1847 case AsmToken::Exclaim:
1848 case AsmToken::ExclaimEqual:
1849 case AsmToken::Percent:
1850 case AsmToken::Less:
1851 case AsmToken::LessEqual:
1852 case AsmToken::LessLess:
1853 case AsmToken::LessGreater:
1854 case AsmToken::Greater:
1855 case AsmToken::GreaterEqual:
1856 case AsmToken::GreaterGreater:
1862 class AsmLexerSkipSpaceRAII {
1864 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1865 Lexer.setSkipSpace(SkipSpace);
1868 ~AsmLexerSkipSpaceRAII() {
1869 Lexer.setSkipSpace(true);
1877 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA) {
1878 unsigned ParenLevel = 0;
1879 unsigned AddTokens = 0;
1881 // Darwin doesn't use spaces to delmit arguments.
1882 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1885 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1886 return TokError("unexpected token in macro instantiation");
1888 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1891 if (Lexer.is(AsmToken::Space)) {
1892 Lex(); // Eat spaces
1894 // Spaces can delimit parameters, but could also be part an expression.
1895 // If the token after a space is an operator, add the token and the next
1896 // one into this argument
1898 if (isOperator(Lexer.getKind())) {
1899 // Check to see whether the token is used as an operator,
1900 // or part of an identifier
1901 const char *NextChar = getTok().getEndLoc().getPointer();
1902 if (*NextChar == ' ')
1906 if (!AddTokens && ParenLevel == 0) {
1912 // handleMacroEntry relies on not advancing the lexer here
1913 // to be able to fill in the remaining default parameter values
1914 if (Lexer.is(AsmToken::EndOfStatement))
1917 // Adjust the current parentheses level.
1918 if (Lexer.is(AsmToken::LParen))
1920 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1923 // Append the token to the current argument list.
1924 MA.push_back(getTok());
1930 if (ParenLevel != 0)
1931 return TokError("unbalanced parentheses in macro argument");
1935 // Parse the macro instantiation arguments.
1936 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1937 MCAsmMacroArguments &A) {
1938 const unsigned NParameters = M ? M->Parameters.size() : 0;
1940 A.resize(NParameters);
1941 for (unsigned PI = 0; PI < NParameters; ++PI)
1942 if (!M->Parameters[PI].second.empty())
1943 A[PI] = M->Parameters[PI].second;
1945 bool NamedParametersFound = false;
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 MCAsmMacroParameter FA;
1955 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1957 if (parseIdentifier(FA.first)) {
1958 Error(L, "invalid argument identifier for formal argument");
1959 eatToEndOfStatement();
1963 if (!Lexer.is(AsmToken::Equal)) {
1964 TokError("expected '=' after formal parameter identifier");
1965 eatToEndOfStatement();
1970 NamedParametersFound = true;
1973 if (NamedParametersFound && FA.first.empty()) {
1974 Error(Lexer.getLoc(), "cannot mix positional and keyword arguments");
1975 eatToEndOfStatement();
1979 if (parseMacroArgument(FA.second))
1982 unsigned PI = Parameter;
1983 if (!FA.first.empty()) {
1985 for (FAI = 0; FAI < NParameters; ++FAI)
1986 if (M->Parameters[FAI].first == FA.first)
1988 if (FAI >= NParameters) {
1990 "parameter named '" + FA.first + "' does not exist for macro '" +
1997 if (!FA.second.empty()) {
2003 // At the end of the statement, fill in remaining arguments that have
2004 // default values. If there aren't any, then the next argument is
2005 // required but missing
2006 if (Lexer.is(AsmToken::EndOfStatement))
2009 if (Lexer.is(AsmToken::Comma))
2013 return TokError("too many positional arguments");
2016 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2017 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2018 return (I == MacroMap.end()) ? NULL : I->getValue();
2021 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2022 MacroMap[Name] = new MCAsmMacro(Macro);
2025 void AsmParser::undefineMacro(StringRef Name) {
2026 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2027 if (I != MacroMap.end()) {
2028 delete I->getValue();
2033 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2034 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2035 // this, although we should protect against infinite loops.
2036 if (ActiveMacros.size() == 20)
2037 return TokError("macros cannot be nested more than 20 levels deep");
2039 MCAsmMacroArguments A;
2040 if (parseMacroArguments(M, A))
2043 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2044 // to hold the macro body with substitutions.
2045 SmallString<256> Buf;
2046 StringRef Body = M->Body;
2047 raw_svector_ostream OS(Buf);
2049 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2052 // We include the .endmacro in the buffer as our cue to exit the macro
2054 OS << ".endmacro\n";
2056 MemoryBuffer *Instantiation =
2057 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2059 // Create the macro instantiation object and add to the current macro
2060 // instantiation stack.
2061 MacroInstantiation *MI = new MacroInstantiation(
2062 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2063 ActiveMacros.push_back(MI);
2065 // Jump to the macro instantiation and prime the lexer.
2066 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2067 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2073 void AsmParser::handleMacroExit() {
2074 // Jump to the EndOfStatement we should return to, and consume it.
2075 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2078 // Pop the instantiation entry.
2079 delete ActiveMacros.back();
2080 ActiveMacros.pop_back();
2083 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2084 switch (Value->getKind()) {
2085 case MCExpr::Binary: {
2086 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2087 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2089 case MCExpr::Target:
2090 case MCExpr::Constant:
2092 case MCExpr::SymbolRef: {
2094 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2096 return isUsedIn(Sym, S.getVariableValue());
2100 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2103 llvm_unreachable("Unknown expr kind!");
2106 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2108 // FIXME: Use better location, we should use proper tokens.
2109 SMLoc EqualLoc = Lexer.getLoc();
2111 const MCExpr *Value;
2112 if (parseExpression(Value))
2115 // Note: we don't count b as used in "a = b". This is to allow
2119 if (Lexer.isNot(AsmToken::EndOfStatement))
2120 return TokError("unexpected token in assignment");
2122 // Error on assignment to '.'.
2124 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2125 "(use '.space' or '.org').)"));
2128 // Eat the end of statement marker.
2131 // Validate that the LHS is allowed to be a variable (either it has not been
2132 // used as a symbol, or it is an absolute symbol).
2133 MCSymbol *Sym = getContext().LookupSymbol(Name);
2135 // Diagnose assignment to a label.
2137 // FIXME: Diagnostics. Note the location of the definition as a label.
2138 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2139 if (isUsedIn(Sym, Value))
2140 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2141 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2142 ; // Allow redefinitions of undefined symbols only used in directives.
2143 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2144 ; // Allow redefinitions of variables that haven't yet been used.
2145 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2146 return Error(EqualLoc, "redefinition of '" + Name + "'");
2147 else if (!Sym->isVariable())
2148 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2149 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2150 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2153 // Don't count these checks as uses.
2154 Sym->setUsed(false);
2156 Sym = getContext().GetOrCreateSymbol(Name);
2158 // FIXME: Handle '.'.
2160 // Do the assignment.
2161 Out.EmitAssignment(Sym, Value);
2163 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2168 /// parseIdentifier:
2171 bool AsmParser::parseIdentifier(StringRef &Res) {
2172 // The assembler has relaxed rules for accepting identifiers, in particular we
2173 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2174 // separate tokens. At this level, we have already lexed so we cannot (currently)
2175 // handle this as a context dependent token, instead we detect adjacent tokens
2176 // and return the combined identifier.
2177 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2178 SMLoc PrefixLoc = getLexer().getLoc();
2180 // Consume the prefix character, and check for a following identifier.
2182 if (Lexer.isNot(AsmToken::Identifier))
2185 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2186 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2189 // Construct the joined identifier and consume the token.
2191 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2196 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2199 Res = getTok().getIdentifier();
2201 Lex(); // Consume the identifier token.
2206 /// parseDirectiveSet:
2207 /// ::= .equ identifier ',' expression
2208 /// ::= .equiv identifier ',' expression
2209 /// ::= .set identifier ',' expression
2210 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2213 if (parseIdentifier(Name))
2214 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2216 if (getLexer().isNot(AsmToken::Comma))
2217 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2220 return parseAssignment(Name, allow_redef, true);
2223 bool AsmParser::parseEscapedString(std::string &Data) {
2224 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2227 StringRef Str = getTok().getStringContents();
2228 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2229 if (Str[i] != '\\') {
2234 // Recognize escaped characters. Note that this escape semantics currently
2235 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2238 return TokError("unexpected backslash at end of string");
2240 // Recognize octal sequences.
2241 if ((unsigned)(Str[i] - '0') <= 7) {
2242 // Consume up to three octal characters.
2243 unsigned Value = Str[i] - '0';
2245 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2247 Value = Value * 8 + (Str[i] - '0');
2249 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2251 Value = Value * 8 + (Str[i] - '0');
2256 return TokError("invalid octal escape sequence (out of range)");
2258 Data += (unsigned char)Value;
2262 // Otherwise recognize individual escapes.
2265 // Just reject invalid escape sequences for now.
2266 return TokError("invalid escape sequence (unrecognized character)");
2268 case 'b': Data += '\b'; break;
2269 case 'f': Data += '\f'; break;
2270 case 'n': Data += '\n'; break;
2271 case 'r': Data += '\r'; break;
2272 case 't': Data += '\t'; break;
2273 case '"': Data += '"'; break;
2274 case '\\': Data += '\\'; break;
2281 /// parseDirectiveAscii:
2282 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2283 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2284 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2285 checkForValidSection();
2288 if (getLexer().isNot(AsmToken::String))
2289 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2292 if (parseEscapedString(Data))
2295 getStreamer().EmitBytes(Data);
2297 getStreamer().EmitBytes(StringRef("\0", 1));
2301 if (getLexer().is(AsmToken::EndOfStatement))
2304 if (getLexer().isNot(AsmToken::Comma))
2305 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2314 /// parseDirectiveValue
2315 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2316 bool AsmParser::parseDirectiveValue(unsigned Size) {
2317 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2318 checkForValidSection();
2321 const MCExpr *Value;
2322 SMLoc ExprLoc = getLexer().getLoc();
2323 if (parseExpression(Value))
2326 // Special case constant expressions to match code generator.
2327 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2328 assert(Size <= 8 && "Invalid size");
2329 uint64_t IntValue = MCE->getValue();
2330 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2331 return Error(ExprLoc, "literal value out of range for directive");
2332 getStreamer().EmitIntValue(IntValue, Size);
2334 getStreamer().EmitValue(Value, Size);
2336 if (getLexer().is(AsmToken::EndOfStatement))
2339 // FIXME: Improve diagnostic.
2340 if (getLexer().isNot(AsmToken::Comma))
2341 return TokError("unexpected token in directive");
2350 /// ParseDirectiveOctaValue
2351 /// ::= .octa [ hexconstant (, hexconstant)* ]
2352 bool AsmParser::parseDirectiveOctaValue() {
2353 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2354 checkForValidSection();
2357 if (Lexer.getKind() == AsmToken::Error)
2359 if (Lexer.getKind() != AsmToken::Integer &&
2360 Lexer.getKind() != AsmToken::BigNum)
2361 return TokError("unknown token in expression");
2363 SMLoc ExprLoc = getLexer().getLoc();
2364 APInt IntValue = getTok().getAPIntVal();
2368 if (IntValue.isIntN(64)) {
2370 lo = IntValue.getZExtValue();
2371 } else if (IntValue.isIntN(128)) {
2372 // It might actually have more than 128 bits, but the top ones are zero.
2373 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2374 lo = IntValue.getLoBits(64).getZExtValue();
2376 return Error(ExprLoc, "literal value out of range for directive");
2378 if (MAI.isLittleEndian()) {
2379 getStreamer().EmitIntValue(lo, 8);
2380 getStreamer().EmitIntValue(hi, 8);
2382 getStreamer().EmitIntValue(hi, 8);
2383 getStreamer().EmitIntValue(lo, 8);
2386 if (getLexer().is(AsmToken::EndOfStatement))
2389 // FIXME: Improve diagnostic.
2390 if (getLexer().isNot(AsmToken::Comma))
2391 return TokError("unexpected token in directive");
2400 /// parseDirectiveRealValue
2401 /// ::= (.single | .double) [ expression (, expression)* ]
2402 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2403 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2404 checkForValidSection();
2407 // We don't truly support arithmetic on floating point expressions, so we
2408 // have to manually parse unary prefixes.
2410 if (getLexer().is(AsmToken::Minus)) {
2413 } else if (getLexer().is(AsmToken::Plus))
2416 if (getLexer().isNot(AsmToken::Integer) &&
2417 getLexer().isNot(AsmToken::Real) &&
2418 getLexer().isNot(AsmToken::Identifier))
2419 return TokError("unexpected token in directive");
2421 // Convert to an APFloat.
2422 APFloat Value(Semantics);
2423 StringRef IDVal = getTok().getString();
2424 if (getLexer().is(AsmToken::Identifier)) {
2425 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2426 Value = APFloat::getInf(Semantics);
2427 else if (!IDVal.compare_lower("nan"))
2428 Value = APFloat::getNaN(Semantics, false, ~0);
2430 return TokError("invalid floating point literal");
2431 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2432 APFloat::opInvalidOp)
2433 return TokError("invalid floating point literal");
2437 // Consume the numeric token.
2440 // Emit the value as an integer.
2441 APInt AsInt = Value.bitcastToAPInt();
2442 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2443 AsInt.getBitWidth() / 8);
2445 if (getLexer().is(AsmToken::EndOfStatement))
2448 if (getLexer().isNot(AsmToken::Comma))
2449 return TokError("unexpected token in directive");
2458 /// parseDirectiveZero
2459 /// ::= .zero expression
2460 bool AsmParser::parseDirectiveZero() {
2461 checkForValidSection();
2464 if (parseAbsoluteExpression(NumBytes))
2468 if (getLexer().is(AsmToken::Comma)) {
2470 if (parseAbsoluteExpression(Val))
2474 if (getLexer().isNot(AsmToken::EndOfStatement))
2475 return TokError("unexpected token in '.zero' directive");
2479 getStreamer().EmitFill(NumBytes, Val);
2484 /// parseDirectiveFill
2485 /// ::= .fill expression [ , expression [ , expression ] ]
2486 bool AsmParser::parseDirectiveFill() {
2487 checkForValidSection();
2489 SMLoc RepeatLoc = getLexer().getLoc();
2491 if (parseAbsoluteExpression(NumValues))
2494 if (NumValues < 0) {
2496 "'.fill' directive with negative repeat count has no effect");
2500 int64_t FillSize = 1;
2501 int64_t FillExpr = 0;
2503 SMLoc SizeLoc, ExprLoc;
2504 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2505 if (getLexer().isNot(AsmToken::Comma))
2506 return TokError("unexpected token in '.fill' directive");
2509 SizeLoc = getLexer().getLoc();
2510 if (parseAbsoluteExpression(FillSize))
2513 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2514 if (getLexer().isNot(AsmToken::Comma))
2515 return TokError("unexpected token in '.fill' directive");
2518 ExprLoc = getLexer().getLoc();
2519 if (parseAbsoluteExpression(FillExpr))
2522 if (getLexer().isNot(AsmToken::EndOfStatement))
2523 return TokError("unexpected token in '.fill' directive");
2530 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2534 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2538 if (!isUInt<32>(FillExpr) && FillSize > 4)
2539 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2541 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2542 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2544 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2545 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2546 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2552 /// parseDirectiveOrg
2553 /// ::= .org expression [ , expression ]
2554 bool AsmParser::parseDirectiveOrg() {
2555 checkForValidSection();
2557 const MCExpr *Offset;
2558 SMLoc Loc = getTok().getLoc();
2559 if (parseExpression(Offset))
2562 // Parse optional fill expression.
2563 int64_t FillExpr = 0;
2564 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2565 if (getLexer().isNot(AsmToken::Comma))
2566 return TokError("unexpected token in '.org' directive");
2569 if (parseAbsoluteExpression(FillExpr))
2572 if (getLexer().isNot(AsmToken::EndOfStatement))
2573 return TokError("unexpected token in '.org' directive");
2578 // Only limited forms of relocatable expressions are accepted here, it
2579 // has to be relative to the current section. The streamer will return
2580 // 'true' if the expression wasn't evaluatable.
2581 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2582 return Error(Loc, "expected assembly-time absolute expression");
2587 /// parseDirectiveAlign
2588 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2589 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2590 checkForValidSection();
2592 SMLoc AlignmentLoc = getLexer().getLoc();
2594 if (parseAbsoluteExpression(Alignment))
2598 bool HasFillExpr = false;
2599 int64_t FillExpr = 0;
2600 int64_t MaxBytesToFill = 0;
2601 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2602 if (getLexer().isNot(AsmToken::Comma))
2603 return TokError("unexpected token in directive");
2606 // The fill expression can be omitted while specifying a maximum number of
2607 // alignment bytes, e.g:
2609 if (getLexer().isNot(AsmToken::Comma)) {
2611 if (parseAbsoluteExpression(FillExpr))
2615 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2616 if (getLexer().isNot(AsmToken::Comma))
2617 return TokError("unexpected token in directive");
2620 MaxBytesLoc = getLexer().getLoc();
2621 if (parseAbsoluteExpression(MaxBytesToFill))
2624 if (getLexer().isNot(AsmToken::EndOfStatement))
2625 return TokError("unexpected token in directive");
2634 // Compute alignment in bytes.
2636 // FIXME: Diagnose overflow.
2637 if (Alignment >= 32) {
2638 Error(AlignmentLoc, "invalid alignment value");
2642 Alignment = 1ULL << Alignment;
2644 // Reject alignments that aren't a power of two, for gas compatibility.
2645 if (!isPowerOf2_64(Alignment))
2646 Error(AlignmentLoc, "alignment must be a power of 2");
2649 // Diagnose non-sensical max bytes to align.
2650 if (MaxBytesLoc.isValid()) {
2651 if (MaxBytesToFill < 1) {
2652 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2653 "many bytes, ignoring maximum bytes expression");
2657 if (MaxBytesToFill >= Alignment) {
2658 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2664 // Check whether we should use optimal code alignment for this .align
2666 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2667 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2668 ValueSize == 1 && UseCodeAlign) {
2669 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2671 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2672 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2679 /// parseDirectiveFile
2680 /// ::= .file [number] filename
2681 /// ::= .file number directory filename
2682 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2683 // FIXME: I'm not sure what this is.
2684 int64_t FileNumber = -1;
2685 SMLoc FileNumberLoc = getLexer().getLoc();
2686 if (getLexer().is(AsmToken::Integer)) {
2687 FileNumber = getTok().getIntVal();
2691 return TokError("file number less than one");
2694 if (getLexer().isNot(AsmToken::String))
2695 return TokError("unexpected token in '.file' directive");
2697 // Usually the directory and filename together, otherwise just the directory.
2698 // Allow the strings to have escaped octal character sequence.
2699 std::string Path = getTok().getString();
2700 if (parseEscapedString(Path))
2704 StringRef Directory;
2706 std::string FilenameData;
2707 if (getLexer().is(AsmToken::String)) {
2708 if (FileNumber == -1)
2709 return TokError("explicit path specified, but no file number");
2710 if (parseEscapedString(FilenameData))
2712 Filename = FilenameData;
2719 if (getLexer().isNot(AsmToken::EndOfStatement))
2720 return TokError("unexpected token in '.file' directive");
2722 if (FileNumber == -1)
2723 getStreamer().EmitFileDirective(Filename);
2725 if (getContext().getGenDwarfForAssembly() == true)
2727 "input can't have .file dwarf directives when -g is "
2728 "used to generate dwarf debug info for assembly code");
2730 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2731 Error(FileNumberLoc, "file number already allocated");
2737 /// parseDirectiveLine
2738 /// ::= .line [number]
2739 bool AsmParser::parseDirectiveLine() {
2740 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2741 if (getLexer().isNot(AsmToken::Integer))
2742 return TokError("unexpected token in '.line' directive");
2744 int64_t LineNumber = getTok().getIntVal();
2748 // FIXME: Do something with the .line.
2751 if (getLexer().isNot(AsmToken::EndOfStatement))
2752 return TokError("unexpected token in '.line' directive");
2757 /// parseDirectiveLoc
2758 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2759 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2760 /// The first number is a file number, must have been previously assigned with
2761 /// a .file directive, the second number is the line number and optionally the
2762 /// third number is a column position (zero if not specified). The remaining
2763 /// optional items are .loc sub-directives.
2764 bool AsmParser::parseDirectiveLoc() {
2765 if (getLexer().isNot(AsmToken::Integer))
2766 return TokError("unexpected token in '.loc' directive");
2767 int64_t FileNumber = getTok().getIntVal();
2769 return TokError("file number less than one in '.loc' directive");
2770 if (!getContext().isValidDwarfFileNumber(FileNumber))
2771 return TokError("unassigned file number in '.loc' directive");
2774 int64_t LineNumber = 0;
2775 if (getLexer().is(AsmToken::Integer)) {
2776 LineNumber = getTok().getIntVal();
2778 return TokError("line number less than zero in '.loc' directive");
2782 int64_t ColumnPos = 0;
2783 if (getLexer().is(AsmToken::Integer)) {
2784 ColumnPos = getTok().getIntVal();
2786 return TokError("column position less than zero in '.loc' directive");
2790 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2792 int64_t Discriminator = 0;
2793 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2795 if (getLexer().is(AsmToken::EndOfStatement))
2799 SMLoc Loc = getTok().getLoc();
2800 if (parseIdentifier(Name))
2801 return TokError("unexpected token in '.loc' directive");
2803 if (Name == "basic_block")
2804 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2805 else if (Name == "prologue_end")
2806 Flags |= DWARF2_FLAG_PROLOGUE_END;
2807 else if (Name == "epilogue_begin")
2808 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2809 else if (Name == "is_stmt") {
2810 Loc = getTok().getLoc();
2811 const MCExpr *Value;
2812 if (parseExpression(Value))
2814 // The expression must be the constant 0 or 1.
2815 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2816 int Value = MCE->getValue();
2818 Flags &= ~DWARF2_FLAG_IS_STMT;
2819 else if (Value == 1)
2820 Flags |= DWARF2_FLAG_IS_STMT;
2822 return Error(Loc, "is_stmt value not 0 or 1");
2824 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2826 } else if (Name == "isa") {
2827 Loc = getTok().getLoc();
2828 const MCExpr *Value;
2829 if (parseExpression(Value))
2831 // The expression must be a constant greater or equal to 0.
2832 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2833 int Value = MCE->getValue();
2835 return Error(Loc, "isa number less than zero");
2838 return Error(Loc, "isa number not a constant value");
2840 } else if (Name == "discriminator") {
2841 if (parseAbsoluteExpression(Discriminator))
2844 return Error(Loc, "unknown sub-directive in '.loc' directive");
2847 if (getLexer().is(AsmToken::EndOfStatement))
2852 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2853 Isa, Discriminator, StringRef());
2858 /// parseDirectiveStabs
2859 /// ::= .stabs string, number, number, number
2860 bool AsmParser::parseDirectiveStabs() {
2861 return TokError("unsupported directive '.stabs'");
2864 /// parseDirectiveCFISections
2865 /// ::= .cfi_sections section [, section]
2866 bool AsmParser::parseDirectiveCFISections() {
2871 if (parseIdentifier(Name))
2872 return TokError("Expected an identifier");
2874 if (Name == ".eh_frame")
2876 else if (Name == ".debug_frame")
2879 if (getLexer().is(AsmToken::Comma)) {
2882 if (parseIdentifier(Name))
2883 return TokError("Expected an identifier");
2885 if (Name == ".eh_frame")
2887 else if (Name == ".debug_frame")
2891 getStreamer().EmitCFISections(EH, Debug);
2895 /// parseDirectiveCFIStartProc
2896 /// ::= .cfi_startproc [simple]
2897 bool AsmParser::parseDirectiveCFIStartProc() {
2899 if (getLexer().isNot(AsmToken::EndOfStatement))
2900 if (parseIdentifier(Simple) || Simple != "simple")
2901 return TokError("unexpected token in .cfi_startproc directive");
2903 getStreamer().EmitCFIStartProc(!Simple.empty());
2907 /// parseDirectiveCFIEndProc
2908 /// ::= .cfi_endproc
2909 bool AsmParser::parseDirectiveCFIEndProc() {
2910 getStreamer().EmitCFIEndProc();
2914 /// \brief parse register name or number.
2915 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2916 SMLoc DirectiveLoc) {
2919 if (getLexer().isNot(AsmToken::Integer)) {
2920 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2922 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2924 return parseAbsoluteExpression(Register);
2929 /// parseDirectiveCFIDefCfa
2930 /// ::= .cfi_def_cfa register, offset
2931 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2932 int64_t Register = 0;
2933 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2936 if (getLexer().isNot(AsmToken::Comma))
2937 return TokError("unexpected token in directive");
2941 if (parseAbsoluteExpression(Offset))
2944 getStreamer().EmitCFIDefCfa(Register, Offset);
2948 /// parseDirectiveCFIDefCfaOffset
2949 /// ::= .cfi_def_cfa_offset offset
2950 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2952 if (parseAbsoluteExpression(Offset))
2955 getStreamer().EmitCFIDefCfaOffset(Offset);
2959 /// parseDirectiveCFIRegister
2960 /// ::= .cfi_register register, register
2961 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2962 int64_t Register1 = 0;
2963 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2966 if (getLexer().isNot(AsmToken::Comma))
2967 return TokError("unexpected token in directive");
2970 int64_t Register2 = 0;
2971 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2974 getStreamer().EmitCFIRegister(Register1, Register2);
2978 /// parseDirectiveCFIWindowSave
2979 /// ::= .cfi_window_save
2980 bool AsmParser::parseDirectiveCFIWindowSave() {
2981 getStreamer().EmitCFIWindowSave();
2985 /// parseDirectiveCFIAdjustCfaOffset
2986 /// ::= .cfi_adjust_cfa_offset adjustment
2987 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2988 int64_t Adjustment = 0;
2989 if (parseAbsoluteExpression(Adjustment))
2992 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2996 /// parseDirectiveCFIDefCfaRegister
2997 /// ::= .cfi_def_cfa_register register
2998 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2999 int64_t Register = 0;
3000 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3003 getStreamer().EmitCFIDefCfaRegister(Register);
3007 /// parseDirectiveCFIOffset
3008 /// ::= .cfi_offset register, offset
3009 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3010 int64_t Register = 0;
3013 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3016 if (getLexer().isNot(AsmToken::Comma))
3017 return TokError("unexpected token in directive");
3020 if (parseAbsoluteExpression(Offset))
3023 getStreamer().EmitCFIOffset(Register, Offset);
3027 /// parseDirectiveCFIRelOffset
3028 /// ::= .cfi_rel_offset register, offset
3029 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3030 int64_t Register = 0;
3032 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3035 if (getLexer().isNot(AsmToken::Comma))
3036 return TokError("unexpected token in directive");
3040 if (parseAbsoluteExpression(Offset))
3043 getStreamer().EmitCFIRelOffset(Register, Offset);
3047 static bool isValidEncoding(int64_t Encoding) {
3048 if (Encoding & ~0xff)
3051 if (Encoding == dwarf::DW_EH_PE_omit)
3054 const unsigned Format = Encoding & 0xf;
3055 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3056 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3057 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3058 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3061 const unsigned Application = Encoding & 0x70;
3062 if (Application != dwarf::DW_EH_PE_absptr &&
3063 Application != dwarf::DW_EH_PE_pcrel)
3069 /// parseDirectiveCFIPersonalityOrLsda
3070 /// IsPersonality true for cfi_personality, false for cfi_lsda
3071 /// ::= .cfi_personality encoding, [symbol_name]
3072 /// ::= .cfi_lsda encoding, [symbol_name]
3073 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3074 int64_t Encoding = 0;
3075 if (parseAbsoluteExpression(Encoding))
3077 if (Encoding == dwarf::DW_EH_PE_omit)
3080 if (!isValidEncoding(Encoding))
3081 return TokError("unsupported encoding.");
3083 if (getLexer().isNot(AsmToken::Comma))
3084 return TokError("unexpected token in directive");
3088 if (parseIdentifier(Name))
3089 return TokError("expected identifier in directive");
3091 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3094 getStreamer().EmitCFIPersonality(Sym, Encoding);
3096 getStreamer().EmitCFILsda(Sym, Encoding);
3100 /// parseDirectiveCFIRememberState
3101 /// ::= .cfi_remember_state
3102 bool AsmParser::parseDirectiveCFIRememberState() {
3103 getStreamer().EmitCFIRememberState();
3107 /// parseDirectiveCFIRestoreState
3108 /// ::= .cfi_remember_state
3109 bool AsmParser::parseDirectiveCFIRestoreState() {
3110 getStreamer().EmitCFIRestoreState();
3114 /// parseDirectiveCFISameValue
3115 /// ::= .cfi_same_value register
3116 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3117 int64_t Register = 0;
3119 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3122 getStreamer().EmitCFISameValue(Register);
3126 /// parseDirectiveCFIRestore
3127 /// ::= .cfi_restore register
3128 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3129 int64_t Register = 0;
3130 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3133 getStreamer().EmitCFIRestore(Register);
3137 /// parseDirectiveCFIEscape
3138 /// ::= .cfi_escape expression[,...]
3139 bool AsmParser::parseDirectiveCFIEscape() {
3142 if (parseAbsoluteExpression(CurrValue))
3145 Values.push_back((uint8_t)CurrValue);
3147 while (getLexer().is(AsmToken::Comma)) {
3150 if (parseAbsoluteExpression(CurrValue))
3153 Values.push_back((uint8_t)CurrValue);
3156 getStreamer().EmitCFIEscape(Values);
3160 /// parseDirectiveCFISignalFrame
3161 /// ::= .cfi_signal_frame
3162 bool AsmParser::parseDirectiveCFISignalFrame() {
3163 if (getLexer().isNot(AsmToken::EndOfStatement))
3164 return Error(getLexer().getLoc(),
3165 "unexpected token in '.cfi_signal_frame'");
3167 getStreamer().EmitCFISignalFrame();
3171 /// parseDirectiveCFIUndefined
3172 /// ::= .cfi_undefined register
3173 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3174 int64_t Register = 0;
3176 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3179 getStreamer().EmitCFIUndefined(Register);
3183 /// parseDirectiveMacrosOnOff
3186 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3187 if (getLexer().isNot(AsmToken::EndOfStatement))
3188 return Error(getLexer().getLoc(),
3189 "unexpected token in '" + Directive + "' directive");
3191 setMacrosEnabled(Directive == ".macros_on");
3195 /// parseDirectiveMacro
3196 /// ::= .macro name[,] [parameters]
3197 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3199 if (parseIdentifier(Name))
3200 return TokError("expected identifier in '.macro' directive");
3202 if (getLexer().is(AsmToken::Comma))
3205 MCAsmMacroParameters Parameters;
3206 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3207 MCAsmMacroParameter Parameter;
3208 if (parseIdentifier(Parameter.first))
3209 return TokError("expected identifier in '.macro' directive");
3211 if (getLexer().is(AsmToken::Equal)) {
3213 if (parseMacroArgument(Parameter.second))
3217 Parameters.push_back(Parameter);
3219 if (getLexer().is(AsmToken::Comma))
3223 // Eat the end of statement.
3226 AsmToken EndToken, StartToken = getTok();
3227 unsigned MacroDepth = 0;
3229 // Lex the macro definition.
3231 // Check whether we have reached the end of the file.
3232 if (getLexer().is(AsmToken::Eof))
3233 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3235 // Otherwise, check whether we have reach the .endmacro.
3236 if (getLexer().is(AsmToken::Identifier)) {
3237 if (getTok().getIdentifier() == ".endm" ||
3238 getTok().getIdentifier() == ".endmacro") {
3239 if (MacroDepth == 0) { // Outermost macro.
3240 EndToken = getTok();
3242 if (getLexer().isNot(AsmToken::EndOfStatement))
3243 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3247 // Otherwise we just found the end of an inner macro.
3250 } else if (getTok().getIdentifier() == ".macro") {
3251 // We allow nested macros. Those aren't instantiated until the outermost
3252 // macro is expanded so just ignore them for now.
3257 // Otherwise, scan til the end of the statement.
3258 eatToEndOfStatement();
3261 if (lookupMacro(Name)) {
3262 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3265 const char *BodyStart = StartToken.getLoc().getPointer();
3266 const char *BodyEnd = EndToken.getLoc().getPointer();
3267 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3268 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3269 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3273 /// checkForBadMacro
3275 /// With the support added for named parameters there may be code out there that
3276 /// is transitioning from positional parameters. In versions of gas that did
3277 /// not support named parameters they would be ignored on the macro definition.
3278 /// But to support both styles of parameters this is not possible so if a macro
3279 /// definition has named parameters but does not use them and has what appears
3280 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3281 /// warning that the positional parameter found in body which have no effect.
3282 /// Hoping the developer will either remove the named parameters from the macro
3283 /// definition so the positional parameters get used if that was what was
3284 /// intended or change the macro to use the named parameters. It is possible
3285 /// this warning will trigger when the none of the named parameters are used
3286 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3287 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3289 ArrayRef<MCAsmMacroParameter> Parameters) {
3290 // If this macro is not defined with named parameters the warning we are
3291 // checking for here doesn't apply.
3292 unsigned NParameters = Parameters.size();
3293 if (NParameters == 0)
3296 bool NamedParametersFound = false;
3297 bool PositionalParametersFound = false;
3299 // Look at the body of the macro for use of both the named parameters and what
3300 // are likely to be positional parameters. This is what expandMacro() is
3301 // doing when it finds the parameters in the body.
3302 while (!Body.empty()) {
3303 // Scan for the next possible parameter.
3304 std::size_t End = Body.size(), Pos = 0;
3305 for (; Pos != End; ++Pos) {
3306 // Check for a substitution or escape.
3307 // This macro is defined with parameters, look for \foo, \bar, etc.
3308 if (Body[Pos] == '\\' && Pos + 1 != End)
3311 // This macro should have parameters, but look for $0, $1, ..., $n too.
3312 if (Body[Pos] != '$' || Pos + 1 == End)
3314 char Next = Body[Pos + 1];
3315 if (Next == '$' || Next == 'n' ||
3316 isdigit(static_cast<unsigned char>(Next)))
3320 // Check if we reached the end.
3324 if (Body[Pos] == '$') {
3325 switch (Body[Pos + 1]) {
3330 // $n => number of arguments
3332 PositionalParametersFound = true;
3335 // $[0-9] => argument
3337 PositionalParametersFound = true;
3343 unsigned I = Pos + 1;
3344 while (isIdentifierChar(Body[I]) && I + 1 != End)
3347 const char *Begin = Body.data() + Pos + 1;
3348 StringRef Argument(Begin, I - (Pos + 1));
3350 for (; Index < NParameters; ++Index)
3351 if (Parameters[Index].first == Argument)
3354 if (Index == NParameters) {
3355 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3361 NamedParametersFound = true;
3362 Pos += 1 + Argument.size();
3365 // Update the scan point.
3366 Body = Body.substr(Pos);
3369 if (!NamedParametersFound && PositionalParametersFound)
3370 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3371 "used in macro body, possible positional parameter "
3372 "found in body which will have no effect");
3375 /// parseDirectiveEndMacro
3378 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3379 if (getLexer().isNot(AsmToken::EndOfStatement))
3380 return TokError("unexpected token in '" + Directive + "' directive");
3382 // If we are inside a macro instantiation, terminate the current
3384 if (isInsideMacroInstantiation()) {
3389 // Otherwise, this .endmacro is a stray entry in the file; well formed
3390 // .endmacro directives are handled during the macro definition parsing.
3391 return TokError("unexpected '" + Directive + "' in file, "
3392 "no current macro definition");
3395 /// parseDirectivePurgeMacro
3397 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3399 if (parseIdentifier(Name))
3400 return TokError("expected identifier in '.purgem' directive");
3402 if (getLexer().isNot(AsmToken::EndOfStatement))
3403 return TokError("unexpected token in '.purgem' directive");
3405 if (!lookupMacro(Name))
3406 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3408 undefineMacro(Name);
3412 /// parseDirectiveBundleAlignMode
3413 /// ::= {.bundle_align_mode} expression
3414 bool AsmParser::parseDirectiveBundleAlignMode() {
3415 checkForValidSection();
3417 // Expect a single argument: an expression that evaluates to a constant
3418 // in the inclusive range 0-30.
3419 SMLoc ExprLoc = getLexer().getLoc();
3420 int64_t AlignSizePow2;
3421 if (parseAbsoluteExpression(AlignSizePow2))
3423 else if (getLexer().isNot(AsmToken::EndOfStatement))
3424 return TokError("unexpected token after expression in"
3425 " '.bundle_align_mode' directive");
3426 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3427 return Error(ExprLoc,
3428 "invalid bundle alignment size (expected between 0 and 30)");
3432 // Because of AlignSizePow2's verified range we can safely truncate it to
3434 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3438 /// parseDirectiveBundleLock
3439 /// ::= {.bundle_lock} [align_to_end]
3440 bool AsmParser::parseDirectiveBundleLock() {
3441 checkForValidSection();
3442 bool AlignToEnd = false;
3444 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3446 SMLoc Loc = getTok().getLoc();
3447 const char *kInvalidOptionError =
3448 "invalid option for '.bundle_lock' directive";
3450 if (parseIdentifier(Option))
3451 return Error(Loc, kInvalidOptionError);
3453 if (Option != "align_to_end")
3454 return Error(Loc, kInvalidOptionError);
3455 else if (getLexer().isNot(AsmToken::EndOfStatement))
3457 "unexpected token after '.bundle_lock' directive option");
3463 getStreamer().EmitBundleLock(AlignToEnd);
3467 /// parseDirectiveBundleLock
3468 /// ::= {.bundle_lock}
3469 bool AsmParser::parseDirectiveBundleUnlock() {
3470 checkForValidSection();
3472 if (getLexer().isNot(AsmToken::EndOfStatement))
3473 return TokError("unexpected token in '.bundle_unlock' directive");
3476 getStreamer().EmitBundleUnlock();
3480 /// parseDirectiveSpace
3481 /// ::= (.skip | .space) expression [ , expression ]
3482 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3483 checkForValidSection();
3486 if (parseAbsoluteExpression(NumBytes))
3489 int64_t FillExpr = 0;
3490 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3491 if (getLexer().isNot(AsmToken::Comma))
3492 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3495 if (parseAbsoluteExpression(FillExpr))
3498 if (getLexer().isNot(AsmToken::EndOfStatement))
3499 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3505 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3508 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3509 getStreamer().EmitFill(NumBytes, FillExpr);
3514 /// parseDirectiveLEB128
3515 /// ::= (.sleb128 | .uleb128) expression
3516 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3517 checkForValidSection();
3518 const MCExpr *Value;
3520 if (parseExpression(Value))
3523 if (getLexer().isNot(AsmToken::EndOfStatement))
3524 return TokError("unexpected token in directive");
3527 getStreamer().EmitSLEB128Value(Value);
3529 getStreamer().EmitULEB128Value(Value);
3534 /// parseDirectiveSymbolAttribute
3535 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3536 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3537 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3540 SMLoc Loc = getTok().getLoc();
3542 if (parseIdentifier(Name))
3543 return Error(Loc, "expected identifier in directive");
3545 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3547 // Assembler local symbols don't make any sense here. Complain loudly.
3548 if (Sym->isTemporary())
3549 return Error(Loc, "non-local symbol required in directive");
3551 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3552 return Error(Loc, "unable to emit symbol attribute");
3554 if (getLexer().is(AsmToken::EndOfStatement))
3557 if (getLexer().isNot(AsmToken::Comma))
3558 return TokError("unexpected token in directive");
3567 /// parseDirectiveComm
3568 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3569 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3570 checkForValidSection();
3572 SMLoc IDLoc = getLexer().getLoc();
3574 if (parseIdentifier(Name))
3575 return TokError("expected identifier in directive");
3577 // Handle the identifier as the key symbol.
3578 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3580 if (getLexer().isNot(AsmToken::Comma))
3581 return TokError("unexpected token in directive");
3585 SMLoc SizeLoc = getLexer().getLoc();
3586 if (parseAbsoluteExpression(Size))
3589 int64_t Pow2Alignment = 0;
3590 SMLoc Pow2AlignmentLoc;
3591 if (getLexer().is(AsmToken::Comma)) {
3593 Pow2AlignmentLoc = getLexer().getLoc();
3594 if (parseAbsoluteExpression(Pow2Alignment))
3597 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3598 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3599 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3601 // If this target takes alignments in bytes (not log) validate and convert.
3602 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3603 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3604 if (!isPowerOf2_64(Pow2Alignment))
3605 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3606 Pow2Alignment = Log2_64(Pow2Alignment);
3610 if (getLexer().isNot(AsmToken::EndOfStatement))
3611 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3615 // NOTE: a size of zero for a .comm should create a undefined symbol
3616 // but a size of .lcomm creates a bss symbol of size zero.
3618 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3619 "be less than zero");
3621 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3622 // may internally end up wanting an alignment in bytes.
3623 // FIXME: Diagnose overflow.
3624 if (Pow2Alignment < 0)
3625 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3626 "alignment, can't be less than zero");
3628 if (!Sym->isUndefined())
3629 return Error(IDLoc, "invalid symbol redefinition");
3631 // Create the Symbol as a common or local common with Size and Pow2Alignment
3633 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3637 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3641 /// parseDirectiveAbort
3642 /// ::= .abort [... message ...]
3643 bool AsmParser::parseDirectiveAbort() {
3644 // FIXME: Use loc from directive.
3645 SMLoc Loc = getLexer().getLoc();
3647 StringRef Str = parseStringToEndOfStatement();
3648 if (getLexer().isNot(AsmToken::EndOfStatement))
3649 return TokError("unexpected token in '.abort' directive");
3654 Error(Loc, ".abort detected. Assembly stopping.");
3656 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3657 // FIXME: Actually abort assembly here.
3662 /// parseDirectiveInclude
3663 /// ::= .include "filename"
3664 bool AsmParser::parseDirectiveInclude() {
3665 if (getLexer().isNot(AsmToken::String))
3666 return TokError("expected string in '.include' directive");
3668 // Allow the strings to have escaped octal character sequence.
3669 std::string Filename;
3670 if (parseEscapedString(Filename))
3672 SMLoc IncludeLoc = getLexer().getLoc();
3675 if (getLexer().isNot(AsmToken::EndOfStatement))
3676 return TokError("unexpected token in '.include' directive");
3678 // Attempt to switch the lexer to the included file before consuming the end
3679 // of statement to avoid losing it when we switch.
3680 if (enterIncludeFile(Filename)) {
3681 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3688 /// parseDirectiveIncbin
3689 /// ::= .incbin "filename"
3690 bool AsmParser::parseDirectiveIncbin() {
3691 if (getLexer().isNot(AsmToken::String))
3692 return TokError("expected string in '.incbin' directive");
3694 // Allow the strings to have escaped octal character sequence.
3695 std::string Filename;
3696 if (parseEscapedString(Filename))
3698 SMLoc IncbinLoc = getLexer().getLoc();
3701 if (getLexer().isNot(AsmToken::EndOfStatement))
3702 return TokError("unexpected token in '.incbin' directive");
3704 // Attempt to process the included file.
3705 if (processIncbinFile(Filename)) {
3706 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3713 /// parseDirectiveIf
3714 /// ::= .if expression
3715 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3716 TheCondStack.push_back(TheCondState);
3717 TheCondState.TheCond = AsmCond::IfCond;
3718 if (TheCondState.Ignore) {
3719 eatToEndOfStatement();
3722 if (parseAbsoluteExpression(ExprValue))
3725 if (getLexer().isNot(AsmToken::EndOfStatement))
3726 return TokError("unexpected token in '.if' directive");
3730 TheCondState.CondMet = ExprValue;
3731 TheCondState.Ignore = !TheCondState.CondMet;
3737 /// parseDirectiveIfb
3739 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3740 TheCondStack.push_back(TheCondState);
3741 TheCondState.TheCond = AsmCond::IfCond;
3743 if (TheCondState.Ignore) {
3744 eatToEndOfStatement();
3746 StringRef Str = parseStringToEndOfStatement();
3748 if (getLexer().isNot(AsmToken::EndOfStatement))
3749 return TokError("unexpected token in '.ifb' directive");
3753 TheCondState.CondMet = ExpectBlank == Str.empty();
3754 TheCondState.Ignore = !TheCondState.CondMet;
3760 /// parseDirectiveIfc
3761 /// ::= .ifc string1, string2
3762 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3763 TheCondStack.push_back(TheCondState);
3764 TheCondState.TheCond = AsmCond::IfCond;
3766 if (TheCondState.Ignore) {
3767 eatToEndOfStatement();
3769 StringRef Str1 = parseStringToComma();
3771 if (getLexer().isNot(AsmToken::Comma))
3772 return TokError("unexpected token in '.ifc' directive");
3776 StringRef Str2 = parseStringToEndOfStatement();
3778 if (getLexer().isNot(AsmToken::EndOfStatement))
3779 return TokError("unexpected token in '.ifc' directive");
3783 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3784 TheCondState.Ignore = !TheCondState.CondMet;
3790 /// parseDirectiveIfdef
3791 /// ::= .ifdef symbol
3792 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3794 TheCondStack.push_back(TheCondState);
3795 TheCondState.TheCond = AsmCond::IfCond;
3797 if (TheCondState.Ignore) {
3798 eatToEndOfStatement();
3800 if (parseIdentifier(Name))
3801 return TokError("expected identifier after '.ifdef'");
3805 MCSymbol *Sym = getContext().LookupSymbol(Name);
3808 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3810 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3811 TheCondState.Ignore = !TheCondState.CondMet;
3817 /// parseDirectiveElseIf
3818 /// ::= .elseif expression
3819 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3820 if (TheCondState.TheCond != AsmCond::IfCond &&
3821 TheCondState.TheCond != AsmCond::ElseIfCond)
3822 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3824 TheCondState.TheCond = AsmCond::ElseIfCond;
3826 bool LastIgnoreState = false;
3827 if (!TheCondStack.empty())
3828 LastIgnoreState = TheCondStack.back().Ignore;
3829 if (LastIgnoreState || TheCondState.CondMet) {
3830 TheCondState.Ignore = true;
3831 eatToEndOfStatement();
3834 if (parseAbsoluteExpression(ExprValue))
3837 if (getLexer().isNot(AsmToken::EndOfStatement))
3838 return TokError("unexpected token in '.elseif' directive");
3841 TheCondState.CondMet = ExprValue;
3842 TheCondState.Ignore = !TheCondState.CondMet;
3848 /// parseDirectiveElse
3850 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3851 if (getLexer().isNot(AsmToken::EndOfStatement))
3852 return TokError("unexpected token in '.else' directive");
3856 if (TheCondState.TheCond != AsmCond::IfCond &&
3857 TheCondState.TheCond != AsmCond::ElseIfCond)
3858 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3860 TheCondState.TheCond = AsmCond::ElseCond;
3861 bool LastIgnoreState = false;
3862 if (!TheCondStack.empty())
3863 LastIgnoreState = TheCondStack.back().Ignore;
3864 if (LastIgnoreState || TheCondState.CondMet)
3865 TheCondState.Ignore = true;
3867 TheCondState.Ignore = false;
3872 /// parseDirectiveEnd
3874 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3875 if (getLexer().isNot(AsmToken::EndOfStatement))
3876 return TokError("unexpected token in '.end' directive");
3880 while (Lexer.isNot(AsmToken::Eof))
3886 /// parseDirectiveEndIf
3888 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3889 if (getLexer().isNot(AsmToken::EndOfStatement))
3890 return TokError("unexpected token in '.endif' directive");
3894 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3895 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3897 if (!TheCondStack.empty()) {
3898 TheCondState = TheCondStack.back();
3899 TheCondStack.pop_back();
3905 void AsmParser::initializeDirectiveKindMap() {
3906 DirectiveKindMap[".set"] = DK_SET;
3907 DirectiveKindMap[".equ"] = DK_EQU;
3908 DirectiveKindMap[".equiv"] = DK_EQUIV;
3909 DirectiveKindMap[".ascii"] = DK_ASCII;
3910 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3911 DirectiveKindMap[".string"] = DK_STRING;
3912 DirectiveKindMap[".byte"] = DK_BYTE;
3913 DirectiveKindMap[".short"] = DK_SHORT;
3914 DirectiveKindMap[".value"] = DK_VALUE;
3915 DirectiveKindMap[".2byte"] = DK_2BYTE;
3916 DirectiveKindMap[".long"] = DK_LONG;
3917 DirectiveKindMap[".int"] = DK_INT;
3918 DirectiveKindMap[".4byte"] = DK_4BYTE;
3919 DirectiveKindMap[".quad"] = DK_QUAD;
3920 DirectiveKindMap[".8byte"] = DK_8BYTE;
3921 DirectiveKindMap[".octa"] = DK_OCTA;
3922 DirectiveKindMap[".single"] = DK_SINGLE;
3923 DirectiveKindMap[".float"] = DK_FLOAT;
3924 DirectiveKindMap[".double"] = DK_DOUBLE;
3925 DirectiveKindMap[".align"] = DK_ALIGN;
3926 DirectiveKindMap[".align32"] = DK_ALIGN32;
3927 DirectiveKindMap[".balign"] = DK_BALIGN;
3928 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3929 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3930 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3931 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3932 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3933 DirectiveKindMap[".org"] = DK_ORG;
3934 DirectiveKindMap[".fill"] = DK_FILL;
3935 DirectiveKindMap[".zero"] = DK_ZERO;
3936 DirectiveKindMap[".extern"] = DK_EXTERN;
3937 DirectiveKindMap[".globl"] = DK_GLOBL;
3938 DirectiveKindMap[".global"] = DK_GLOBAL;
3939 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3940 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3941 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3942 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3943 DirectiveKindMap[".reference"] = DK_REFERENCE;
3944 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3945 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3946 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3947 DirectiveKindMap[".comm"] = DK_COMM;
3948 DirectiveKindMap[".common"] = DK_COMMON;
3949 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3950 DirectiveKindMap[".abort"] = DK_ABORT;
3951 DirectiveKindMap[".include"] = DK_INCLUDE;
3952 DirectiveKindMap[".incbin"] = DK_INCBIN;
3953 DirectiveKindMap[".code16"] = DK_CODE16;
3954 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3955 DirectiveKindMap[".rept"] = DK_REPT;
3956 DirectiveKindMap[".rep"] = DK_REPT;
3957 DirectiveKindMap[".irp"] = DK_IRP;
3958 DirectiveKindMap[".irpc"] = DK_IRPC;
3959 DirectiveKindMap[".endr"] = DK_ENDR;
3960 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3961 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3962 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3963 DirectiveKindMap[".if"] = DK_IF;
3964 DirectiveKindMap[".ifb"] = DK_IFB;
3965 DirectiveKindMap[".ifnb"] = DK_IFNB;
3966 DirectiveKindMap[".ifc"] = DK_IFC;
3967 DirectiveKindMap[".ifnc"] = DK_IFNC;
3968 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3969 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3970 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3971 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3972 DirectiveKindMap[".else"] = DK_ELSE;
3973 DirectiveKindMap[".end"] = DK_END;
3974 DirectiveKindMap[".endif"] = DK_ENDIF;
3975 DirectiveKindMap[".skip"] = DK_SKIP;
3976 DirectiveKindMap[".space"] = DK_SPACE;
3977 DirectiveKindMap[".file"] = DK_FILE;
3978 DirectiveKindMap[".line"] = DK_LINE;
3979 DirectiveKindMap[".loc"] = DK_LOC;
3980 DirectiveKindMap[".stabs"] = DK_STABS;
3981 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3982 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3983 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3984 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3985 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3986 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3987 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3988 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3989 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3990 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3991 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3992 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3993 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3994 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3995 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3996 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3997 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3998 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3999 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4000 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4001 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4002 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4003 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4004 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4005 DirectiveKindMap[".macro"] = DK_MACRO;
4006 DirectiveKindMap[".endm"] = DK_ENDM;
4007 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4008 DirectiveKindMap[".purgem"] = DK_PURGEM;
4011 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4012 AsmToken EndToken, StartToken = getTok();
4014 unsigned NestLevel = 0;
4016 // Check whether we have reached the end of the file.
4017 if (getLexer().is(AsmToken::Eof)) {
4018 Error(DirectiveLoc, "no matching '.endr' in definition");
4022 if (Lexer.is(AsmToken::Identifier) &&
4023 (getTok().getIdentifier() == ".rept")) {
4027 // Otherwise, check whether we have reached the .endr.
4028 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4029 if (NestLevel == 0) {
4030 EndToken = getTok();
4032 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4033 TokError("unexpected token in '.endr' directive");
4041 // Otherwise, scan till the end of the statement.
4042 eatToEndOfStatement();
4045 const char *BodyStart = StartToken.getLoc().getPointer();
4046 const char *BodyEnd = EndToken.getLoc().getPointer();
4047 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4049 // We Are Anonymous.
4050 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4051 return &MacroLikeBodies.back();
4054 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4055 raw_svector_ostream &OS) {
4058 MemoryBuffer *Instantiation =
4059 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4061 // Create the macro instantiation object and add to the current macro
4062 // instantiation stack.
4063 MacroInstantiation *MI = new MacroInstantiation(
4064 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4065 ActiveMacros.push_back(MI);
4067 // Jump to the macro instantiation and prime the lexer.
4068 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4069 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4073 /// parseDirectiveRept
4074 /// ::= .rep | .rept count
4075 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4076 const MCExpr *CountExpr;
4077 SMLoc CountLoc = getTok().getLoc();
4078 if (parseExpression(CountExpr))
4082 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4083 eatToEndOfStatement();
4084 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4088 return Error(CountLoc, "Count is negative");
4090 if (Lexer.isNot(AsmToken::EndOfStatement))
4091 return TokError("unexpected token in '" + Dir + "' directive");
4093 // Eat the end of statement.
4096 // Lex the rept definition.
4097 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4101 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4102 // to hold the macro body with substitutions.
4103 SmallString<256> Buf;
4104 raw_svector_ostream OS(Buf);
4106 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4109 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4114 /// parseDirectiveIrp
4115 /// ::= .irp symbol,values
4116 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4117 MCAsmMacroParameter Parameter;
4119 if (parseIdentifier(Parameter.first))
4120 return TokError("expected identifier in '.irp' directive");
4122 if (Lexer.isNot(AsmToken::Comma))
4123 return TokError("expected comma in '.irp' directive");
4127 MCAsmMacroArguments A;
4128 if (parseMacroArguments(0, A))
4131 // Eat the end of statement.
4134 // Lex the irp definition.
4135 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4139 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4140 // to hold the macro body with substitutions.
4141 SmallString<256> Buf;
4142 raw_svector_ostream OS(Buf);
4144 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4145 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4149 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4154 /// parseDirectiveIrpc
4155 /// ::= .irpc symbol,values
4156 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4157 MCAsmMacroParameter Parameter;
4159 if (parseIdentifier(Parameter.first))
4160 return TokError("expected identifier in '.irpc' directive");
4162 if (Lexer.isNot(AsmToken::Comma))
4163 return TokError("expected comma in '.irpc' directive");
4167 MCAsmMacroArguments A;
4168 if (parseMacroArguments(0, A))
4171 if (A.size() != 1 || A.front().size() != 1)
4172 return TokError("unexpected token in '.irpc' directive");
4174 // Eat the end of statement.
4177 // Lex the irpc definition.
4178 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4182 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4183 // to hold the macro body with substitutions.
4184 SmallString<256> Buf;
4185 raw_svector_ostream OS(Buf);
4187 StringRef Values = A.front().front().getString();
4188 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4189 MCAsmMacroArgument Arg;
4190 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4192 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4196 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4201 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4202 if (ActiveMacros.empty())
4203 return TokError("unmatched '.endr' directive");
4205 // The only .repl that should get here are the ones created by
4206 // instantiateMacroLikeBody.
4207 assert(getLexer().is(AsmToken::EndOfStatement));
4213 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4215 const MCExpr *Value;
4216 SMLoc ExprLoc = getLexer().getLoc();
4217 if (parseExpression(Value))
4219 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4221 return Error(ExprLoc, "unexpected expression in _emit");
4222 uint64_t IntValue = MCE->getValue();
4223 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4224 return Error(ExprLoc, "literal value out of range for directive");
4226 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4230 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4231 const MCExpr *Value;
4232 SMLoc ExprLoc = getLexer().getLoc();
4233 if (parseExpression(Value))
4235 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4237 return Error(ExprLoc, "unexpected expression in align");
4238 uint64_t IntValue = MCE->getValue();
4239 if (!isPowerOf2_64(IntValue))
4240 return Error(ExprLoc, "literal value not a power of two greater then zero");
4242 Info.AsmRewrites->push_back(
4243 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4247 // We are comparing pointers, but the pointers are relative to a single string.
4248 // Thus, this should always be deterministic.
4249 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4250 const AsmRewrite *AsmRewriteB) {
4251 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4253 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4256 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4257 // rewrite to the same location. Make sure the SizeDirective rewrite is
4258 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4259 // ensures the sort algorithm is stable.
4260 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4261 AsmRewritePrecedence[AsmRewriteB->Kind])
4264 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4265 AsmRewritePrecedence[AsmRewriteB->Kind])
4267 llvm_unreachable("Unstable rewrite sort.");
4270 bool AsmParser::parseMSInlineAsm(
4271 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4272 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4273 SmallVectorImpl<std::string> &Constraints,
4274 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4275 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4276 SmallVector<void *, 4> InputDecls;
4277 SmallVector<void *, 4> OutputDecls;
4278 SmallVector<bool, 4> InputDeclsAddressOf;
4279 SmallVector<bool, 4> OutputDeclsAddressOf;
4280 SmallVector<std::string, 4> InputConstraints;
4281 SmallVector<std::string, 4> OutputConstraints;
4282 SmallVector<unsigned, 4> ClobberRegs;
4284 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4289 // While we have input, parse each statement.
4290 unsigned InputIdx = 0;
4291 unsigned OutputIdx = 0;
4292 while (getLexer().isNot(AsmToken::Eof)) {
4293 ParseStatementInfo Info(&AsmStrRewrites);
4294 if (parseStatement(Info))
4297 if (Info.ParseError)
4300 if (Info.Opcode == ~0U)
4303 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4305 // Build the list of clobbers, outputs and inputs.
4306 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4307 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4310 if (Operand->isImm())
4313 // Register operand.
4314 if (Operand->isReg() && !Operand->needAddressOf()) {
4315 unsigned NumDefs = Desc.getNumDefs();
4317 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4318 ClobberRegs.push_back(Operand->getReg());
4322 // Expr/Input or Output.
4323 StringRef SymName = Operand->getSymName();
4324 if (SymName.empty())
4327 void *OpDecl = Operand->getOpDecl();
4331 bool isOutput = (i == 1) && Desc.mayStore();
4332 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4335 OutputDecls.push_back(OpDecl);
4336 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4337 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4338 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4340 InputDecls.push_back(OpDecl);
4341 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4342 InputConstraints.push_back(Operand->getConstraint().str());
4343 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4347 // Consider implicit defs to be clobbers. Think of cpuid and push.
4348 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4349 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4350 ClobberRegs.push_back(ImpDefs[I]);
4353 // Set the number of Outputs and Inputs.
4354 NumOutputs = OutputDecls.size();
4355 NumInputs = InputDecls.size();
4357 // Set the unique clobbers.
4358 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4359 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4361 Clobbers.assign(ClobberRegs.size(), std::string());
4362 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4363 raw_string_ostream OS(Clobbers[I]);
4364 IP->printRegName(OS, ClobberRegs[I]);
4367 // Merge the various outputs and inputs. Output are expected first.
4368 if (NumOutputs || NumInputs) {
4369 unsigned NumExprs = NumOutputs + NumInputs;
4370 OpDecls.resize(NumExprs);
4371 Constraints.resize(NumExprs);
4372 for (unsigned i = 0; i < NumOutputs; ++i) {
4373 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4374 Constraints[i] = OutputConstraints[i];
4376 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4377 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4378 Constraints[j] = InputConstraints[i];
4382 // Build the IR assembly string.
4383 std::string AsmStringIR;
4384 raw_string_ostream OS(AsmStringIR);
4385 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4386 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4387 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4388 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4389 E = AsmStrRewrites.end();
4391 AsmRewriteKind Kind = (*I).Kind;
4392 if (Kind == AOK_Delete)
4395 const char *Loc = (*I).Loc.getPointer();
4396 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4398 // Emit everything up to the immediate/expression.
4399 unsigned Len = Loc - AsmStart;
4401 OS << StringRef(AsmStart, Len);
4403 // Skip the original expression.
4404 if (Kind == AOK_Skip) {
4405 AsmStart = Loc + (*I).Len;
4409 unsigned AdditionalSkip = 0;
4410 // Rewrite expressions in $N notation.
4415 OS << "$$" << (*I).Val;
4421 OS << '$' << InputIdx++;
4424 OS << '$' << OutputIdx++;
4426 case AOK_SizeDirective:
4429 case 8: OS << "byte ptr "; break;
4430 case 16: OS << "word ptr "; break;
4431 case 32: OS << "dword ptr "; break;
4432 case 64: OS << "qword ptr "; break;
4433 case 80: OS << "xword ptr "; break;
4434 case 128: OS << "xmmword ptr "; break;
4435 case 256: OS << "ymmword ptr "; break;
4442 unsigned Val = (*I).Val;
4443 OS << ".align " << Val;
4445 // Skip the original immediate.
4446 assert(Val < 10 && "Expected alignment less then 2^10.");
4447 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4450 case AOK_DotOperator:
4455 // Skip the original expression.
4456 AsmStart = Loc + (*I).Len + AdditionalSkip;
4459 // Emit the remainder of the asm string.
4460 if (AsmStart != AsmEnd)
4461 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4463 AsmString = OS.str();
4467 /// \brief Create an MCAsmParser instance.
4468 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4469 MCStreamer &Out, const MCAsmInfo &MAI) {
4470 return new AsmParser(SM, C, Out, MAI);