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() {}
54 /// \brief Helper types for tracking macro definitions.
55 typedef std::vector<AsmToken> MCAsmMacroArgument;
56 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58 struct MCAsmMacroParameter {
60 MCAsmMacroArgument Value;
63 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
68 MCAsmMacroParameters Parameters;
71 MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
72 Name(N), Body(B), Parameters(P) {}
75 /// \brief Helper class for storing information about an active macro
77 struct MacroInstantiation {
78 /// The macro being instantiated.
79 const MCAsmMacro *TheMacro;
81 /// The macro instantiation with substitutions.
82 MemoryBuffer *Instantiation;
84 /// The location of the instantiation.
85 SMLoc InstantiationLoc;
87 /// The buffer where parsing should resume upon instantiation completion.
90 /// The location where parsing should resume upon instantiation completion.
94 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
98 struct ParseStatementInfo {
99 /// \brief The parsed operands from the last parsed statement.
100 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
102 /// \brief The opcode from the last parsed instruction.
105 /// \brief Was there an error parsing the inline assembly?
108 SmallVectorImpl<AsmRewrite> *AsmRewrites;
110 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
111 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
112 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
114 ~ParseStatementInfo() {
115 // Free any parsed operands.
116 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
117 delete ParsedOperands[i];
118 ParsedOperands.clear();
122 /// \brief The concrete assembly parser instance.
123 class AsmParser : public MCAsmParser {
124 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
125 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
130 const MCAsmInfo &MAI;
132 SourceMgr::DiagHandlerTy SavedDiagHandler;
133 void *SavedDiagContext;
134 MCAsmParserExtension *PlatformParser;
136 /// This is the current buffer index we're lexing from as managed by the
137 /// SourceMgr object.
140 AsmCond TheCondState;
141 std::vector<AsmCond> TheCondStack;
143 /// \brief maps directive names to handler methods in parser
144 /// extensions. Extensions register themselves in this map by calling
145 /// addDirectiveHandler.
146 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
148 /// \brief Map of currently defined macros.
149 StringMap<MCAsmMacro*> MacroMap;
151 /// \brief Stack of active macro instantiations.
152 std::vector<MacroInstantiation*> ActiveMacros;
154 /// \brief List of bodies of anonymous macros.
155 std::deque<MCAsmMacro> MacroLikeBodies;
157 /// Boolean tracking whether macro substitution is enabled.
158 unsigned MacrosEnabledFlag : 1;
160 /// Flag tracking whether any errors have been encountered.
161 unsigned HadError : 1;
163 /// The values from the last parsed cpp hash file line comment if any.
164 StringRef CppHashFilename;
165 int64_t CppHashLineNumber;
168 /// When generating dwarf for assembly source files we need to calculate the
169 /// logical line number based on the last parsed cpp hash file line comment
170 /// and current line. Since this is slow and messes up the SourceMgr's
171 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
172 SMLoc LastQueryIDLoc;
174 unsigned LastQueryLine;
176 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
177 unsigned AssemblerDialect;
179 /// \brief is Darwin compatibility enabled?
182 /// \brief Are we parsing ms-style inline assembly?
183 bool ParsingInlineAsm;
186 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
187 const MCAsmInfo &MAI);
188 virtual ~AsmParser();
190 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
192 virtual void addDirectiveHandler(StringRef Directive,
193 ExtensionDirectiveHandler Handler) {
194 ExtensionDirectiveMap[Directive] = Handler;
198 /// @name MCAsmParser Interface
201 virtual SourceMgr &getSourceManager() { return SrcMgr; }
202 virtual MCAsmLexer &getLexer() { return Lexer; }
203 virtual MCContext &getContext() { return Ctx; }
204 virtual MCStreamer &getStreamer() { return Out; }
205 virtual unsigned getAssemblerDialect() {
206 if (AssemblerDialect == ~0U)
207 return MAI.getAssemblerDialect();
209 return AssemblerDialect;
211 virtual void setAssemblerDialect(unsigned i) {
212 AssemblerDialect = i;
215 virtual void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None);
216 virtual bool Warning(SMLoc L, const Twine &Msg,
217 ArrayRef<SMRange> Ranges = None);
218 virtual bool Error(SMLoc L, const Twine &Msg,
219 ArrayRef<SMRange> Ranges = None);
221 virtual const AsmToken &Lex();
223 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
224 bool isParsingInlineAsm() { return ParsingInlineAsm; }
226 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
227 unsigned &NumOutputs, unsigned &NumInputs,
228 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
229 SmallVectorImpl<std::string> &Constraints,
230 SmallVectorImpl<std::string> &Clobbers,
231 const MCInstrInfo *MII,
232 const MCInstPrinter *IP,
233 MCAsmParserSemaCallback &SI);
235 bool parseExpression(const MCExpr *&Res);
236 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
237 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
238 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
239 virtual bool parseAbsoluteExpression(int64_t &Res);
241 /// \brief Parse an identifier or string (as a quoted identifier)
242 /// and set \p Res to the identifier contents.
243 virtual bool parseIdentifier(StringRef &Res);
244 virtual void eatToEndOfStatement();
246 virtual void checkForValidSection();
251 bool parseStatement(ParseStatementInfo &Info);
252 void eatToEndOfLine();
253 bool parseCppHashLineFilenameComment(const SMLoc &L);
255 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
256 ArrayRef<MCAsmMacroParameter> Parameters);
257 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
258 ArrayRef<MCAsmMacroParameter> Parameters,
259 ArrayRef<MCAsmMacroArgument> A,
262 /// \brief Are macros enabled in the parser?
263 bool areMacrosEnabled() {return MacrosEnabledFlag;}
265 /// \brief Control a flag in the parser that enables or disables macros.
266 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
268 /// \brief Lookup a previously defined macro.
269 /// \param Name Macro name.
270 /// \returns Pointer to macro. NULL if no such macro was defined.
271 const MCAsmMacro* lookupMacro(StringRef Name);
273 /// \brief Define a new macro with the given name and information.
274 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
276 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
277 void undefineMacro(StringRef Name);
279 /// \brief Are we inside a macro instantiation?
280 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
282 /// \brief Handle entry to macro instantiation.
284 /// \param M The macro.
285 /// \param NameLoc Instantiation location.
286 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
288 /// \brief Handle exit from macro instantiation.
289 void handleMacroExit();
291 /// \brief Extract AsmTokens for a macro argument.
292 bool parseMacroArgument(MCAsmMacroArgument &MA);
294 /// \brief Parse all macro arguments for a given macro.
295 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
297 void printMacroInstantiations();
298 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
299 ArrayRef<SMRange> Ranges = None) const {
300 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
302 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
304 /// \brief Enter the specified file. This returns true on failure.
305 bool enterIncludeFile(const std::string &Filename);
307 /// \brief Process the specified file for the .incbin directive.
308 /// This returns true on failure.
309 bool processIncbinFile(const std::string &Filename);
311 /// \brief Reset the current lexer position to that given by \p Loc. The
312 /// current token is not set; clients should ensure Lex() is called
315 /// \param InBuffer If not -1, should be the known buffer id that contains the
317 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
319 /// \brief Parse up to the end of statement and a return the contents from the
320 /// current token until the end of the statement; the current token on exit
321 /// will be either the EndOfStatement or EOF.
322 virtual StringRef parseStringToEndOfStatement();
324 /// \brief Parse until the end of a statement or a comma is encountered,
325 /// return the contents from the current token up to the end or comma.
326 StringRef parseStringToComma();
328 bool parseAssignment(StringRef Name, bool allow_redef,
329 bool NoDeadStrip = false);
331 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
332 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
335 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
337 // Generic (target and platform independent) directive parsing.
339 DK_NO_DIRECTIVE, // Placeholder
340 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
341 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
342 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
343 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
344 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
345 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
346 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
347 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
348 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
349 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
350 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
351 DK_ELSEIF, DK_ELSE, DK_ENDIF,
352 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
353 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
354 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
355 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
356 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
357 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
358 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
359 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
360 DK_SLEB128, DK_ULEB128,
364 /// \brief Maps directive name --> DirectiveKind enum, for
365 /// directives parsed by this class.
366 StringMap<DirectiveKind> DirectiveKindMap;
368 // ".ascii", ".asciz", ".string"
369 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
370 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
371 bool parseDirectiveOctaValue(); // ".octa"
372 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
373 bool parseDirectiveFill(); // ".fill"
374 bool parseDirectiveZero(); // ".zero"
375 // ".set", ".equ", ".equiv"
376 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
377 bool parseDirectiveOrg(); // ".org"
378 // ".align{,32}", ".p2align{,w,l}"
379 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
381 // ".file", ".line", ".loc", ".stabs"
382 bool parseDirectiveFile(SMLoc DirectiveLoc);
383 bool parseDirectiveLine();
384 bool parseDirectiveLoc();
385 bool parseDirectiveStabs();
388 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
389 bool parseDirectiveCFIWindowSave();
390 bool parseDirectiveCFISections();
391 bool parseDirectiveCFIStartProc();
392 bool parseDirectiveCFIEndProc();
393 bool parseDirectiveCFIDefCfaOffset();
394 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
395 bool parseDirectiveCFIAdjustCfaOffset();
396 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
400 bool parseDirectiveCFIRememberState();
401 bool parseDirectiveCFIRestoreState();
402 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIEscape();
405 bool parseDirectiveCFISignalFrame();
406 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
409 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
410 bool parseDirectiveEndMacro(StringRef Directive);
411 bool parseDirectiveMacro(SMLoc DirectiveLoc);
412 bool parseDirectiveMacrosOnOff(StringRef Directive);
414 // ".bundle_align_mode"
415 bool parseDirectiveBundleAlignMode();
417 bool parseDirectiveBundleLock();
419 bool parseDirectiveBundleUnlock();
422 bool parseDirectiveSpace(StringRef IDVal);
424 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
425 bool parseDirectiveLEB128(bool Signed);
427 /// \brief Parse a directive like ".globl" which
428 /// accepts a single symbol (which should be a label or an external).
429 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
431 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
433 bool parseDirectiveAbort(); // ".abort"
434 bool parseDirectiveInclude(); // ".include"
435 bool parseDirectiveIncbin(); // ".incbin"
437 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
438 // ".ifb" or ".ifnb", depending on ExpectBlank.
439 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
440 // ".ifc" or ".ifnc", depending on ExpectEqual.
441 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
442 // ".ifdef" or ".ifndef", depending on expect_defined
443 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
444 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
445 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
446 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
447 virtual bool parseEscapedString(std::string &Data);
449 const MCExpr *applyModifierToExpr(const MCExpr *E,
450 MCSymbolRefExpr::VariantKind Variant);
452 // Macro-like directives
453 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
454 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
455 raw_svector_ostream &OS);
456 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
457 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
458 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
459 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
461 // "_emit" or "__emit"
462 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
466 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
469 bool parseDirectiveEnd(SMLoc DirectiveLoc);
471 void initializeDirectiveKindMap();
477 extern MCAsmParserExtension *createDarwinAsmParser();
478 extern MCAsmParserExtension *createELFAsmParser();
479 extern MCAsmParserExtension *createCOFFAsmParser();
483 enum { DEFAULT_ADDRSPACE = 0 };
485 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
486 const MCAsmInfo &_MAI)
487 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
488 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
489 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
490 ParsingInlineAsm(false) {
491 // Save the old handler.
492 SavedDiagHandler = SrcMgr.getDiagHandler();
493 SavedDiagContext = SrcMgr.getDiagContext();
494 // Set our own handler which calls the saved handler.
495 SrcMgr.setDiagHandler(DiagHandler, this);
496 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
498 // Initialize the platform / file format parser.
499 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
500 case MCObjectFileInfo::IsCOFF:
501 PlatformParser = createCOFFAsmParser();
502 PlatformParser->Initialize(*this);
504 case MCObjectFileInfo::IsMachO:
505 PlatformParser = createDarwinAsmParser();
506 PlatformParser->Initialize(*this);
509 case MCObjectFileInfo::IsELF:
510 PlatformParser = createELFAsmParser();
511 PlatformParser->Initialize(*this);
515 initializeDirectiveKindMap();
518 AsmParser::~AsmParser() {
519 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
521 // Destroy any macros.
522 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
525 delete it->getValue();
527 delete PlatformParser;
530 void AsmParser::printMacroInstantiations() {
531 // Print the active macro instantiation stack.
532 for (std::vector<MacroInstantiation *>::const_reverse_iterator
533 it = ActiveMacros.rbegin(),
534 ie = ActiveMacros.rend();
536 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
537 "while in macro instantiation");
540 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
541 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
542 printMacroInstantiations();
545 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
546 if (FatalAssemblerWarnings)
547 return Error(L, Msg, Ranges);
548 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
549 printMacroInstantiations();
553 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
555 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
556 printMacroInstantiations();
560 bool AsmParser::enterIncludeFile(const std::string &Filename) {
561 std::string IncludedFile;
562 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
568 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
573 /// Process the specified .incbin file by searching for it in the include paths
574 /// then just emitting the byte contents of the file to the streamer. This
575 /// returns true on failure.
576 bool AsmParser::processIncbinFile(const std::string &Filename) {
577 std::string IncludedFile;
578 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
582 // Pick up the bytes from the file and emit them.
583 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
587 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
588 if (InBuffer != -1) {
589 CurBuffer = InBuffer;
591 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
593 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
596 const AsmToken &AsmParser::Lex() {
597 const AsmToken *tok = &Lexer.Lex();
599 if (tok->is(AsmToken::Eof)) {
600 // If this is the end of an included file, pop the parent file off the
602 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
603 if (ParentIncludeLoc != SMLoc()) {
604 jumpToLoc(ParentIncludeLoc);
609 if (tok->is(AsmToken::Error))
610 Error(Lexer.getErrLoc(), Lexer.getErr());
615 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
616 // Create the initial section, if requested.
617 if (!NoInitialTextSection)
624 AsmCond StartingCondState = TheCondState;
626 // If we are generating dwarf for assembly source files save the initial text
627 // section and generate a .file directive.
628 if (getContext().getGenDwarfForAssembly()) {
629 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
630 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
631 getStreamer().EmitLabel(SectionStartSym);
632 getContext().setGenDwarfSectionStartSym(SectionStartSym);
633 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
635 getContext().getMainFileName());
638 // While we have input, parse each statement.
639 while (Lexer.isNot(AsmToken::Eof)) {
640 ParseStatementInfo Info;
641 if (!parseStatement(Info))
644 // We had an error, validate that one was emitted and recover by skipping to
646 assert(HadError && "Parse statement returned an error, but none emitted!");
647 eatToEndOfStatement();
650 if (TheCondState.TheCond != StartingCondState.TheCond ||
651 TheCondState.Ignore != StartingCondState.Ignore)
652 return TokError("unmatched .ifs or .elses");
654 // Check to see there are no empty DwarfFile slots.
655 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
656 getContext().getMCDwarfFiles();
657 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
658 if (!MCDwarfFiles[i])
659 TokError("unassigned file number: " + Twine(i) + " for .file directives");
662 // Check to see that all assembler local symbols were actually defined.
663 // Targets that don't do subsections via symbols may not want this, though,
664 // so conservatively exclude them. Only do this if we're finalizing, though,
665 // as otherwise we won't necessarilly have seen everything yet.
666 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
667 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
668 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
671 MCSymbol *Sym = i->getValue();
672 // Variable symbols may not be marked as defined, so check those
673 // explicitly. If we know it's a variable, we have a definition for
674 // the purposes of this check.
675 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
676 // FIXME: We would really like to refer back to where the symbol was
677 // first referenced for a source location. We need to add something
678 // to track that. Currently, we just point to the end of the file.
680 getLexer().getLoc(), SourceMgr::DK_Error,
681 "assembler local symbol '" + Sym->getName() + "' not defined");
685 // Finalize the output stream if there are no errors and if the client wants
687 if (!HadError && !NoFinalize)
693 void AsmParser::checkForValidSection() {
694 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
695 TokError("expected section directive before assembly directive");
700 /// \brief Throw away the rest of the line for testing purposes.
701 void AsmParser::eatToEndOfStatement() {
702 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
706 if (Lexer.is(AsmToken::EndOfStatement))
710 StringRef AsmParser::parseStringToEndOfStatement() {
711 const char *Start = getTok().getLoc().getPointer();
713 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
716 const char *End = getTok().getLoc().getPointer();
717 return StringRef(Start, End - Start);
720 StringRef AsmParser::parseStringToComma() {
721 const char *Start = getTok().getLoc().getPointer();
723 while (Lexer.isNot(AsmToken::EndOfStatement) &&
724 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
727 const char *End = getTok().getLoc().getPointer();
728 return StringRef(Start, End - Start);
731 /// \brief Parse a paren expression and return it.
732 /// NOTE: This assumes the leading '(' has already been consumed.
734 /// parenexpr ::= expr)
736 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
737 if (parseExpression(Res))
739 if (Lexer.isNot(AsmToken::RParen))
740 return TokError("expected ')' in parentheses expression");
741 EndLoc = Lexer.getTok().getEndLoc();
746 /// \brief Parse a bracket expression and return it.
747 /// NOTE: This assumes the leading '[' has already been consumed.
749 /// bracketexpr ::= expr]
751 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
752 if (parseExpression(Res))
754 if (Lexer.isNot(AsmToken::RBrac))
755 return TokError("expected ']' in brackets expression");
756 EndLoc = Lexer.getTok().getEndLoc();
761 /// \brief Parse a primary expression and return it.
762 /// primaryexpr ::= (parenexpr
763 /// primaryexpr ::= symbol
764 /// primaryexpr ::= number
765 /// primaryexpr ::= '.'
766 /// primaryexpr ::= ~,+,- primaryexpr
767 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
768 SMLoc FirstTokenLoc = getLexer().getLoc();
769 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
770 switch (FirstTokenKind) {
772 return TokError("unknown token in expression");
773 // If we have an error assume that we've already handled it.
774 case AsmToken::Error:
776 case AsmToken::Exclaim:
777 Lex(); // Eat the operator.
778 if (parsePrimaryExpr(Res, EndLoc))
780 Res = MCUnaryExpr::CreateLNot(Res, getContext());
782 case AsmToken::Dollar:
784 case AsmToken::String:
785 case AsmToken::Identifier: {
786 StringRef Identifier;
787 if (parseIdentifier(Identifier)) {
788 if (FirstTokenKind == AsmToken::Dollar) {
789 if (Lexer.getMAI().getDollarIsPC()) {
790 // This is a '$' reference, which references the current PC. Emit a
791 // temporary label to the streamer and refer to it.
792 MCSymbol *Sym = Ctx.CreateTempSymbol();
794 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
796 EndLoc = FirstTokenLoc;
799 return Error(FirstTokenLoc, "invalid token in expression");
803 // Parse symbol variant
804 std::pair<StringRef, StringRef> Split;
805 if (!MAI.useParensForSymbolVariant()) {
806 Split = Identifier.split('@');
807 } else if (Lexer.is(AsmToken::LParen)) {
808 Lexer.Lex(); // eat (
810 parseIdentifier(VName);
811 if (Lexer.isNot(AsmToken::RParen)) {
812 return Error(Lexer.getTok().getLoc(),
813 "unexpected token in variant, expected ')'");
815 Lexer.Lex(); // eat )
816 Split = std::make_pair(Identifier, VName);
819 EndLoc = SMLoc::getFromPointer(Identifier.end());
821 // This is a symbol reference.
822 StringRef SymbolName = Identifier;
823 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
825 // Lookup the symbol variant if used.
826 if (Split.second.size()) {
827 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
828 if (Variant != MCSymbolRefExpr::VK_Invalid) {
829 SymbolName = Split.first;
830 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
831 Variant = MCSymbolRefExpr::VK_None;
833 Variant = MCSymbolRefExpr::VK_None;
834 return Error(SMLoc::getFromPointer(Split.second.begin()),
835 "invalid variant '" + Split.second + "'");
839 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
841 // If this is an absolute variable reference, substitute it now to preserve
842 // semantics in the face of reassignment.
843 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
845 return Error(EndLoc, "unexpected modifier on variable reference");
847 Res = Sym->getVariableValue();
851 // Otherwise create a symbol ref.
852 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
855 case AsmToken::BigNum:
856 return TokError("literal value out of range for directive");
857 case AsmToken::Integer: {
858 SMLoc Loc = getTok().getLoc();
859 int64_t IntVal = getTok().getIntVal();
860 Res = MCConstantExpr::Create(IntVal, getContext());
861 EndLoc = Lexer.getTok().getEndLoc();
863 // Look for 'b' or 'f' following an Integer as a directional label
864 if (Lexer.getKind() == AsmToken::Identifier) {
865 StringRef IDVal = getTok().getString();
866 // Lookup the symbol variant if used.
867 std::pair<StringRef, StringRef> Split = IDVal.split('@');
868 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
869 if (Split.first.size() != IDVal.size()) {
870 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
871 if (Variant == MCSymbolRefExpr::VK_Invalid) {
872 Variant = MCSymbolRefExpr::VK_None;
873 return TokError("invalid variant '" + Split.second + "'");
877 if (IDVal == "f" || IDVal == "b") {
879 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
880 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
881 if (IDVal == "b" && Sym->isUndefined())
882 return Error(Loc, "invalid reference to undefined symbol");
883 EndLoc = Lexer.getTok().getEndLoc();
884 Lex(); // Eat identifier.
889 case AsmToken::Real: {
890 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
891 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
892 Res = MCConstantExpr::Create(IntVal, getContext());
893 EndLoc = Lexer.getTok().getEndLoc();
897 case AsmToken::Dot: {
898 // This is a '.' reference, which references the current PC. Emit a
899 // temporary label to the streamer and refer to it.
900 MCSymbol *Sym = Ctx.CreateTempSymbol();
902 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
903 EndLoc = Lexer.getTok().getEndLoc();
904 Lex(); // Eat identifier.
907 case AsmToken::LParen:
908 Lex(); // Eat the '('.
909 return parseParenExpr(Res, EndLoc);
910 case AsmToken::LBrac:
911 if (!PlatformParser->HasBracketExpressions())
912 return TokError("brackets expression not supported on this target");
913 Lex(); // Eat the '['.
914 return parseBracketExpr(Res, EndLoc);
915 case AsmToken::Minus:
916 Lex(); // Eat the operator.
917 if (parsePrimaryExpr(Res, EndLoc))
919 Res = MCUnaryExpr::CreateMinus(Res, getContext());
922 Lex(); // Eat the operator.
923 if (parsePrimaryExpr(Res, EndLoc))
925 Res = MCUnaryExpr::CreatePlus(Res, getContext());
927 case AsmToken::Tilde:
928 Lex(); // Eat the operator.
929 if (parsePrimaryExpr(Res, EndLoc))
931 Res = MCUnaryExpr::CreateNot(Res, getContext());
936 bool AsmParser::parseExpression(const MCExpr *&Res) {
938 return parseExpression(Res, EndLoc);
942 AsmParser::applyModifierToExpr(const MCExpr *E,
943 MCSymbolRefExpr::VariantKind Variant) {
944 // Ask the target implementation about this expression first.
945 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
948 // Recurse over the given expression, rebuilding it to apply the given variant
949 // if there is exactly one symbol.
950 switch (E->getKind()) {
952 case MCExpr::Constant:
955 case MCExpr::SymbolRef: {
956 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
958 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
959 TokError("invalid variant on expression '" + getTok().getIdentifier() +
960 "' (already modified)");
964 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
967 case MCExpr::Unary: {
968 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
969 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
972 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
975 case MCExpr::Binary: {
976 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
977 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
978 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
988 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
992 llvm_unreachable("Invalid expression kind!");
995 /// \brief Parse an expression and return it.
997 /// expr ::= expr &&,|| expr -> lowest.
998 /// expr ::= expr |,^,&,! expr
999 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1000 /// expr ::= expr <<,>> expr
1001 /// expr ::= expr +,- expr
1002 /// expr ::= expr *,/,% expr -> highest.
1003 /// expr ::= primaryexpr
1005 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1006 // Parse the expression.
1008 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1011 // As a special case, we support 'a op b @ modifier' by rewriting the
1012 // expression to include the modifier. This is inefficient, but in general we
1013 // expect users to use 'a@modifier op b'.
1014 if (Lexer.getKind() == AsmToken::At) {
1017 if (Lexer.isNot(AsmToken::Identifier))
1018 return TokError("unexpected symbol modifier following '@'");
1020 MCSymbolRefExpr::VariantKind Variant =
1021 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1022 if (Variant == MCSymbolRefExpr::VK_Invalid)
1023 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1025 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1027 return TokError("invalid modifier '" + getTok().getIdentifier() +
1028 "' (no symbols present)");
1035 // Try to constant fold it up front, if possible.
1037 if (Res->EvaluateAsAbsolute(Value))
1038 Res = MCConstantExpr::Create(Value, getContext());
1043 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1045 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1048 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1051 SMLoc StartLoc = Lexer.getLoc();
1052 if (parseExpression(Expr))
1055 if (!Expr->EvaluateAsAbsolute(Res))
1056 return Error(StartLoc, "expected absolute expression");
1061 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1062 MCBinaryExpr::Opcode &Kind) {
1065 return 0; // not a binop.
1067 // Lowest Precedence: &&, ||
1068 case AsmToken::AmpAmp:
1069 Kind = MCBinaryExpr::LAnd;
1071 case AsmToken::PipePipe:
1072 Kind = MCBinaryExpr::LOr;
1075 // Low Precedence: |, &, ^
1077 // FIXME: gas seems to support '!' as an infix operator?
1078 case AsmToken::Pipe:
1079 Kind = MCBinaryExpr::Or;
1081 case AsmToken::Caret:
1082 Kind = MCBinaryExpr::Xor;
1085 Kind = MCBinaryExpr::And;
1088 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1089 case AsmToken::EqualEqual:
1090 Kind = MCBinaryExpr::EQ;
1092 case AsmToken::ExclaimEqual:
1093 case AsmToken::LessGreater:
1094 Kind = MCBinaryExpr::NE;
1096 case AsmToken::Less:
1097 Kind = MCBinaryExpr::LT;
1099 case AsmToken::LessEqual:
1100 Kind = MCBinaryExpr::LTE;
1102 case AsmToken::Greater:
1103 Kind = MCBinaryExpr::GT;
1105 case AsmToken::GreaterEqual:
1106 Kind = MCBinaryExpr::GTE;
1109 // Intermediate Precedence: <<, >>
1110 case AsmToken::LessLess:
1111 Kind = MCBinaryExpr::Shl;
1113 case AsmToken::GreaterGreater:
1114 Kind = MCBinaryExpr::Shr;
1117 // High Intermediate Precedence: +, -
1118 case AsmToken::Plus:
1119 Kind = MCBinaryExpr::Add;
1121 case AsmToken::Minus:
1122 Kind = MCBinaryExpr::Sub;
1125 // Highest Precedence: *, /, %
1126 case AsmToken::Star:
1127 Kind = MCBinaryExpr::Mul;
1129 case AsmToken::Slash:
1130 Kind = MCBinaryExpr::Div;
1132 case AsmToken::Percent:
1133 Kind = MCBinaryExpr::Mod;
1138 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1139 /// Res contains the LHS of the expression on input.
1140 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1143 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1144 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1146 // If the next token is lower precedence than we are allowed to eat, return
1147 // successfully with what we ate already.
1148 if (TokPrec < Precedence)
1153 // Eat the next primary expression.
1155 if (parsePrimaryExpr(RHS, EndLoc))
1158 // If BinOp binds less tightly with RHS than the operator after RHS, let
1159 // the pending operator take RHS as its LHS.
1160 MCBinaryExpr::Opcode Dummy;
1161 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1162 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1165 // Merge LHS and RHS according to operator.
1166 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1171 /// ::= EndOfStatement
1172 /// ::= Label* Directive ...Operands... EndOfStatement
1173 /// ::= Label* Identifier OperandList* EndOfStatement
1174 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1175 if (Lexer.is(AsmToken::EndOfStatement)) {
1181 // Statements always start with an identifier or are a full line comment.
1182 AsmToken ID = getTok();
1183 SMLoc IDLoc = ID.getLoc();
1185 int64_t LocalLabelVal = -1;
1186 // A full line comment is a '#' as the first token.
1187 if (Lexer.is(AsmToken::Hash))
1188 return parseCppHashLineFilenameComment(IDLoc);
1190 // Allow an integer followed by a ':' as a directional local label.
1191 if (Lexer.is(AsmToken::Integer)) {
1192 LocalLabelVal = getTok().getIntVal();
1193 if (LocalLabelVal < 0) {
1194 if (!TheCondState.Ignore)
1195 return TokError("unexpected token at start of statement");
1198 IDVal = getTok().getString();
1199 Lex(); // Consume the integer token to be used as an identifier token.
1200 if (Lexer.getKind() != AsmToken::Colon) {
1201 if (!TheCondState.Ignore)
1202 return TokError("unexpected token at start of statement");
1205 } else if (Lexer.is(AsmToken::Dot)) {
1206 // Treat '.' as a valid identifier in this context.
1209 } else if (parseIdentifier(IDVal)) {
1210 if (!TheCondState.Ignore)
1211 return TokError("unexpected token at start of statement");
1215 // Handle conditional assembly here before checking for skipping. We
1216 // have to do this so that .endif isn't skipped in a ".if 0" block for
1218 StringMap<DirectiveKind>::const_iterator DirKindIt =
1219 DirectiveKindMap.find(IDVal);
1220 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1222 : DirKindIt->getValue();
1227 return parseDirectiveIf(IDLoc);
1229 return parseDirectiveIfb(IDLoc, true);
1231 return parseDirectiveIfb(IDLoc, false);
1233 return parseDirectiveIfc(IDLoc, true);
1235 return parseDirectiveIfc(IDLoc, false);
1237 return parseDirectiveIfdef(IDLoc, true);
1240 return parseDirectiveIfdef(IDLoc, false);
1242 return parseDirectiveElseIf(IDLoc);
1244 return parseDirectiveElse(IDLoc);
1246 return parseDirectiveEndIf(IDLoc);
1249 // Ignore the statement if in the middle of inactive conditional
1251 if (TheCondState.Ignore) {
1252 eatToEndOfStatement();
1256 // FIXME: Recurse on local labels?
1258 // See what kind of statement we have.
1259 switch (Lexer.getKind()) {
1260 case AsmToken::Colon: {
1261 checkForValidSection();
1263 // identifier ':' -> Label.
1266 // Diagnose attempt to use '.' as a label.
1268 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1270 // Diagnose attempt to use a variable as a label.
1272 // FIXME: Diagnostics. Note the location of the definition as a label.
1273 // FIXME: This doesn't diagnose assignment to a symbol which has been
1274 // implicitly marked as external.
1276 if (LocalLabelVal == -1)
1277 Sym = getContext().GetOrCreateSymbol(IDVal);
1279 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1280 if (!Sym->isUndefined() || Sym->isVariable())
1281 return Error(IDLoc, "invalid symbol redefinition");
1284 if (!ParsingInlineAsm)
1287 // If we are generating dwarf for assembly source files then gather the
1288 // info to make a dwarf label entry for this label if needed.
1289 if (getContext().getGenDwarfForAssembly())
1290 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1293 getTargetParser().onLabelParsed(Sym);
1295 // Consume any end of statement token, if present, to avoid spurious
1296 // AddBlankLine calls().
1297 if (Lexer.is(AsmToken::EndOfStatement)) {
1299 if (Lexer.is(AsmToken::Eof))
1306 case AsmToken::Equal:
1307 // identifier '=' ... -> assignment statement
1310 return parseAssignment(IDVal, true);
1312 default: // Normal instruction or directive.
1316 // If macros are enabled, check to see if this is a macro instantiation.
1317 if (areMacrosEnabled())
1318 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1319 return handleMacroEntry(M, IDLoc);
1322 // Otherwise, we have a normal instruction or directive.
1324 // Directives start with "."
1325 if (IDVal[0] == '.' && IDVal != ".") {
1326 // There are several entities interested in parsing directives:
1328 // 1. The target-specific assembly parser. Some directives are target
1329 // specific or may potentially behave differently on certain targets.
1330 // 2. Asm parser extensions. For example, platform-specific parsers
1331 // (like the ELF parser) register themselves as extensions.
1332 // 3. The generic directive parser implemented by this class. These are
1333 // all the directives that behave in a target and platform independent
1334 // manner, or at least have a default behavior that's shared between
1335 // all targets and platforms.
1337 // First query the target-specific parser. It will return 'true' if it
1338 // isn't interested in this directive.
1339 if (!getTargetParser().ParseDirective(ID))
1342 // Next, check the extension directive map to see if any extension has
1343 // registered itself to parse this directive.
1344 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1345 ExtensionDirectiveMap.lookup(IDVal);
1347 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1349 // Finally, if no one else is interested in this directive, it must be
1350 // generic and familiar to this class.
1356 return parseDirectiveSet(IDVal, true);
1358 return parseDirectiveSet(IDVal, false);
1360 return parseDirectiveAscii(IDVal, false);
1363 return parseDirectiveAscii(IDVal, true);
1365 return parseDirectiveValue(1);
1369 return parseDirectiveValue(2);
1373 return parseDirectiveValue(4);
1376 return parseDirectiveValue(8);
1378 return parseDirectiveOctaValue();
1381 return parseDirectiveRealValue(APFloat::IEEEsingle);
1383 return parseDirectiveRealValue(APFloat::IEEEdouble);
1385 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1386 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1389 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1390 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1393 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1395 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1397 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1399 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1401 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1403 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1405 return parseDirectiveOrg();
1407 return parseDirectiveFill();
1409 return parseDirectiveZero();
1411 eatToEndOfStatement(); // .extern is the default, ignore it.
1415 return parseDirectiveSymbolAttribute(MCSA_Global);
1416 case DK_LAZY_REFERENCE:
1417 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1418 case DK_NO_DEAD_STRIP:
1419 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1420 case DK_SYMBOL_RESOLVER:
1421 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1422 case DK_PRIVATE_EXTERN:
1423 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1425 return parseDirectiveSymbolAttribute(MCSA_Reference);
1426 case DK_WEAK_DEFINITION:
1427 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1428 case DK_WEAK_REFERENCE:
1429 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1430 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1431 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1434 return parseDirectiveComm(/*IsLocal=*/false);
1436 return parseDirectiveComm(/*IsLocal=*/true);
1438 return parseDirectiveAbort();
1440 return parseDirectiveInclude();
1442 return parseDirectiveIncbin();
1445 return TokError(Twine(IDVal) + " not supported yet");
1447 return parseDirectiveRept(IDLoc, IDVal);
1449 return parseDirectiveIrp(IDLoc);
1451 return parseDirectiveIrpc(IDLoc);
1453 return parseDirectiveEndr(IDLoc);
1454 case DK_BUNDLE_ALIGN_MODE:
1455 return parseDirectiveBundleAlignMode();
1456 case DK_BUNDLE_LOCK:
1457 return parseDirectiveBundleLock();
1458 case DK_BUNDLE_UNLOCK:
1459 return parseDirectiveBundleUnlock();
1461 return parseDirectiveLEB128(true);
1463 return parseDirectiveLEB128(false);
1466 return parseDirectiveSpace(IDVal);
1468 return parseDirectiveFile(IDLoc);
1470 return parseDirectiveLine();
1472 return parseDirectiveLoc();
1474 return parseDirectiveStabs();
1475 case DK_CFI_SECTIONS:
1476 return parseDirectiveCFISections();
1477 case DK_CFI_STARTPROC:
1478 return parseDirectiveCFIStartProc();
1479 case DK_CFI_ENDPROC:
1480 return parseDirectiveCFIEndProc();
1481 case DK_CFI_DEF_CFA:
1482 return parseDirectiveCFIDefCfa(IDLoc);
1483 case DK_CFI_DEF_CFA_OFFSET:
1484 return parseDirectiveCFIDefCfaOffset();
1485 case DK_CFI_ADJUST_CFA_OFFSET:
1486 return parseDirectiveCFIAdjustCfaOffset();
1487 case DK_CFI_DEF_CFA_REGISTER:
1488 return parseDirectiveCFIDefCfaRegister(IDLoc);
1490 return parseDirectiveCFIOffset(IDLoc);
1491 case DK_CFI_REL_OFFSET:
1492 return parseDirectiveCFIRelOffset(IDLoc);
1493 case DK_CFI_PERSONALITY:
1494 return parseDirectiveCFIPersonalityOrLsda(true);
1496 return parseDirectiveCFIPersonalityOrLsda(false);
1497 case DK_CFI_REMEMBER_STATE:
1498 return parseDirectiveCFIRememberState();
1499 case DK_CFI_RESTORE_STATE:
1500 return parseDirectiveCFIRestoreState();
1501 case DK_CFI_SAME_VALUE:
1502 return parseDirectiveCFISameValue(IDLoc);
1503 case DK_CFI_RESTORE:
1504 return parseDirectiveCFIRestore(IDLoc);
1506 return parseDirectiveCFIEscape();
1507 case DK_CFI_SIGNAL_FRAME:
1508 return parseDirectiveCFISignalFrame();
1509 case DK_CFI_UNDEFINED:
1510 return parseDirectiveCFIUndefined(IDLoc);
1511 case DK_CFI_REGISTER:
1512 return parseDirectiveCFIRegister(IDLoc);
1513 case DK_CFI_WINDOW_SAVE:
1514 return parseDirectiveCFIWindowSave();
1517 return parseDirectiveMacrosOnOff(IDVal);
1519 return parseDirectiveMacro(IDLoc);
1522 return parseDirectiveEndMacro(IDVal);
1524 return parseDirectivePurgeMacro(IDLoc);
1526 return parseDirectiveEnd(IDLoc);
1529 return Error(IDLoc, "unknown directive");
1532 // __asm _emit or __asm __emit
1533 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1534 IDVal == "_EMIT" || IDVal == "__EMIT"))
1535 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1538 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1539 return parseDirectiveMSAlign(IDLoc, Info);
1541 checkForValidSection();
1543 // Canonicalize the opcode to lower case.
1544 std::string OpcodeStr = IDVal.lower();
1545 ParseInstructionInfo IInfo(Info.AsmRewrites);
1546 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1547 Info.ParsedOperands);
1548 Info.ParseError = HadError;
1550 // Dump the parsed representation, if requested.
1551 if (getShowParsedOperands()) {
1552 SmallString<256> Str;
1553 raw_svector_ostream OS(Str);
1554 OS << "parsed instruction: [";
1555 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1558 Info.ParsedOperands[i]->print(OS);
1562 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1565 // If we are generating dwarf for assembly source files and the current
1566 // section is the initial text section then generate a .loc directive for
1568 if (!HadError && getContext().getGenDwarfForAssembly() &&
1569 getContext().getGenDwarfSection() ==
1570 getStreamer().getCurrentSection().first) {
1572 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1574 // If we previously parsed a cpp hash file line comment then make sure the
1575 // current Dwarf File is for the CppHashFilename if not then emit the
1576 // Dwarf File table for it and adjust the line number for the .loc.
1577 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1578 getContext().getMCDwarfFiles();
1579 if (CppHashFilename.size() != 0) {
1580 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1582 getStreamer().EmitDwarfFileDirective(
1583 getContext().nextGenDwarfFileNumber(), StringRef(),
1586 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1587 // cache with the different Loc from the call above we save the last
1588 // info we queried here with SrcMgr.FindLineNumber().
1589 unsigned CppHashLocLineNo;
1590 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1591 CppHashLocLineNo = LastQueryLine;
1593 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1594 LastQueryLine = CppHashLocLineNo;
1595 LastQueryIDLoc = CppHashLoc;
1596 LastQueryBuffer = CppHashBuf;
1598 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1601 getStreamer().EmitDwarfLocDirective(
1602 getContext().getGenDwarfFileNumber(), Line, 0,
1603 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1607 // If parsing succeeded, match the instruction.
1610 HadError = getTargetParser().MatchAndEmitInstruction(
1611 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1615 // Don't skip the rest of the line, the instruction parser is responsible for
1620 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1621 /// since they may not be able to be tokenized to get to the end of line token.
1622 void AsmParser::eatToEndOfLine() {
1623 if (!Lexer.is(AsmToken::EndOfStatement))
1624 Lexer.LexUntilEndOfLine();
1629 /// parseCppHashLineFilenameComment as this:
1630 /// ::= # number "filename"
1631 /// or just as a full line comment if it doesn't have a number and a string.
1632 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1633 Lex(); // Eat the hash token.
1635 if (getLexer().isNot(AsmToken::Integer)) {
1636 // Consume the line since in cases it is not a well-formed line directive,
1637 // as if were simply a full line comment.
1642 int64_t LineNumber = getTok().getIntVal();
1645 if (getLexer().isNot(AsmToken::String)) {
1650 StringRef Filename = getTok().getString();
1651 // Get rid of the enclosing quotes.
1652 Filename = Filename.substr(1, Filename.size() - 2);
1654 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1656 CppHashFilename = Filename;
1657 CppHashLineNumber = LineNumber;
1658 CppHashBuf = CurBuffer;
1660 // Ignore any trailing characters, they're just comment.
1665 /// \brief will use the last parsed cpp hash line filename comment
1666 /// for the Filename and LineNo if any in the diagnostic.
1667 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1668 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1669 raw_ostream &OS = errs();
1671 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1672 const SMLoc &DiagLoc = Diag.getLoc();
1673 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1674 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1676 // Like SourceMgr::printMessage() we need to print the include stack if any
1677 // before printing the message.
1678 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1679 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1680 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1681 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1684 // If we have not parsed a cpp hash line filename comment or the source
1685 // manager changed or buffer changed (like in a nested include) then just
1686 // print the normal diagnostic using its Filename and LineNo.
1687 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1688 DiagBuf != CppHashBuf) {
1689 if (Parser->SavedDiagHandler)
1690 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1696 // Use the CppHashFilename and calculate a line number based on the
1697 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1699 const std::string &Filename = Parser->CppHashFilename;
1701 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1702 int CppHashLocLineNo =
1703 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1705 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1707 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1708 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1709 Diag.getLineContents(), Diag.getRanges());
1711 if (Parser->SavedDiagHandler)
1712 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1714 NewDiag.print(0, OS);
1717 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1718 // difference being that that function accepts '@' as part of identifiers and
1719 // we can't do that. AsmLexer.cpp should probably be changed to handle
1720 // '@' as a special case when needed.
1721 static bool isIdentifierChar(char c) {
1722 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1726 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1727 ArrayRef<MCAsmMacroParameter> Parameters,
1728 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1729 unsigned NParameters = Parameters.size();
1730 if (NParameters != 0 && NParameters != A.size())
1731 return Error(L, "Wrong number of arguments");
1733 // A macro without parameters is handled differently on Darwin:
1734 // gas accepts no arguments and does no substitutions
1735 while (!Body.empty()) {
1736 // Scan for the next substitution.
1737 std::size_t End = Body.size(), Pos = 0;
1738 for (; Pos != End; ++Pos) {
1739 // Check for a substitution or escape.
1741 // This macro has no parameters, look for $0, $1, etc.
1742 if (Body[Pos] != '$' || Pos + 1 == End)
1745 char Next = Body[Pos + 1];
1746 if (Next == '$' || Next == 'n' ||
1747 isdigit(static_cast<unsigned char>(Next)))
1750 // This macro has parameters, look for \foo, \bar, etc.
1751 if (Body[Pos] == '\\' && Pos + 1 != End)
1757 OS << Body.slice(0, Pos);
1759 // Check if we reached the end.
1764 switch (Body[Pos + 1]) {
1770 // $n => number of arguments
1775 // $[0-9] => argument
1777 // Missing arguments are ignored.
1778 unsigned Index = Body[Pos + 1] - '0';
1779 if (Index >= A.size())
1782 // Otherwise substitute with the token values, with spaces eliminated.
1783 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1784 ie = A[Index].end();
1786 OS << it->getString();
1792 unsigned I = Pos + 1;
1793 while (isIdentifierChar(Body[I]) && I + 1 != End)
1796 const char *Begin = Body.data() + Pos + 1;
1797 StringRef Argument(Begin, I - (Pos + 1));
1799 for (; Index < NParameters; ++Index)
1800 if (Parameters[Index].Name == Argument)
1803 if (Index == NParameters) {
1804 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1807 OS << '\\' << Argument;
1811 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1812 ie = A[Index].end();
1814 if (it->getKind() == AsmToken::String)
1815 OS << it->getStringContents();
1817 OS << it->getString();
1819 Pos += 1 + Argument.size();
1822 // Update the scan point.
1823 Body = Body.substr(Pos);
1829 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1830 SMLoc EL, MemoryBuffer *I)
1831 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1834 static bool isOperator(AsmToken::TokenKind kind) {
1838 case AsmToken::Plus:
1839 case AsmToken::Minus:
1840 case AsmToken::Tilde:
1841 case AsmToken::Slash:
1842 case AsmToken::Star:
1844 case AsmToken::Equal:
1845 case AsmToken::EqualEqual:
1846 case AsmToken::Pipe:
1847 case AsmToken::PipePipe:
1848 case AsmToken::Caret:
1850 case AsmToken::AmpAmp:
1851 case AsmToken::Exclaim:
1852 case AsmToken::ExclaimEqual:
1853 case AsmToken::Percent:
1854 case AsmToken::Less:
1855 case AsmToken::LessEqual:
1856 case AsmToken::LessLess:
1857 case AsmToken::LessGreater:
1858 case AsmToken::Greater:
1859 case AsmToken::GreaterEqual:
1860 case AsmToken::GreaterGreater:
1866 class AsmLexerSkipSpaceRAII {
1868 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1869 Lexer.setSkipSpace(SkipSpace);
1872 ~AsmLexerSkipSpaceRAII() {
1873 Lexer.setSkipSpace(true);
1881 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA) {
1882 unsigned ParenLevel = 0;
1883 unsigned AddTokens = 0;
1885 // Darwin doesn't use spaces to delmit arguments.
1886 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1889 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1890 return TokError("unexpected token in macro instantiation");
1892 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1895 if (Lexer.is(AsmToken::Space)) {
1896 Lex(); // Eat spaces
1898 // Spaces can delimit parameters, but could also be part an expression.
1899 // If the token after a space is an operator, add the token and the next
1900 // one into this argument
1902 if (isOperator(Lexer.getKind())) {
1903 // Check to see whether the token is used as an operator,
1904 // or part of an identifier
1905 const char *NextChar = getTok().getEndLoc().getPointer();
1906 if (*NextChar == ' ')
1910 if (!AddTokens && ParenLevel == 0) {
1916 // handleMacroEntry relies on not advancing the lexer here
1917 // to be able to fill in the remaining default parameter values
1918 if (Lexer.is(AsmToken::EndOfStatement))
1921 // Adjust the current parentheses level.
1922 if (Lexer.is(AsmToken::LParen))
1924 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1927 // Append the token to the current argument list.
1928 MA.push_back(getTok());
1934 if (ParenLevel != 0)
1935 return TokError("unbalanced parentheses in macro argument");
1939 // Parse the macro instantiation arguments.
1940 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1941 MCAsmMacroArguments &A) {
1942 const unsigned NParameters = M ? M->Parameters.size() : 0;
1944 A.resize(NParameters);
1945 for (unsigned PI = 0; PI < NParameters; ++PI)
1946 if (!M->Parameters[PI].Value.empty())
1947 A[PI] = M->Parameters[PI].Value;
1949 bool NamedParametersFound = false;
1951 // Parse two kinds of macro invocations:
1952 // - macros defined without any parameters accept an arbitrary number of them
1953 // - macros defined with parameters accept at most that many of them
1954 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1956 MCAsmMacroParameter FA;
1959 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1961 if (parseIdentifier(FA.Name)) {
1962 Error(L, "invalid argument identifier for formal argument");
1963 eatToEndOfStatement();
1967 if (!Lexer.is(AsmToken::Equal)) {
1968 TokError("expected '=' after formal parameter identifier");
1969 eatToEndOfStatement();
1974 NamedParametersFound = true;
1977 if (NamedParametersFound && FA.Name.empty()) {
1978 Error(Lexer.getLoc(), "cannot mix positional and keyword arguments");
1979 eatToEndOfStatement();
1983 if (parseMacroArgument(FA.Value))
1986 unsigned PI = Parameter;
1987 if (!FA.Name.empty()) {
1989 for (FAI = 0; FAI < NParameters; ++FAI)
1990 if (M->Parameters[FAI].Name == FA.Name)
1992 if (FAI >= NParameters) {
1994 "parameter named '" + FA.Name + "' does not exist for macro '" +
2001 if (!FA.Value.empty()) {
2007 // At the end of the statement, fill in remaining arguments that have
2008 // default values. If there aren't any, then the next argument is
2009 // required but missing
2010 if (Lexer.is(AsmToken::EndOfStatement))
2013 if (Lexer.is(AsmToken::Comma))
2017 return TokError("too many positional arguments");
2020 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2021 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2022 return (I == MacroMap.end()) ? NULL : I->getValue();
2025 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2026 MacroMap[Name] = new MCAsmMacro(Macro);
2029 void AsmParser::undefineMacro(StringRef Name) {
2030 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2031 if (I != MacroMap.end()) {
2032 delete I->getValue();
2037 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2038 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2039 // this, although we should protect against infinite loops.
2040 if (ActiveMacros.size() == 20)
2041 return TokError("macros cannot be nested more than 20 levels deep");
2043 MCAsmMacroArguments A;
2044 if (parseMacroArguments(M, A))
2047 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2048 // to hold the macro body with substitutions.
2049 SmallString<256> Buf;
2050 StringRef Body = M->Body;
2051 raw_svector_ostream OS(Buf);
2053 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2056 // We include the .endmacro in the buffer as our cue to exit the macro
2058 OS << ".endmacro\n";
2060 MemoryBuffer *Instantiation =
2061 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2063 // Create the macro instantiation object and add to the current macro
2064 // instantiation stack.
2065 MacroInstantiation *MI = new MacroInstantiation(
2066 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2067 ActiveMacros.push_back(MI);
2069 // Jump to the macro instantiation and prime the lexer.
2070 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2071 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2077 void AsmParser::handleMacroExit() {
2078 // Jump to the EndOfStatement we should return to, and consume it.
2079 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2082 // Pop the instantiation entry.
2083 delete ActiveMacros.back();
2084 ActiveMacros.pop_back();
2087 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2088 switch (Value->getKind()) {
2089 case MCExpr::Binary: {
2090 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2091 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2093 case MCExpr::Target:
2094 case MCExpr::Constant:
2096 case MCExpr::SymbolRef: {
2098 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2100 return isUsedIn(Sym, S.getVariableValue());
2104 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2107 llvm_unreachable("Unknown expr kind!");
2110 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2112 // FIXME: Use better location, we should use proper tokens.
2113 SMLoc EqualLoc = Lexer.getLoc();
2115 const MCExpr *Value;
2116 if (parseExpression(Value))
2119 // Note: we don't count b as used in "a = b". This is to allow
2123 if (Lexer.isNot(AsmToken::EndOfStatement))
2124 return TokError("unexpected token in assignment");
2126 // Eat the end of statement marker.
2129 // Validate that the LHS is allowed to be a variable (either it has not been
2130 // used as a symbol, or it is an absolute symbol).
2131 MCSymbol *Sym = getContext().LookupSymbol(Name);
2133 // Diagnose assignment to a label.
2135 // FIXME: Diagnostics. Note the location of the definition as a label.
2136 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2137 if (isUsedIn(Sym, Value))
2138 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2139 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2140 ; // Allow redefinitions of undefined symbols only used in directives.
2141 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2142 ; // Allow redefinitions of variables that haven't yet been used.
2143 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2144 return Error(EqualLoc, "redefinition of '" + Name + "'");
2145 else if (!Sym->isVariable())
2146 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2147 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2148 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2151 // Don't count these checks as uses.
2152 Sym->setUsed(false);
2153 } else if (Name == ".") {
2154 if (Out.EmitValueToOffset(Value, 0)) {
2155 Error(EqualLoc, "expected absolute expression");
2156 eatToEndOfStatement();
2160 Sym = getContext().GetOrCreateSymbol(Name);
2162 // Do the assignment.
2163 Out.EmitAssignment(Sym, Value);
2165 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2170 /// parseIdentifier:
2173 bool AsmParser::parseIdentifier(StringRef &Res) {
2174 // The assembler has relaxed rules for accepting identifiers, in particular we
2175 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2176 // separate tokens. At this level, we have already lexed so we cannot (currently)
2177 // handle this as a context dependent token, instead we detect adjacent tokens
2178 // and return the combined identifier.
2179 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2180 SMLoc PrefixLoc = getLexer().getLoc();
2182 // Consume the prefix character, and check for a following identifier.
2184 if (Lexer.isNot(AsmToken::Identifier))
2187 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2188 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2191 // Construct the joined identifier and consume the token.
2193 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2198 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2201 Res = getTok().getIdentifier();
2203 Lex(); // Consume the identifier token.
2208 /// parseDirectiveSet:
2209 /// ::= .equ identifier ',' expression
2210 /// ::= .equiv identifier ',' expression
2211 /// ::= .set identifier ',' expression
2212 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2215 if (parseIdentifier(Name))
2216 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2218 if (getLexer().isNot(AsmToken::Comma))
2219 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2222 return parseAssignment(Name, allow_redef, true);
2225 bool AsmParser::parseEscapedString(std::string &Data) {
2226 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2229 StringRef Str = getTok().getStringContents();
2230 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2231 if (Str[i] != '\\') {
2236 // Recognize escaped characters. Note that this escape semantics currently
2237 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2240 return TokError("unexpected backslash at end of string");
2242 // Recognize octal sequences.
2243 if ((unsigned)(Str[i] - '0') <= 7) {
2244 // Consume up to three octal characters.
2245 unsigned Value = Str[i] - '0';
2247 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2249 Value = Value * 8 + (Str[i] - '0');
2251 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2253 Value = Value * 8 + (Str[i] - '0');
2258 return TokError("invalid octal escape sequence (out of range)");
2260 Data += (unsigned char)Value;
2264 // Otherwise recognize individual escapes.
2267 // Just reject invalid escape sequences for now.
2268 return TokError("invalid escape sequence (unrecognized character)");
2270 case 'b': Data += '\b'; break;
2271 case 'f': Data += '\f'; break;
2272 case 'n': Data += '\n'; break;
2273 case 'r': Data += '\r'; break;
2274 case 't': Data += '\t'; break;
2275 case '"': Data += '"'; break;
2276 case '\\': Data += '\\'; break;
2283 /// parseDirectiveAscii:
2284 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2285 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2286 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2287 checkForValidSection();
2290 if (getLexer().isNot(AsmToken::String))
2291 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2294 if (parseEscapedString(Data))
2297 getStreamer().EmitBytes(Data);
2299 getStreamer().EmitBytes(StringRef("\0", 1));
2303 if (getLexer().is(AsmToken::EndOfStatement))
2306 if (getLexer().isNot(AsmToken::Comma))
2307 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2316 /// parseDirectiveValue
2317 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2318 bool AsmParser::parseDirectiveValue(unsigned Size) {
2319 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2320 checkForValidSection();
2323 const MCExpr *Value;
2324 SMLoc ExprLoc = getLexer().getLoc();
2325 if (parseExpression(Value))
2328 // Special case constant expressions to match code generator.
2329 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2330 assert(Size <= 8 && "Invalid size");
2331 uint64_t IntValue = MCE->getValue();
2332 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2333 return Error(ExprLoc, "literal value out of range for directive");
2334 getStreamer().EmitIntValue(IntValue, Size);
2336 getStreamer().EmitValue(Value, Size);
2338 if (getLexer().is(AsmToken::EndOfStatement))
2341 // FIXME: Improve diagnostic.
2342 if (getLexer().isNot(AsmToken::Comma))
2343 return TokError("unexpected token in directive");
2352 /// ParseDirectiveOctaValue
2353 /// ::= .octa [ hexconstant (, hexconstant)* ]
2354 bool AsmParser::parseDirectiveOctaValue() {
2355 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2356 checkForValidSection();
2359 if (Lexer.getKind() == AsmToken::Error)
2361 if (Lexer.getKind() != AsmToken::Integer &&
2362 Lexer.getKind() != AsmToken::BigNum)
2363 return TokError("unknown token in expression");
2365 SMLoc ExprLoc = getLexer().getLoc();
2366 APInt IntValue = getTok().getAPIntVal();
2370 if (IntValue.isIntN(64)) {
2372 lo = IntValue.getZExtValue();
2373 } else if (IntValue.isIntN(128)) {
2374 // It might actually have more than 128 bits, but the top ones are zero.
2375 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2376 lo = IntValue.getLoBits(64).getZExtValue();
2378 return Error(ExprLoc, "literal value out of range for directive");
2380 if (MAI.isLittleEndian()) {
2381 getStreamer().EmitIntValue(lo, 8);
2382 getStreamer().EmitIntValue(hi, 8);
2384 getStreamer().EmitIntValue(hi, 8);
2385 getStreamer().EmitIntValue(lo, 8);
2388 if (getLexer().is(AsmToken::EndOfStatement))
2391 // FIXME: Improve diagnostic.
2392 if (getLexer().isNot(AsmToken::Comma))
2393 return TokError("unexpected token in directive");
2402 /// parseDirectiveRealValue
2403 /// ::= (.single | .double) [ expression (, expression)* ]
2404 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2405 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2406 checkForValidSection();
2409 // We don't truly support arithmetic on floating point expressions, so we
2410 // have to manually parse unary prefixes.
2412 if (getLexer().is(AsmToken::Minus)) {
2415 } else if (getLexer().is(AsmToken::Plus))
2418 if (getLexer().isNot(AsmToken::Integer) &&
2419 getLexer().isNot(AsmToken::Real) &&
2420 getLexer().isNot(AsmToken::Identifier))
2421 return TokError("unexpected token in directive");
2423 // Convert to an APFloat.
2424 APFloat Value(Semantics);
2425 StringRef IDVal = getTok().getString();
2426 if (getLexer().is(AsmToken::Identifier)) {
2427 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2428 Value = APFloat::getInf(Semantics);
2429 else if (!IDVal.compare_lower("nan"))
2430 Value = APFloat::getNaN(Semantics, false, ~0);
2432 return TokError("invalid floating point literal");
2433 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2434 APFloat::opInvalidOp)
2435 return TokError("invalid floating point literal");
2439 // Consume the numeric token.
2442 // Emit the value as an integer.
2443 APInt AsInt = Value.bitcastToAPInt();
2444 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2445 AsInt.getBitWidth() / 8);
2447 if (getLexer().is(AsmToken::EndOfStatement))
2450 if (getLexer().isNot(AsmToken::Comma))
2451 return TokError("unexpected token in directive");
2460 /// parseDirectiveZero
2461 /// ::= .zero expression
2462 bool AsmParser::parseDirectiveZero() {
2463 checkForValidSection();
2466 if (parseAbsoluteExpression(NumBytes))
2470 if (getLexer().is(AsmToken::Comma)) {
2472 if (parseAbsoluteExpression(Val))
2476 if (getLexer().isNot(AsmToken::EndOfStatement))
2477 return TokError("unexpected token in '.zero' directive");
2481 getStreamer().EmitFill(NumBytes, Val);
2486 /// parseDirectiveFill
2487 /// ::= .fill expression [ , expression [ , expression ] ]
2488 bool AsmParser::parseDirectiveFill() {
2489 checkForValidSection();
2491 SMLoc RepeatLoc = getLexer().getLoc();
2493 if (parseAbsoluteExpression(NumValues))
2496 if (NumValues < 0) {
2498 "'.fill' directive with negative repeat count has no effect");
2502 int64_t FillSize = 1;
2503 int64_t FillExpr = 0;
2505 SMLoc SizeLoc, ExprLoc;
2506 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2507 if (getLexer().isNot(AsmToken::Comma))
2508 return TokError("unexpected token in '.fill' directive");
2511 SizeLoc = getLexer().getLoc();
2512 if (parseAbsoluteExpression(FillSize))
2515 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2516 if (getLexer().isNot(AsmToken::Comma))
2517 return TokError("unexpected token in '.fill' directive");
2520 ExprLoc = getLexer().getLoc();
2521 if (parseAbsoluteExpression(FillExpr))
2524 if (getLexer().isNot(AsmToken::EndOfStatement))
2525 return TokError("unexpected token in '.fill' directive");
2532 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2536 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2540 if (!isUInt<32>(FillExpr) && FillSize > 4)
2541 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2543 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2544 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2546 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2547 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2548 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2554 /// parseDirectiveOrg
2555 /// ::= .org expression [ , expression ]
2556 bool AsmParser::parseDirectiveOrg() {
2557 checkForValidSection();
2559 const MCExpr *Offset;
2560 SMLoc Loc = getTok().getLoc();
2561 if (parseExpression(Offset))
2564 // Parse optional fill expression.
2565 int64_t FillExpr = 0;
2566 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2567 if (getLexer().isNot(AsmToken::Comma))
2568 return TokError("unexpected token in '.org' directive");
2571 if (parseAbsoluteExpression(FillExpr))
2574 if (getLexer().isNot(AsmToken::EndOfStatement))
2575 return TokError("unexpected token in '.org' directive");
2580 // Only limited forms of relocatable expressions are accepted here, it
2581 // has to be relative to the current section. The streamer will return
2582 // 'true' if the expression wasn't evaluatable.
2583 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2584 return Error(Loc, "expected assembly-time absolute expression");
2589 /// parseDirectiveAlign
2590 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2591 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2592 checkForValidSection();
2594 SMLoc AlignmentLoc = getLexer().getLoc();
2596 if (parseAbsoluteExpression(Alignment))
2600 bool HasFillExpr = false;
2601 int64_t FillExpr = 0;
2602 int64_t MaxBytesToFill = 0;
2603 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2604 if (getLexer().isNot(AsmToken::Comma))
2605 return TokError("unexpected token in directive");
2608 // The fill expression can be omitted while specifying a maximum number of
2609 // alignment bytes, e.g:
2611 if (getLexer().isNot(AsmToken::Comma)) {
2613 if (parseAbsoluteExpression(FillExpr))
2617 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2618 if (getLexer().isNot(AsmToken::Comma))
2619 return TokError("unexpected token in directive");
2622 MaxBytesLoc = getLexer().getLoc();
2623 if (parseAbsoluteExpression(MaxBytesToFill))
2626 if (getLexer().isNot(AsmToken::EndOfStatement))
2627 return TokError("unexpected token in directive");
2636 // Compute alignment in bytes.
2638 // FIXME: Diagnose overflow.
2639 if (Alignment >= 32) {
2640 Error(AlignmentLoc, "invalid alignment value");
2644 Alignment = 1ULL << Alignment;
2646 // Reject alignments that aren't a power of two, for gas compatibility.
2647 if (!isPowerOf2_64(Alignment))
2648 Error(AlignmentLoc, "alignment must be a power of 2");
2651 // Diagnose non-sensical max bytes to align.
2652 if (MaxBytesLoc.isValid()) {
2653 if (MaxBytesToFill < 1) {
2654 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2655 "many bytes, ignoring maximum bytes expression");
2659 if (MaxBytesToFill >= Alignment) {
2660 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2666 // Check whether we should use optimal code alignment for this .align
2668 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2669 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2670 ValueSize == 1 && UseCodeAlign) {
2671 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2673 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2674 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2681 /// parseDirectiveFile
2682 /// ::= .file [number] filename
2683 /// ::= .file number directory filename
2684 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2685 // FIXME: I'm not sure what this is.
2686 int64_t FileNumber = -1;
2687 SMLoc FileNumberLoc = getLexer().getLoc();
2688 if (getLexer().is(AsmToken::Integer)) {
2689 FileNumber = getTok().getIntVal();
2693 return TokError("file number less than one");
2696 if (getLexer().isNot(AsmToken::String))
2697 return TokError("unexpected token in '.file' directive");
2699 // Usually the directory and filename together, otherwise just the directory.
2700 // Allow the strings to have escaped octal character sequence.
2701 std::string Path = getTok().getString();
2702 if (parseEscapedString(Path))
2706 StringRef Directory;
2708 std::string FilenameData;
2709 if (getLexer().is(AsmToken::String)) {
2710 if (FileNumber == -1)
2711 return TokError("explicit path specified, but no file number");
2712 if (parseEscapedString(FilenameData))
2714 Filename = FilenameData;
2721 if (getLexer().isNot(AsmToken::EndOfStatement))
2722 return TokError("unexpected token in '.file' directive");
2724 if (FileNumber == -1)
2725 getStreamer().EmitFileDirective(Filename);
2727 if (getContext().getGenDwarfForAssembly() == true)
2729 "input can't have .file dwarf directives when -g is "
2730 "used to generate dwarf debug info for assembly code");
2732 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2733 Error(FileNumberLoc, "file number already allocated");
2739 /// parseDirectiveLine
2740 /// ::= .line [number]
2741 bool AsmParser::parseDirectiveLine() {
2742 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2743 if (getLexer().isNot(AsmToken::Integer))
2744 return TokError("unexpected token in '.line' directive");
2746 int64_t LineNumber = getTok().getIntVal();
2750 // FIXME: Do something with the .line.
2753 if (getLexer().isNot(AsmToken::EndOfStatement))
2754 return TokError("unexpected token in '.line' directive");
2759 /// parseDirectiveLoc
2760 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2761 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2762 /// The first number is a file number, must have been previously assigned with
2763 /// a .file directive, the second number is the line number and optionally the
2764 /// third number is a column position (zero if not specified). The remaining
2765 /// optional items are .loc sub-directives.
2766 bool AsmParser::parseDirectiveLoc() {
2767 if (getLexer().isNot(AsmToken::Integer))
2768 return TokError("unexpected token in '.loc' directive");
2769 int64_t FileNumber = getTok().getIntVal();
2771 return TokError("file number less than one in '.loc' directive");
2772 if (!getContext().isValidDwarfFileNumber(FileNumber))
2773 return TokError("unassigned file number in '.loc' directive");
2776 int64_t LineNumber = 0;
2777 if (getLexer().is(AsmToken::Integer)) {
2778 LineNumber = getTok().getIntVal();
2780 return TokError("line number less than zero in '.loc' directive");
2784 int64_t ColumnPos = 0;
2785 if (getLexer().is(AsmToken::Integer)) {
2786 ColumnPos = getTok().getIntVal();
2788 return TokError("column position less than zero in '.loc' directive");
2792 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2794 int64_t Discriminator = 0;
2795 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2797 if (getLexer().is(AsmToken::EndOfStatement))
2801 SMLoc Loc = getTok().getLoc();
2802 if (parseIdentifier(Name))
2803 return TokError("unexpected token in '.loc' directive");
2805 if (Name == "basic_block")
2806 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2807 else if (Name == "prologue_end")
2808 Flags |= DWARF2_FLAG_PROLOGUE_END;
2809 else if (Name == "epilogue_begin")
2810 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2811 else if (Name == "is_stmt") {
2812 Loc = getTok().getLoc();
2813 const MCExpr *Value;
2814 if (parseExpression(Value))
2816 // The expression must be the constant 0 or 1.
2817 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2818 int Value = MCE->getValue();
2820 Flags &= ~DWARF2_FLAG_IS_STMT;
2821 else if (Value == 1)
2822 Flags |= DWARF2_FLAG_IS_STMT;
2824 return Error(Loc, "is_stmt value not 0 or 1");
2826 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2828 } else if (Name == "isa") {
2829 Loc = getTok().getLoc();
2830 const MCExpr *Value;
2831 if (parseExpression(Value))
2833 // The expression must be a constant greater or equal to 0.
2834 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2835 int Value = MCE->getValue();
2837 return Error(Loc, "isa number less than zero");
2840 return Error(Loc, "isa number not a constant value");
2842 } else if (Name == "discriminator") {
2843 if (parseAbsoluteExpression(Discriminator))
2846 return Error(Loc, "unknown sub-directive in '.loc' directive");
2849 if (getLexer().is(AsmToken::EndOfStatement))
2854 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2855 Isa, Discriminator, StringRef());
2860 /// parseDirectiveStabs
2861 /// ::= .stabs string, number, number, number
2862 bool AsmParser::parseDirectiveStabs() {
2863 return TokError("unsupported directive '.stabs'");
2866 /// parseDirectiveCFISections
2867 /// ::= .cfi_sections section [, section]
2868 bool AsmParser::parseDirectiveCFISections() {
2873 if (parseIdentifier(Name))
2874 return TokError("Expected an identifier");
2876 if (Name == ".eh_frame")
2878 else if (Name == ".debug_frame")
2881 if (getLexer().is(AsmToken::Comma)) {
2884 if (parseIdentifier(Name))
2885 return TokError("Expected an identifier");
2887 if (Name == ".eh_frame")
2889 else if (Name == ".debug_frame")
2893 getStreamer().EmitCFISections(EH, Debug);
2897 /// parseDirectiveCFIStartProc
2898 /// ::= .cfi_startproc [simple]
2899 bool AsmParser::parseDirectiveCFIStartProc() {
2901 if (getLexer().isNot(AsmToken::EndOfStatement))
2902 if (parseIdentifier(Simple) || Simple != "simple")
2903 return TokError("unexpected token in .cfi_startproc directive");
2905 getStreamer().EmitCFIStartProc(!Simple.empty());
2909 /// parseDirectiveCFIEndProc
2910 /// ::= .cfi_endproc
2911 bool AsmParser::parseDirectiveCFIEndProc() {
2912 getStreamer().EmitCFIEndProc();
2916 /// \brief parse register name or number.
2917 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2918 SMLoc DirectiveLoc) {
2921 if (getLexer().isNot(AsmToken::Integer)) {
2922 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2924 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2926 return parseAbsoluteExpression(Register);
2931 /// parseDirectiveCFIDefCfa
2932 /// ::= .cfi_def_cfa register, offset
2933 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2934 int64_t Register = 0;
2935 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2938 if (getLexer().isNot(AsmToken::Comma))
2939 return TokError("unexpected token in directive");
2943 if (parseAbsoluteExpression(Offset))
2946 getStreamer().EmitCFIDefCfa(Register, Offset);
2950 /// parseDirectiveCFIDefCfaOffset
2951 /// ::= .cfi_def_cfa_offset offset
2952 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2954 if (parseAbsoluteExpression(Offset))
2957 getStreamer().EmitCFIDefCfaOffset(Offset);
2961 /// parseDirectiveCFIRegister
2962 /// ::= .cfi_register register, register
2963 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2964 int64_t Register1 = 0;
2965 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2968 if (getLexer().isNot(AsmToken::Comma))
2969 return TokError("unexpected token in directive");
2972 int64_t Register2 = 0;
2973 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2976 getStreamer().EmitCFIRegister(Register1, Register2);
2980 /// parseDirectiveCFIWindowSave
2981 /// ::= .cfi_window_save
2982 bool AsmParser::parseDirectiveCFIWindowSave() {
2983 getStreamer().EmitCFIWindowSave();
2987 /// parseDirectiveCFIAdjustCfaOffset
2988 /// ::= .cfi_adjust_cfa_offset adjustment
2989 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2990 int64_t Adjustment = 0;
2991 if (parseAbsoluteExpression(Adjustment))
2994 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2998 /// parseDirectiveCFIDefCfaRegister
2999 /// ::= .cfi_def_cfa_register register
3000 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3001 int64_t Register = 0;
3002 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3005 getStreamer().EmitCFIDefCfaRegister(Register);
3009 /// parseDirectiveCFIOffset
3010 /// ::= .cfi_offset register, offset
3011 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3012 int64_t Register = 0;
3015 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3018 if (getLexer().isNot(AsmToken::Comma))
3019 return TokError("unexpected token in directive");
3022 if (parseAbsoluteExpression(Offset))
3025 getStreamer().EmitCFIOffset(Register, Offset);
3029 /// parseDirectiveCFIRelOffset
3030 /// ::= .cfi_rel_offset register, offset
3031 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3032 int64_t Register = 0;
3034 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3037 if (getLexer().isNot(AsmToken::Comma))
3038 return TokError("unexpected token in directive");
3042 if (parseAbsoluteExpression(Offset))
3045 getStreamer().EmitCFIRelOffset(Register, Offset);
3049 static bool isValidEncoding(int64_t Encoding) {
3050 if (Encoding & ~0xff)
3053 if (Encoding == dwarf::DW_EH_PE_omit)
3056 const unsigned Format = Encoding & 0xf;
3057 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3058 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3059 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3060 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3063 const unsigned Application = Encoding & 0x70;
3064 if (Application != dwarf::DW_EH_PE_absptr &&
3065 Application != dwarf::DW_EH_PE_pcrel)
3071 /// parseDirectiveCFIPersonalityOrLsda
3072 /// IsPersonality true for cfi_personality, false for cfi_lsda
3073 /// ::= .cfi_personality encoding, [symbol_name]
3074 /// ::= .cfi_lsda encoding, [symbol_name]
3075 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3076 int64_t Encoding = 0;
3077 if (parseAbsoluteExpression(Encoding))
3079 if (Encoding == dwarf::DW_EH_PE_omit)
3082 if (!isValidEncoding(Encoding))
3083 return TokError("unsupported encoding.");
3085 if (getLexer().isNot(AsmToken::Comma))
3086 return TokError("unexpected token in directive");
3090 if (parseIdentifier(Name))
3091 return TokError("expected identifier in directive");
3093 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3096 getStreamer().EmitCFIPersonality(Sym, Encoding);
3098 getStreamer().EmitCFILsda(Sym, Encoding);
3102 /// parseDirectiveCFIRememberState
3103 /// ::= .cfi_remember_state
3104 bool AsmParser::parseDirectiveCFIRememberState() {
3105 getStreamer().EmitCFIRememberState();
3109 /// parseDirectiveCFIRestoreState
3110 /// ::= .cfi_remember_state
3111 bool AsmParser::parseDirectiveCFIRestoreState() {
3112 getStreamer().EmitCFIRestoreState();
3116 /// parseDirectiveCFISameValue
3117 /// ::= .cfi_same_value register
3118 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3119 int64_t Register = 0;
3121 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3124 getStreamer().EmitCFISameValue(Register);
3128 /// parseDirectiveCFIRestore
3129 /// ::= .cfi_restore register
3130 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3131 int64_t Register = 0;
3132 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3135 getStreamer().EmitCFIRestore(Register);
3139 /// parseDirectiveCFIEscape
3140 /// ::= .cfi_escape expression[,...]
3141 bool AsmParser::parseDirectiveCFIEscape() {
3144 if (parseAbsoluteExpression(CurrValue))
3147 Values.push_back((uint8_t)CurrValue);
3149 while (getLexer().is(AsmToken::Comma)) {
3152 if (parseAbsoluteExpression(CurrValue))
3155 Values.push_back((uint8_t)CurrValue);
3158 getStreamer().EmitCFIEscape(Values);
3162 /// parseDirectiveCFISignalFrame
3163 /// ::= .cfi_signal_frame
3164 bool AsmParser::parseDirectiveCFISignalFrame() {
3165 if (getLexer().isNot(AsmToken::EndOfStatement))
3166 return Error(getLexer().getLoc(),
3167 "unexpected token in '.cfi_signal_frame'");
3169 getStreamer().EmitCFISignalFrame();
3173 /// parseDirectiveCFIUndefined
3174 /// ::= .cfi_undefined register
3175 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3176 int64_t Register = 0;
3178 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3181 getStreamer().EmitCFIUndefined(Register);
3185 /// parseDirectiveMacrosOnOff
3188 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3189 if (getLexer().isNot(AsmToken::EndOfStatement))
3190 return Error(getLexer().getLoc(),
3191 "unexpected token in '" + Directive + "' directive");
3193 setMacrosEnabled(Directive == ".macros_on");
3197 /// parseDirectiveMacro
3198 /// ::= .macro name[,] [parameters]
3199 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3201 if (parseIdentifier(Name))
3202 return TokError("expected identifier in '.macro' directive");
3204 if (getLexer().is(AsmToken::Comma))
3207 MCAsmMacroParameters Parameters;
3208 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3209 MCAsmMacroParameter Parameter;
3210 if (parseIdentifier(Parameter.Name))
3211 return TokError("expected identifier in '.macro' directive");
3213 if (getLexer().is(AsmToken::Equal)) {
3215 if (parseMacroArgument(Parameter.Value))
3219 Parameters.push_back(Parameter);
3221 if (getLexer().is(AsmToken::Comma))
3225 // Eat the end of statement.
3228 AsmToken EndToken, StartToken = getTok();
3229 unsigned MacroDepth = 0;
3231 // Lex the macro definition.
3233 // Check whether we have reached the end of the file.
3234 if (getLexer().is(AsmToken::Eof))
3235 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3237 // Otherwise, check whether we have reach the .endmacro.
3238 if (getLexer().is(AsmToken::Identifier)) {
3239 if (getTok().getIdentifier() == ".endm" ||
3240 getTok().getIdentifier() == ".endmacro") {
3241 if (MacroDepth == 0) { // Outermost macro.
3242 EndToken = getTok();
3244 if (getLexer().isNot(AsmToken::EndOfStatement))
3245 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3249 // Otherwise we just found the end of an inner macro.
3252 } else if (getTok().getIdentifier() == ".macro") {
3253 // We allow nested macros. Those aren't instantiated until the outermost
3254 // macro is expanded so just ignore them for now.
3259 // Otherwise, scan til the end of the statement.
3260 eatToEndOfStatement();
3263 if (lookupMacro(Name)) {
3264 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3267 const char *BodyStart = StartToken.getLoc().getPointer();
3268 const char *BodyEnd = EndToken.getLoc().getPointer();
3269 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3270 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3271 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3275 /// checkForBadMacro
3277 /// With the support added for named parameters there may be code out there that
3278 /// is transitioning from positional parameters. In versions of gas that did
3279 /// not support named parameters they would be ignored on the macro definition.
3280 /// But to support both styles of parameters this is not possible so if a macro
3281 /// definition has named parameters but does not use them and has what appears
3282 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3283 /// warning that the positional parameter found in body which have no effect.
3284 /// Hoping the developer will either remove the named parameters from the macro
3285 /// definition so the positional parameters get used if that was what was
3286 /// intended or change the macro to use the named parameters. It is possible
3287 /// this warning will trigger when the none of the named parameters are used
3288 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3289 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3291 ArrayRef<MCAsmMacroParameter> Parameters) {
3292 // If this macro is not defined with named parameters the warning we are
3293 // checking for here doesn't apply.
3294 unsigned NParameters = Parameters.size();
3295 if (NParameters == 0)
3298 bool NamedParametersFound = false;
3299 bool PositionalParametersFound = false;
3301 // Look at the body of the macro for use of both the named parameters and what
3302 // are likely to be positional parameters. This is what expandMacro() is
3303 // doing when it finds the parameters in the body.
3304 while (!Body.empty()) {
3305 // Scan for the next possible parameter.
3306 std::size_t End = Body.size(), Pos = 0;
3307 for (; Pos != End; ++Pos) {
3308 // Check for a substitution or escape.
3309 // This macro is defined with parameters, look for \foo, \bar, etc.
3310 if (Body[Pos] == '\\' && Pos + 1 != End)
3313 // This macro should have parameters, but look for $0, $1, ..., $n too.
3314 if (Body[Pos] != '$' || Pos + 1 == End)
3316 char Next = Body[Pos + 1];
3317 if (Next == '$' || Next == 'n' ||
3318 isdigit(static_cast<unsigned char>(Next)))
3322 // Check if we reached the end.
3326 if (Body[Pos] == '$') {
3327 switch (Body[Pos + 1]) {
3332 // $n => number of arguments
3334 PositionalParametersFound = true;
3337 // $[0-9] => argument
3339 PositionalParametersFound = true;
3345 unsigned I = Pos + 1;
3346 while (isIdentifierChar(Body[I]) && I + 1 != End)
3349 const char *Begin = Body.data() + Pos + 1;
3350 StringRef Argument(Begin, I - (Pos + 1));
3352 for (; Index < NParameters; ++Index)
3353 if (Parameters[Index].Name == Argument)
3356 if (Index == NParameters) {
3357 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3363 NamedParametersFound = true;
3364 Pos += 1 + Argument.size();
3367 // Update the scan point.
3368 Body = Body.substr(Pos);
3371 if (!NamedParametersFound && PositionalParametersFound)
3372 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3373 "used in macro body, possible positional parameter "
3374 "found in body which will have no effect");
3377 /// parseDirectiveEndMacro
3380 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3381 if (getLexer().isNot(AsmToken::EndOfStatement))
3382 return TokError("unexpected token in '" + Directive + "' directive");
3384 // If we are inside a macro instantiation, terminate the current
3386 if (isInsideMacroInstantiation()) {
3391 // Otherwise, this .endmacro is a stray entry in the file; well formed
3392 // .endmacro directives are handled during the macro definition parsing.
3393 return TokError("unexpected '" + Directive + "' in file, "
3394 "no current macro definition");
3397 /// parseDirectivePurgeMacro
3399 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3401 if (parseIdentifier(Name))
3402 return TokError("expected identifier in '.purgem' directive");
3404 if (getLexer().isNot(AsmToken::EndOfStatement))
3405 return TokError("unexpected token in '.purgem' directive");
3407 if (!lookupMacro(Name))
3408 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3410 undefineMacro(Name);
3414 /// parseDirectiveBundleAlignMode
3415 /// ::= {.bundle_align_mode} expression
3416 bool AsmParser::parseDirectiveBundleAlignMode() {
3417 checkForValidSection();
3419 // Expect a single argument: an expression that evaluates to a constant
3420 // in the inclusive range 0-30.
3421 SMLoc ExprLoc = getLexer().getLoc();
3422 int64_t AlignSizePow2;
3423 if (parseAbsoluteExpression(AlignSizePow2))
3425 else if (getLexer().isNot(AsmToken::EndOfStatement))
3426 return TokError("unexpected token after expression in"
3427 " '.bundle_align_mode' directive");
3428 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3429 return Error(ExprLoc,
3430 "invalid bundle alignment size (expected between 0 and 30)");
3434 // Because of AlignSizePow2's verified range we can safely truncate it to
3436 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3440 /// parseDirectiveBundleLock
3441 /// ::= {.bundle_lock} [align_to_end]
3442 bool AsmParser::parseDirectiveBundleLock() {
3443 checkForValidSection();
3444 bool AlignToEnd = false;
3446 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3448 SMLoc Loc = getTok().getLoc();
3449 const char *kInvalidOptionError =
3450 "invalid option for '.bundle_lock' directive";
3452 if (parseIdentifier(Option))
3453 return Error(Loc, kInvalidOptionError);
3455 if (Option != "align_to_end")
3456 return Error(Loc, kInvalidOptionError);
3457 else if (getLexer().isNot(AsmToken::EndOfStatement))
3459 "unexpected token after '.bundle_lock' directive option");
3465 getStreamer().EmitBundleLock(AlignToEnd);
3469 /// parseDirectiveBundleLock
3470 /// ::= {.bundle_lock}
3471 bool AsmParser::parseDirectiveBundleUnlock() {
3472 checkForValidSection();
3474 if (getLexer().isNot(AsmToken::EndOfStatement))
3475 return TokError("unexpected token in '.bundle_unlock' directive");
3478 getStreamer().EmitBundleUnlock();
3482 /// parseDirectiveSpace
3483 /// ::= (.skip | .space) expression [ , expression ]
3484 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3485 checkForValidSection();
3488 if (parseAbsoluteExpression(NumBytes))
3491 int64_t FillExpr = 0;
3492 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3493 if (getLexer().isNot(AsmToken::Comma))
3494 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3497 if (parseAbsoluteExpression(FillExpr))
3500 if (getLexer().isNot(AsmToken::EndOfStatement))
3501 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3507 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3510 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3511 getStreamer().EmitFill(NumBytes, FillExpr);
3516 /// parseDirectiveLEB128
3517 /// ::= (.sleb128 | .uleb128) expression
3518 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3519 checkForValidSection();
3520 const MCExpr *Value;
3522 if (parseExpression(Value))
3525 if (getLexer().isNot(AsmToken::EndOfStatement))
3526 return TokError("unexpected token in directive");
3529 getStreamer().EmitSLEB128Value(Value);
3531 getStreamer().EmitULEB128Value(Value);
3536 /// parseDirectiveSymbolAttribute
3537 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3538 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3539 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3542 SMLoc Loc = getTok().getLoc();
3544 if (parseIdentifier(Name))
3545 return Error(Loc, "expected identifier in directive");
3547 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3549 // Assembler local symbols don't make any sense here. Complain loudly.
3550 if (Sym->isTemporary())
3551 return Error(Loc, "non-local symbol required in directive");
3553 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3554 return Error(Loc, "unable to emit symbol attribute");
3556 if (getLexer().is(AsmToken::EndOfStatement))
3559 if (getLexer().isNot(AsmToken::Comma))
3560 return TokError("unexpected token in directive");
3569 /// parseDirectiveComm
3570 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3571 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3572 checkForValidSection();
3574 SMLoc IDLoc = getLexer().getLoc();
3576 if (parseIdentifier(Name))
3577 return TokError("expected identifier in directive");
3579 // Handle the identifier as the key symbol.
3580 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3582 if (getLexer().isNot(AsmToken::Comma))
3583 return TokError("unexpected token in directive");
3587 SMLoc SizeLoc = getLexer().getLoc();
3588 if (parseAbsoluteExpression(Size))
3591 int64_t Pow2Alignment = 0;
3592 SMLoc Pow2AlignmentLoc;
3593 if (getLexer().is(AsmToken::Comma)) {
3595 Pow2AlignmentLoc = getLexer().getLoc();
3596 if (parseAbsoluteExpression(Pow2Alignment))
3599 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3600 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3601 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3603 // If this target takes alignments in bytes (not log) validate and convert.
3604 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3605 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3606 if (!isPowerOf2_64(Pow2Alignment))
3607 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3608 Pow2Alignment = Log2_64(Pow2Alignment);
3612 if (getLexer().isNot(AsmToken::EndOfStatement))
3613 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3617 // NOTE: a size of zero for a .comm should create a undefined symbol
3618 // but a size of .lcomm creates a bss symbol of size zero.
3620 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3621 "be less than zero");
3623 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3624 // may internally end up wanting an alignment in bytes.
3625 // FIXME: Diagnose overflow.
3626 if (Pow2Alignment < 0)
3627 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3628 "alignment, can't be less than zero");
3630 if (!Sym->isUndefined())
3631 return Error(IDLoc, "invalid symbol redefinition");
3633 // Create the Symbol as a common or local common with Size and Pow2Alignment
3635 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3639 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3643 /// parseDirectiveAbort
3644 /// ::= .abort [... message ...]
3645 bool AsmParser::parseDirectiveAbort() {
3646 // FIXME: Use loc from directive.
3647 SMLoc Loc = getLexer().getLoc();
3649 StringRef Str = parseStringToEndOfStatement();
3650 if (getLexer().isNot(AsmToken::EndOfStatement))
3651 return TokError("unexpected token in '.abort' directive");
3656 Error(Loc, ".abort detected. Assembly stopping.");
3658 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3659 // FIXME: Actually abort assembly here.
3664 /// parseDirectiveInclude
3665 /// ::= .include "filename"
3666 bool AsmParser::parseDirectiveInclude() {
3667 if (getLexer().isNot(AsmToken::String))
3668 return TokError("expected string in '.include' directive");
3670 // Allow the strings to have escaped octal character sequence.
3671 std::string Filename;
3672 if (parseEscapedString(Filename))
3674 SMLoc IncludeLoc = getLexer().getLoc();
3677 if (getLexer().isNot(AsmToken::EndOfStatement))
3678 return TokError("unexpected token in '.include' directive");
3680 // Attempt to switch the lexer to the included file before consuming the end
3681 // of statement to avoid losing it when we switch.
3682 if (enterIncludeFile(Filename)) {
3683 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3690 /// parseDirectiveIncbin
3691 /// ::= .incbin "filename"
3692 bool AsmParser::parseDirectiveIncbin() {
3693 if (getLexer().isNot(AsmToken::String))
3694 return TokError("expected string in '.incbin' directive");
3696 // Allow the strings to have escaped octal character sequence.
3697 std::string Filename;
3698 if (parseEscapedString(Filename))
3700 SMLoc IncbinLoc = getLexer().getLoc();
3703 if (getLexer().isNot(AsmToken::EndOfStatement))
3704 return TokError("unexpected token in '.incbin' directive");
3706 // Attempt to process the included file.
3707 if (processIncbinFile(Filename)) {
3708 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3715 /// parseDirectiveIf
3716 /// ::= .if expression
3717 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3718 TheCondStack.push_back(TheCondState);
3719 TheCondState.TheCond = AsmCond::IfCond;
3720 if (TheCondState.Ignore) {
3721 eatToEndOfStatement();
3724 if (parseAbsoluteExpression(ExprValue))
3727 if (getLexer().isNot(AsmToken::EndOfStatement))
3728 return TokError("unexpected token in '.if' directive");
3732 TheCondState.CondMet = ExprValue;
3733 TheCondState.Ignore = !TheCondState.CondMet;
3739 /// parseDirectiveIfb
3741 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3742 TheCondStack.push_back(TheCondState);
3743 TheCondState.TheCond = AsmCond::IfCond;
3745 if (TheCondState.Ignore) {
3746 eatToEndOfStatement();
3748 StringRef Str = parseStringToEndOfStatement();
3750 if (getLexer().isNot(AsmToken::EndOfStatement))
3751 return TokError("unexpected token in '.ifb' directive");
3755 TheCondState.CondMet = ExpectBlank == Str.empty();
3756 TheCondState.Ignore = !TheCondState.CondMet;
3762 /// parseDirectiveIfc
3763 /// ::= .ifc string1, string2
3764 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3765 TheCondStack.push_back(TheCondState);
3766 TheCondState.TheCond = AsmCond::IfCond;
3768 if (TheCondState.Ignore) {
3769 eatToEndOfStatement();
3771 StringRef Str1 = parseStringToComma();
3773 if (getLexer().isNot(AsmToken::Comma))
3774 return TokError("unexpected token in '.ifc' directive");
3778 StringRef Str2 = parseStringToEndOfStatement();
3780 if (getLexer().isNot(AsmToken::EndOfStatement))
3781 return TokError("unexpected token in '.ifc' directive");
3785 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3786 TheCondState.Ignore = !TheCondState.CondMet;
3792 /// parseDirectiveIfdef
3793 /// ::= .ifdef symbol
3794 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3796 TheCondStack.push_back(TheCondState);
3797 TheCondState.TheCond = AsmCond::IfCond;
3799 if (TheCondState.Ignore) {
3800 eatToEndOfStatement();
3802 if (parseIdentifier(Name))
3803 return TokError("expected identifier after '.ifdef'");
3807 MCSymbol *Sym = getContext().LookupSymbol(Name);
3810 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3812 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3813 TheCondState.Ignore = !TheCondState.CondMet;
3819 /// parseDirectiveElseIf
3820 /// ::= .elseif expression
3821 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3822 if (TheCondState.TheCond != AsmCond::IfCond &&
3823 TheCondState.TheCond != AsmCond::ElseIfCond)
3824 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3826 TheCondState.TheCond = AsmCond::ElseIfCond;
3828 bool LastIgnoreState = false;
3829 if (!TheCondStack.empty())
3830 LastIgnoreState = TheCondStack.back().Ignore;
3831 if (LastIgnoreState || TheCondState.CondMet) {
3832 TheCondState.Ignore = true;
3833 eatToEndOfStatement();
3836 if (parseAbsoluteExpression(ExprValue))
3839 if (getLexer().isNot(AsmToken::EndOfStatement))
3840 return TokError("unexpected token in '.elseif' directive");
3843 TheCondState.CondMet = ExprValue;
3844 TheCondState.Ignore = !TheCondState.CondMet;
3850 /// parseDirectiveElse
3852 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3853 if (getLexer().isNot(AsmToken::EndOfStatement))
3854 return TokError("unexpected token in '.else' directive");
3858 if (TheCondState.TheCond != AsmCond::IfCond &&
3859 TheCondState.TheCond != AsmCond::ElseIfCond)
3860 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3862 TheCondState.TheCond = AsmCond::ElseCond;
3863 bool LastIgnoreState = false;
3864 if (!TheCondStack.empty())
3865 LastIgnoreState = TheCondStack.back().Ignore;
3866 if (LastIgnoreState || TheCondState.CondMet)
3867 TheCondState.Ignore = true;
3869 TheCondState.Ignore = false;
3874 /// parseDirectiveEnd
3876 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3877 if (getLexer().isNot(AsmToken::EndOfStatement))
3878 return TokError("unexpected token in '.end' directive");
3882 while (Lexer.isNot(AsmToken::Eof))
3888 /// parseDirectiveEndIf
3890 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3891 if (getLexer().isNot(AsmToken::EndOfStatement))
3892 return TokError("unexpected token in '.endif' directive");
3896 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3897 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3899 if (!TheCondStack.empty()) {
3900 TheCondState = TheCondStack.back();
3901 TheCondStack.pop_back();
3907 void AsmParser::initializeDirectiveKindMap() {
3908 DirectiveKindMap[".set"] = DK_SET;
3909 DirectiveKindMap[".equ"] = DK_EQU;
3910 DirectiveKindMap[".equiv"] = DK_EQUIV;
3911 DirectiveKindMap[".ascii"] = DK_ASCII;
3912 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3913 DirectiveKindMap[".string"] = DK_STRING;
3914 DirectiveKindMap[".byte"] = DK_BYTE;
3915 DirectiveKindMap[".short"] = DK_SHORT;
3916 DirectiveKindMap[".value"] = DK_VALUE;
3917 DirectiveKindMap[".2byte"] = DK_2BYTE;
3918 DirectiveKindMap[".long"] = DK_LONG;
3919 DirectiveKindMap[".int"] = DK_INT;
3920 DirectiveKindMap[".4byte"] = DK_4BYTE;
3921 DirectiveKindMap[".quad"] = DK_QUAD;
3922 DirectiveKindMap[".8byte"] = DK_8BYTE;
3923 DirectiveKindMap[".octa"] = DK_OCTA;
3924 DirectiveKindMap[".single"] = DK_SINGLE;
3925 DirectiveKindMap[".float"] = DK_FLOAT;
3926 DirectiveKindMap[".double"] = DK_DOUBLE;
3927 DirectiveKindMap[".align"] = DK_ALIGN;
3928 DirectiveKindMap[".align32"] = DK_ALIGN32;
3929 DirectiveKindMap[".balign"] = DK_BALIGN;
3930 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3931 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3932 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3933 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3934 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3935 DirectiveKindMap[".org"] = DK_ORG;
3936 DirectiveKindMap[".fill"] = DK_FILL;
3937 DirectiveKindMap[".zero"] = DK_ZERO;
3938 DirectiveKindMap[".extern"] = DK_EXTERN;
3939 DirectiveKindMap[".globl"] = DK_GLOBL;
3940 DirectiveKindMap[".global"] = DK_GLOBAL;
3941 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3942 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3943 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3944 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3945 DirectiveKindMap[".reference"] = DK_REFERENCE;
3946 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3947 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3948 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3949 DirectiveKindMap[".comm"] = DK_COMM;
3950 DirectiveKindMap[".common"] = DK_COMMON;
3951 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3952 DirectiveKindMap[".abort"] = DK_ABORT;
3953 DirectiveKindMap[".include"] = DK_INCLUDE;
3954 DirectiveKindMap[".incbin"] = DK_INCBIN;
3955 DirectiveKindMap[".code16"] = DK_CODE16;
3956 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3957 DirectiveKindMap[".rept"] = DK_REPT;
3958 DirectiveKindMap[".rep"] = DK_REPT;
3959 DirectiveKindMap[".irp"] = DK_IRP;
3960 DirectiveKindMap[".irpc"] = DK_IRPC;
3961 DirectiveKindMap[".endr"] = DK_ENDR;
3962 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3963 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3964 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3965 DirectiveKindMap[".if"] = DK_IF;
3966 DirectiveKindMap[".ifb"] = DK_IFB;
3967 DirectiveKindMap[".ifnb"] = DK_IFNB;
3968 DirectiveKindMap[".ifc"] = DK_IFC;
3969 DirectiveKindMap[".ifnc"] = DK_IFNC;
3970 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3971 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3972 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3973 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3974 DirectiveKindMap[".else"] = DK_ELSE;
3975 DirectiveKindMap[".end"] = DK_END;
3976 DirectiveKindMap[".endif"] = DK_ENDIF;
3977 DirectiveKindMap[".skip"] = DK_SKIP;
3978 DirectiveKindMap[".space"] = DK_SPACE;
3979 DirectiveKindMap[".file"] = DK_FILE;
3980 DirectiveKindMap[".line"] = DK_LINE;
3981 DirectiveKindMap[".loc"] = DK_LOC;
3982 DirectiveKindMap[".stabs"] = DK_STABS;
3983 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3984 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3985 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3986 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3987 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3988 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3989 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3990 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3991 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3992 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3993 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3994 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3995 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3996 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3997 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3998 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3999 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4000 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4001 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4002 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4003 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4004 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4005 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4006 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4007 DirectiveKindMap[".macro"] = DK_MACRO;
4008 DirectiveKindMap[".endm"] = DK_ENDM;
4009 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4010 DirectiveKindMap[".purgem"] = DK_PURGEM;
4013 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4014 AsmToken EndToken, StartToken = getTok();
4016 unsigned NestLevel = 0;
4018 // Check whether we have reached the end of the file.
4019 if (getLexer().is(AsmToken::Eof)) {
4020 Error(DirectiveLoc, "no matching '.endr' in definition");
4024 if (Lexer.is(AsmToken::Identifier) &&
4025 (getTok().getIdentifier() == ".rept")) {
4029 // Otherwise, check whether we have reached the .endr.
4030 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4031 if (NestLevel == 0) {
4032 EndToken = getTok();
4034 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4035 TokError("unexpected token in '.endr' directive");
4043 // Otherwise, scan till the end of the statement.
4044 eatToEndOfStatement();
4047 const char *BodyStart = StartToken.getLoc().getPointer();
4048 const char *BodyEnd = EndToken.getLoc().getPointer();
4049 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4051 // We Are Anonymous.
4052 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4053 return &MacroLikeBodies.back();
4056 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4057 raw_svector_ostream &OS) {
4060 MemoryBuffer *Instantiation =
4061 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4063 // Create the macro instantiation object and add to the current macro
4064 // instantiation stack.
4065 MacroInstantiation *MI = new MacroInstantiation(
4066 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4067 ActiveMacros.push_back(MI);
4069 // Jump to the macro instantiation and prime the lexer.
4070 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4071 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4075 /// parseDirectiveRept
4076 /// ::= .rep | .rept count
4077 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4078 const MCExpr *CountExpr;
4079 SMLoc CountLoc = getTok().getLoc();
4080 if (parseExpression(CountExpr))
4084 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4085 eatToEndOfStatement();
4086 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4090 return Error(CountLoc, "Count is negative");
4092 if (Lexer.isNot(AsmToken::EndOfStatement))
4093 return TokError("unexpected token in '" + Dir + "' directive");
4095 // Eat the end of statement.
4098 // Lex the rept definition.
4099 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4103 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4104 // to hold the macro body with substitutions.
4105 SmallString<256> Buf;
4106 raw_svector_ostream OS(Buf);
4108 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4111 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4116 /// parseDirectiveIrp
4117 /// ::= .irp symbol,values
4118 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4119 MCAsmMacroParameter Parameter;
4121 if (parseIdentifier(Parameter.Name))
4122 return TokError("expected identifier in '.irp' directive");
4124 if (Lexer.isNot(AsmToken::Comma))
4125 return TokError("expected comma in '.irp' directive");
4129 MCAsmMacroArguments A;
4130 if (parseMacroArguments(0, A))
4133 // Eat the end of statement.
4136 // Lex the irp definition.
4137 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4141 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4142 // to hold the macro body with substitutions.
4143 SmallString<256> Buf;
4144 raw_svector_ostream OS(Buf);
4146 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4147 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4151 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4156 /// parseDirectiveIrpc
4157 /// ::= .irpc symbol,values
4158 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4159 MCAsmMacroParameter Parameter;
4161 if (parseIdentifier(Parameter.Name))
4162 return TokError("expected identifier in '.irpc' directive");
4164 if (Lexer.isNot(AsmToken::Comma))
4165 return TokError("expected comma in '.irpc' directive");
4169 MCAsmMacroArguments A;
4170 if (parseMacroArguments(0, A))
4173 if (A.size() != 1 || A.front().size() != 1)
4174 return TokError("unexpected token in '.irpc' directive");
4176 // Eat the end of statement.
4179 // Lex the irpc definition.
4180 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4184 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4185 // to hold the macro body with substitutions.
4186 SmallString<256> Buf;
4187 raw_svector_ostream OS(Buf);
4189 StringRef Values = A.front().front().getString();
4190 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4191 MCAsmMacroArgument Arg;
4192 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4194 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4198 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4203 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4204 if (ActiveMacros.empty())
4205 return TokError("unmatched '.endr' directive");
4207 // The only .repl that should get here are the ones created by
4208 // instantiateMacroLikeBody.
4209 assert(getLexer().is(AsmToken::EndOfStatement));
4215 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4217 const MCExpr *Value;
4218 SMLoc ExprLoc = getLexer().getLoc();
4219 if (parseExpression(Value))
4221 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4223 return Error(ExprLoc, "unexpected expression in _emit");
4224 uint64_t IntValue = MCE->getValue();
4225 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4226 return Error(ExprLoc, "literal value out of range for directive");
4228 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4232 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4233 const MCExpr *Value;
4234 SMLoc ExprLoc = getLexer().getLoc();
4235 if (parseExpression(Value))
4237 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4239 return Error(ExprLoc, "unexpected expression in align");
4240 uint64_t IntValue = MCE->getValue();
4241 if (!isPowerOf2_64(IntValue))
4242 return Error(ExprLoc, "literal value not a power of two greater then zero");
4244 Info.AsmRewrites->push_back(
4245 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4249 // We are comparing pointers, but the pointers are relative to a single string.
4250 // Thus, this should always be deterministic.
4251 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4252 const AsmRewrite *AsmRewriteB) {
4253 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4255 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4258 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4259 // rewrite to the same location. Make sure the SizeDirective rewrite is
4260 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4261 // ensures the sort algorithm is stable.
4262 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4263 AsmRewritePrecedence[AsmRewriteB->Kind])
4266 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4267 AsmRewritePrecedence[AsmRewriteB->Kind])
4269 llvm_unreachable("Unstable rewrite sort.");
4272 bool AsmParser::parseMSInlineAsm(
4273 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4274 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4275 SmallVectorImpl<std::string> &Constraints,
4276 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4277 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4278 SmallVector<void *, 4> InputDecls;
4279 SmallVector<void *, 4> OutputDecls;
4280 SmallVector<bool, 4> InputDeclsAddressOf;
4281 SmallVector<bool, 4> OutputDeclsAddressOf;
4282 SmallVector<std::string, 4> InputConstraints;
4283 SmallVector<std::string, 4> OutputConstraints;
4284 SmallVector<unsigned, 4> ClobberRegs;
4286 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4291 // While we have input, parse each statement.
4292 unsigned InputIdx = 0;
4293 unsigned OutputIdx = 0;
4294 while (getLexer().isNot(AsmToken::Eof)) {
4295 ParseStatementInfo Info(&AsmStrRewrites);
4296 if (parseStatement(Info))
4299 if (Info.ParseError)
4302 if (Info.Opcode == ~0U)
4305 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4307 // Build the list of clobbers, outputs and inputs.
4308 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4309 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4312 if (Operand->isImm())
4315 // Register operand.
4316 if (Operand->isReg() && !Operand->needAddressOf()) {
4317 unsigned NumDefs = Desc.getNumDefs();
4319 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4320 ClobberRegs.push_back(Operand->getReg());
4324 // Expr/Input or Output.
4325 StringRef SymName = Operand->getSymName();
4326 if (SymName.empty())
4329 void *OpDecl = Operand->getOpDecl();
4333 bool isOutput = (i == 1) && Desc.mayStore();
4334 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4337 OutputDecls.push_back(OpDecl);
4338 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4339 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4340 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4342 InputDecls.push_back(OpDecl);
4343 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4344 InputConstraints.push_back(Operand->getConstraint().str());
4345 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4349 // Consider implicit defs to be clobbers. Think of cpuid and push.
4350 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4351 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4352 ClobberRegs.push_back(ImpDefs[I]);
4355 // Set the number of Outputs and Inputs.
4356 NumOutputs = OutputDecls.size();
4357 NumInputs = InputDecls.size();
4359 // Set the unique clobbers.
4360 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4361 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4363 Clobbers.assign(ClobberRegs.size(), std::string());
4364 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4365 raw_string_ostream OS(Clobbers[I]);
4366 IP->printRegName(OS, ClobberRegs[I]);
4369 // Merge the various outputs and inputs. Output are expected first.
4370 if (NumOutputs || NumInputs) {
4371 unsigned NumExprs = NumOutputs + NumInputs;
4372 OpDecls.resize(NumExprs);
4373 Constraints.resize(NumExprs);
4374 for (unsigned i = 0; i < NumOutputs; ++i) {
4375 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4376 Constraints[i] = OutputConstraints[i];
4378 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4379 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4380 Constraints[j] = InputConstraints[i];
4384 // Build the IR assembly string.
4385 std::string AsmStringIR;
4386 raw_string_ostream OS(AsmStringIR);
4387 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4388 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4389 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4390 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4391 E = AsmStrRewrites.end();
4393 AsmRewriteKind Kind = (*I).Kind;
4394 if (Kind == AOK_Delete)
4397 const char *Loc = (*I).Loc.getPointer();
4398 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4400 // Emit everything up to the immediate/expression.
4401 unsigned Len = Loc - AsmStart;
4403 OS << StringRef(AsmStart, Len);
4405 // Skip the original expression.
4406 if (Kind == AOK_Skip) {
4407 AsmStart = Loc + (*I).Len;
4411 unsigned AdditionalSkip = 0;
4412 // Rewrite expressions in $N notation.
4417 OS << "$$" << (*I).Val;
4423 OS << '$' << InputIdx++;
4426 OS << '$' << OutputIdx++;
4428 case AOK_SizeDirective:
4431 case 8: OS << "byte ptr "; break;
4432 case 16: OS << "word ptr "; break;
4433 case 32: OS << "dword ptr "; break;
4434 case 64: OS << "qword ptr "; break;
4435 case 80: OS << "xword ptr "; break;
4436 case 128: OS << "xmmword ptr "; break;
4437 case 256: OS << "ymmword ptr "; break;
4444 unsigned Val = (*I).Val;
4445 OS << ".align " << Val;
4447 // Skip the original immediate.
4448 assert(Val < 10 && "Expected alignment less then 2^10.");
4449 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4452 case AOK_DotOperator:
4457 // Skip the original expression.
4458 AsmStart = Loc + (*I).Len + AdditionalSkip;
4461 // Emit the remainder of the asm string.
4462 if (AsmStart != AsmEnd)
4463 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4465 AsmString = OS.str();
4469 /// \brief Create an MCAsmParser instance.
4470 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4471 MCStreamer &Out, const MCAsmInfo &MAI) {
4472 return new AsmParser(SM, C, Out, MAI);