1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 FatalAssemblerWarnings("fatal-assembler-warnings",
49 cl::desc("Consider warnings as error"));
51 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
55 /// \brief Helper types for tracking macro definitions.
56 typedef std::vector<AsmToken> MCAsmMacroArgument;
57 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
59 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
64 MCAsmMacroParameters Parameters;
67 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
68 Name(N), Body(B), Parameters(P) {}
70 MCAsmMacro(const MCAsmMacro& Other)
71 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
74 /// \brief Helper class for storing information about an active macro
76 struct MacroInstantiation {
77 /// The macro being instantiated.
78 const MCAsmMacro *TheMacro;
80 /// The macro instantiation with substitutions.
81 MemoryBuffer *Instantiation;
83 /// The location of the instantiation.
84 SMLoc InstantiationLoc;
86 /// The buffer where parsing should resume upon instantiation completion.
89 /// The location where parsing should resume upon instantiation completion.
93 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
97 struct ParseStatementInfo {
98 /// \brief The parsed operands from the last parsed statement.
99 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
101 /// \brief The opcode from the last parsed instruction.
104 /// \brief Was there an error parsing the inline assembly?
107 SmallVectorImpl<AsmRewrite> *AsmRewrites;
109 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
110 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
111 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
113 ~ParseStatementInfo() {
114 // Free any parsed operands.
115 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
116 delete ParsedOperands[i];
117 ParsedOperands.clear();
121 /// \brief The concrete assembly parser instance.
122 class AsmParser : public MCAsmParser {
123 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
124 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
129 const MCAsmInfo &MAI;
131 SourceMgr::DiagHandlerTy SavedDiagHandler;
132 void *SavedDiagContext;
133 MCAsmParserExtension *PlatformParser;
135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
139 AsmCond TheCondState;
140 std::vector<AsmCond> TheCondStack;
142 /// \brief maps directive names to handler methods in parser
143 /// extensions. Extensions register themselves in this map by calling
144 /// addDirectiveHandler.
145 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
147 /// \brief Map of currently defined macros.
148 StringMap<MCAsmMacro*> MacroMap;
150 /// \brief Stack of active macro instantiations.
151 std::vector<MacroInstantiation*> ActiveMacros;
153 /// \brief List of bodies of anonymous macros.
154 std::deque<MCAsmMacro> MacroLikeBodies;
156 /// Boolean tracking whether macro substitution is enabled.
157 unsigned MacrosEnabledFlag : 1;
159 /// Flag tracking whether any errors have been encountered.
160 unsigned HadError : 1;
162 /// The values from the last parsed cpp hash file line comment if any.
163 StringRef CppHashFilename;
164 int64_t CppHashLineNumber;
167 /// When generating dwarf for assembly source files we need to calculate the
168 /// logical line number based on the last parsed cpp hash file line comment
169 /// and current line. Since this is slow and messes up the SourceMgr's
170 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
171 SMLoc LastQueryIDLoc;
173 unsigned LastQueryLine;
175 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
176 unsigned AssemblerDialect;
178 /// \brief is Darwin compatibility enabled?
181 /// \brief Are we parsing ms-style inline assembly?
182 bool ParsingInlineAsm;
185 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
186 const MCAsmInfo &MAI);
187 virtual ~AsmParser();
189 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
191 virtual void addDirectiveHandler(StringRef Directive,
192 ExtensionDirectiveHandler Handler) {
193 ExtensionDirectiveMap[Directive] = Handler;
197 /// @name MCAsmParser Interface
200 virtual SourceMgr &getSourceManager() { return SrcMgr; }
201 virtual MCAsmLexer &getLexer() { return Lexer; }
202 virtual MCContext &getContext() { return Ctx; }
203 virtual MCStreamer &getStreamer() { return Out; }
204 virtual unsigned getAssemblerDialect() {
205 if (AssemblerDialect == ~0U)
206 return MAI.getAssemblerDialect();
208 return AssemblerDialect;
210 virtual void setAssemblerDialect(unsigned i) {
211 AssemblerDialect = i;
214 virtual void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None);
215 virtual bool Warning(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None);
217 virtual bool Error(SMLoc L, const Twine &Msg,
218 ArrayRef<SMRange> Ranges = None);
220 virtual const AsmToken &Lex();
222 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
223 bool isParsingInlineAsm() { return ParsingInlineAsm; }
225 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
226 unsigned &NumOutputs, unsigned &NumInputs,
227 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
228 SmallVectorImpl<std::string> &Constraints,
229 SmallVectorImpl<std::string> &Clobbers,
230 const MCInstrInfo *MII,
231 const MCInstPrinter *IP,
232 MCAsmParserSemaCallback &SI);
234 bool parseExpression(const MCExpr *&Res);
235 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
236 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
237 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
238 virtual bool parseAbsoluteExpression(int64_t &Res);
240 /// \brief Parse an identifier or string (as a quoted identifier)
241 /// and set \p Res to the identifier contents.
242 virtual bool parseIdentifier(StringRef &Res);
243 virtual void eatToEndOfStatement();
245 virtual void checkForValidSection();
250 bool parseStatement(ParseStatementInfo &Info);
251 void eatToEndOfLine();
252 bool parseCppHashLineFilenameComment(const SMLoc &L);
254 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
255 MCAsmMacroParameters Parameters);
256 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
257 const MCAsmMacroParameters &Parameters,
258 const MCAsmMacroArguments &A,
261 /// \brief Are macros enabled in the parser?
262 bool areMacrosEnabled() {return MacrosEnabledFlag;}
264 /// \brief Control a flag in the parser that enables or disables macros.
265 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
267 /// \brief Lookup a previously defined macro.
268 /// \param Name Macro name.
269 /// \returns Pointer to macro. NULL if no such macro was defined.
270 const MCAsmMacro* lookupMacro(StringRef Name);
272 /// \brief Define a new macro with the given name and information.
273 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
275 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
276 void undefineMacro(StringRef Name);
278 /// \brief Are we inside a macro instantiation?
279 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
281 /// \brief Handle entry to macro instantiation.
283 /// \param M The macro.
284 /// \param NameLoc Instantiation location.
285 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
287 /// \brief Handle exit from macro instantiation.
288 void handleMacroExit();
290 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
291 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
292 /// correct delimiter by the method.
293 bool parseMacroArgument(MCAsmMacroArgument &MA,
294 AsmToken::TokenKind &ArgumentDelimiter);
296 /// \brief Parse all macro arguments for a given macro.
297 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
299 void printMacroInstantiations();
300 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
301 ArrayRef<SMRange> Ranges = None) const {
302 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
304 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
306 /// \brief Enter the specified file. This returns true on failure.
307 bool enterIncludeFile(const std::string &Filename);
309 /// \brief Process the specified file for the .incbin directive.
310 /// This returns true on failure.
311 bool processIncbinFile(const std::string &Filename);
313 /// \brief Reset the current lexer position to that given by \p Loc. The
314 /// current token is not set; clients should ensure Lex() is called
317 /// \param InBuffer If not -1, should be the known buffer id that contains the
319 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
321 /// \brief Parse up to the end of statement and a return the contents from the
322 /// current token until the end of the statement; the current token on exit
323 /// will be either the EndOfStatement or EOF.
324 virtual StringRef parseStringToEndOfStatement();
326 /// \brief Parse until the end of a statement or a comma is encountered,
327 /// return the contents from the current token up to the end or comma.
328 StringRef parseStringToComma();
330 bool parseAssignment(StringRef Name, bool allow_redef,
331 bool NoDeadStrip = false);
333 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
334 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
335 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
339 // Generic (target and platform independent) directive parsing.
341 DK_NO_DIRECTIVE, // Placeholder
342 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
343 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
344 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
345 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
346 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
347 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
348 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
349 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
350 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
351 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
352 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
353 DK_ELSEIF, DK_ELSE, DK_ENDIF,
354 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
355 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
356 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
357 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
358 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
359 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
360 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
361 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
362 DK_SLEB128, DK_ULEB128,
366 /// \brief Maps directive name --> DirectiveKind enum, for
367 /// directives parsed by this class.
368 StringMap<DirectiveKind> DirectiveKindMap;
370 // ".ascii", ".asciz", ".string"
371 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
372 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
373 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
374 bool parseDirectiveFill(); // ".fill"
375 bool parseDirectiveZero(); // ".zero"
376 // ".set", ".equ", ".equiv"
377 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
378 bool parseDirectiveOrg(); // ".org"
379 // ".align{,32}", ".p2align{,w,l}"
380 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
382 // ".file", ".line", ".loc", ".stabs"
383 bool parseDirectiveFile(SMLoc DirectiveLoc);
384 bool parseDirectiveLine();
385 bool parseDirectiveLoc();
386 bool parseDirectiveStabs();
389 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
390 bool parseDirectiveCFIWindowSave();
391 bool parseDirectiveCFISections();
392 bool parseDirectiveCFIStartProc();
393 bool parseDirectiveCFIEndProc();
394 bool parseDirectiveCFIDefCfaOffset();
395 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIAdjustCfaOffset();
397 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
400 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
401 bool parseDirectiveCFIRememberState();
402 bool parseDirectiveCFIRestoreState();
403 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
405 bool parseDirectiveCFIEscape();
406 bool parseDirectiveCFISignalFrame();
407 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
410 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
411 bool parseDirectiveEndMacro(StringRef Directive);
412 bool parseDirectiveMacro(SMLoc DirectiveLoc);
413 bool parseDirectiveMacrosOnOff(StringRef Directive);
415 // ".bundle_align_mode"
416 bool parseDirectiveBundleAlignMode();
418 bool parseDirectiveBundleLock();
420 bool parseDirectiveBundleUnlock();
423 bool parseDirectiveSpace(StringRef IDVal);
425 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
426 bool parseDirectiveLEB128(bool Signed);
428 /// \brief Parse a directive like ".globl" which
429 /// accepts a single symbol (which should be a label or an external).
430 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
432 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
434 bool parseDirectiveAbort(); // ".abort"
435 bool parseDirectiveInclude(); // ".include"
436 bool parseDirectiveIncbin(); // ".incbin"
438 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
439 // ".ifb" or ".ifnb", depending on ExpectBlank.
440 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
441 // ".ifc" or ".ifnc", depending on ExpectEqual.
442 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
443 // ".ifdef" or ".ifndef", depending on expect_defined
444 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
445 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
446 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
447 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
448 virtual bool parseEscapedString(std::string &Data);
450 const MCExpr *applyModifierToExpr(const MCExpr *E,
451 MCSymbolRefExpr::VariantKind Variant);
453 // Macro-like directives
454 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
455 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
456 raw_svector_ostream &OS);
457 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
458 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
459 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
460 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
462 // "_emit" or "__emit"
463 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
467 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
470 bool parseDirectiveEnd(SMLoc DirectiveLoc);
472 void initializeDirectiveKindMap();
478 extern MCAsmParserExtension *createDarwinAsmParser();
479 extern MCAsmParserExtension *createELFAsmParser();
480 extern MCAsmParserExtension *createCOFFAsmParser();
484 enum { DEFAULT_ADDRSPACE = 0 };
486 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
487 const MCAsmInfo &_MAI)
488 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
489 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
490 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
491 ParsingInlineAsm(false) {
492 // Save the old handler.
493 SavedDiagHandler = SrcMgr.getDiagHandler();
494 SavedDiagContext = SrcMgr.getDiagContext();
495 // Set our own handler which calls the saved handler.
496 SrcMgr.setDiagHandler(DiagHandler, this);
497 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
499 // Initialize the platform / file format parser.
500 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
501 case MCObjectFileInfo::IsCOFF:
502 PlatformParser = createCOFFAsmParser();
503 PlatformParser->Initialize(*this);
505 case MCObjectFileInfo::IsMachO:
506 PlatformParser = createDarwinAsmParser();
507 PlatformParser->Initialize(*this);
510 case MCObjectFileInfo::IsELF:
511 PlatformParser = createELFAsmParser();
512 PlatformParser->Initialize(*this);
516 initializeDirectiveKindMap();
519 AsmParser::~AsmParser() {
520 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
522 // Destroy any macros.
523 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
526 delete it->getValue();
528 delete PlatformParser;
531 void AsmParser::printMacroInstantiations() {
532 // Print the active macro instantiation stack.
533 for (std::vector<MacroInstantiation *>::const_reverse_iterator
534 it = ActiveMacros.rbegin(),
535 ie = ActiveMacros.rend();
537 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
538 "while in macro instantiation");
541 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
542 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
543 printMacroInstantiations();
546 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
547 if (FatalAssemblerWarnings)
548 return Error(L, Msg, Ranges);
549 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
550 printMacroInstantiations();
554 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
556 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
557 printMacroInstantiations();
561 bool AsmParser::enterIncludeFile(const std::string &Filename) {
562 std::string IncludedFile;
563 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
569 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
574 /// Process the specified .incbin file by searching for it in the include paths
575 /// then just emitting the byte contents of the file to the streamer. This
576 /// returns true on failure.
577 bool AsmParser::processIncbinFile(const std::string &Filename) {
578 std::string IncludedFile;
579 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
583 // Pick up the bytes from the file and emit them.
584 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
588 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
589 if (InBuffer != -1) {
590 CurBuffer = InBuffer;
592 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
594 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
597 const AsmToken &AsmParser::Lex() {
598 const AsmToken *tok = &Lexer.Lex();
600 if (tok->is(AsmToken::Eof)) {
601 // If this is the end of an included file, pop the parent file off the
603 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
604 if (ParentIncludeLoc != SMLoc()) {
605 jumpToLoc(ParentIncludeLoc);
610 if (tok->is(AsmToken::Error))
611 Error(Lexer.getErrLoc(), Lexer.getErr());
616 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
617 // Create the initial section, if requested.
618 if (!NoInitialTextSection)
625 AsmCond StartingCondState = TheCondState;
627 // If we are generating dwarf for assembly source files save the initial text
628 // section and generate a .file directive.
629 if (getContext().getGenDwarfForAssembly()) {
630 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
631 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
632 getStreamer().EmitLabel(SectionStartSym);
633 getContext().setGenDwarfSectionStartSym(SectionStartSym);
634 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
636 getContext().getMainFileName());
639 // While we have input, parse each statement.
640 while (Lexer.isNot(AsmToken::Eof)) {
641 ParseStatementInfo Info;
642 if (!parseStatement(Info))
645 // We had an error, validate that one was emitted and recover by skipping to
647 assert(HadError && "Parse statement returned an error, but none emitted!");
648 eatToEndOfStatement();
651 if (TheCondState.TheCond != StartingCondState.TheCond ||
652 TheCondState.Ignore != StartingCondState.Ignore)
653 return TokError("unmatched .ifs or .elses");
655 // Check to see there are no empty DwarfFile slots.
656 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
657 getContext().getMCDwarfFiles();
658 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
659 if (!MCDwarfFiles[i])
660 TokError("unassigned file number: " + Twine(i) + " for .file directives");
663 // Check to see that all assembler local symbols were actually defined.
664 // Targets that don't do subsections via symbols may not want this, though,
665 // so conservatively exclude them. Only do this if we're finalizing, though,
666 // as otherwise we won't necessarilly have seen everything yet.
667 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
668 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
669 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
672 MCSymbol *Sym = i->getValue();
673 // Variable symbols may not be marked as defined, so check those
674 // explicitly. If we know it's a variable, we have a definition for
675 // the purposes of this check.
676 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
677 // FIXME: We would really like to refer back to where the symbol was
678 // first referenced for a source location. We need to add something
679 // to track that. Currently, we just point to the end of the file.
681 getLexer().getLoc(), SourceMgr::DK_Error,
682 "assembler local symbol '" + Sym->getName() + "' not defined");
686 // Callback to the target parser in case it needs to do anything.
688 getTargetParser().finishParse();
690 // Finalize the output stream if there are no errors and if the client wants
692 if (!HadError && !NoFinalize)
698 void AsmParser::checkForValidSection() {
699 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
700 TokError("expected section directive before assembly directive");
705 /// \brief Throw away the rest of the line for testing purposes.
706 void AsmParser::eatToEndOfStatement() {
707 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
711 if (Lexer.is(AsmToken::EndOfStatement))
715 StringRef AsmParser::parseStringToEndOfStatement() {
716 const char *Start = getTok().getLoc().getPointer();
718 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
721 const char *End = getTok().getLoc().getPointer();
722 return StringRef(Start, End - Start);
725 StringRef AsmParser::parseStringToComma() {
726 const char *Start = getTok().getLoc().getPointer();
728 while (Lexer.isNot(AsmToken::EndOfStatement) &&
729 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
732 const char *End = getTok().getLoc().getPointer();
733 return StringRef(Start, End - Start);
736 /// \brief Parse a paren expression and return it.
737 /// NOTE: This assumes the leading '(' has already been consumed.
739 /// parenexpr ::= expr)
741 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
742 if (parseExpression(Res))
744 if (Lexer.isNot(AsmToken::RParen))
745 return TokError("expected ')' in parentheses expression");
746 EndLoc = Lexer.getTok().getEndLoc();
751 /// \brief Parse a bracket expression and return it.
752 /// NOTE: This assumes the leading '[' has already been consumed.
754 /// bracketexpr ::= expr]
756 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
757 if (parseExpression(Res))
759 if (Lexer.isNot(AsmToken::RBrac))
760 return TokError("expected ']' in brackets expression");
761 EndLoc = Lexer.getTok().getEndLoc();
766 /// \brief Parse a primary expression and return it.
767 /// primaryexpr ::= (parenexpr
768 /// primaryexpr ::= symbol
769 /// primaryexpr ::= number
770 /// primaryexpr ::= '.'
771 /// primaryexpr ::= ~,+,- primaryexpr
772 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
773 SMLoc FirstTokenLoc = getLexer().getLoc();
774 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
775 switch (FirstTokenKind) {
777 return TokError("unknown token in expression");
778 // If we have an error assume that we've already handled it.
779 case AsmToken::Error:
781 case AsmToken::Exclaim:
782 Lex(); // Eat the operator.
783 if (parsePrimaryExpr(Res, EndLoc))
785 Res = MCUnaryExpr::CreateLNot(Res, getContext());
787 case AsmToken::Dollar:
789 case AsmToken::String:
790 case AsmToken::Identifier: {
791 StringRef Identifier;
792 if (parseIdentifier(Identifier)) {
793 if (FirstTokenKind == AsmToken::Dollar) {
794 if (Lexer.getMAI().getDollarIsPC()) {
795 // This is a '$' reference, which references the current PC. Emit a
796 // temporary label to the streamer and refer to it.
797 MCSymbol *Sym = Ctx.CreateTempSymbol();
799 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
801 EndLoc = FirstTokenLoc;
804 return Error(FirstTokenLoc, "invalid token in expression");
808 // Parse symbol variant
809 std::pair<StringRef, StringRef> Split;
810 if (!MAI.useParensForSymbolVariant()) {
811 Split = Identifier.split('@');
812 } else if (Lexer.is(AsmToken::LParen)) {
813 Lexer.Lex(); // eat (
815 parseIdentifier(VName);
816 if (Lexer.isNot(AsmToken::RParen)) {
817 return Error(Lexer.getTok().getLoc(),
818 "unexpected token in variant, expected ')'");
820 Lexer.Lex(); // eat )
821 Split = std::make_pair(Identifier, VName);
824 EndLoc = SMLoc::getFromPointer(Identifier.end());
826 // This is a symbol reference.
827 StringRef SymbolName = Identifier;
828 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
830 // Lookup the symbol variant if used.
831 if (Split.second.size()) {
832 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
833 if (Variant != MCSymbolRefExpr::VK_Invalid) {
834 SymbolName = Split.first;
835 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
836 Variant = MCSymbolRefExpr::VK_None;
838 Variant = MCSymbolRefExpr::VK_None;
839 return TokError("invalid variant '" + Split.second + "'");
843 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
845 // If this is an absolute variable reference, substitute it now to preserve
846 // semantics in the face of reassignment.
847 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
849 return Error(EndLoc, "unexpected modifier on variable reference");
851 Res = Sym->getVariableValue();
855 // Otherwise create a symbol ref.
856 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
859 case AsmToken::Integer: {
860 SMLoc Loc = getTok().getLoc();
861 int64_t IntVal = getTok().getIntVal();
862 Res = MCConstantExpr::Create(IntVal, getContext());
863 EndLoc = Lexer.getTok().getEndLoc();
865 // Look for 'b' or 'f' following an Integer as a directional label
866 if (Lexer.getKind() == AsmToken::Identifier) {
867 StringRef IDVal = getTok().getString();
868 // Lookup the symbol variant if used.
869 std::pair<StringRef, StringRef> Split = IDVal.split('@');
870 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
871 if (Split.first.size() != IDVal.size()) {
872 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
873 if (Variant == MCSymbolRefExpr::VK_Invalid) {
874 Variant = MCSymbolRefExpr::VK_None;
875 return TokError("invalid variant '" + Split.second + "'");
879 if (IDVal == "f" || IDVal == "b") {
881 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
882 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
883 if (IDVal == "b" && Sym->isUndefined())
884 return Error(Loc, "invalid reference to undefined symbol");
885 EndLoc = Lexer.getTok().getEndLoc();
886 Lex(); // Eat identifier.
891 case AsmToken::Real: {
892 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
893 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
894 Res = MCConstantExpr::Create(IntVal, getContext());
895 EndLoc = Lexer.getTok().getEndLoc();
899 case AsmToken::Dot: {
900 // This is a '.' reference, which references the current PC. Emit a
901 // temporary label to the streamer and refer to it.
902 MCSymbol *Sym = Ctx.CreateTempSymbol();
904 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
905 EndLoc = Lexer.getTok().getEndLoc();
906 Lex(); // Eat identifier.
909 case AsmToken::LParen:
910 Lex(); // Eat the '('.
911 return parseParenExpr(Res, EndLoc);
912 case AsmToken::LBrac:
913 if (!PlatformParser->HasBracketExpressions())
914 return TokError("brackets expression not supported on this target");
915 Lex(); // Eat the '['.
916 return parseBracketExpr(Res, EndLoc);
917 case AsmToken::Minus:
918 Lex(); // Eat the operator.
919 if (parsePrimaryExpr(Res, EndLoc))
921 Res = MCUnaryExpr::CreateMinus(Res, getContext());
924 Lex(); // Eat the operator.
925 if (parsePrimaryExpr(Res, EndLoc))
927 Res = MCUnaryExpr::CreatePlus(Res, getContext());
929 case AsmToken::Tilde:
930 Lex(); // Eat the operator.
931 if (parsePrimaryExpr(Res, EndLoc))
933 Res = MCUnaryExpr::CreateNot(Res, getContext());
938 bool AsmParser::parseExpression(const MCExpr *&Res) {
940 return parseExpression(Res, EndLoc);
944 AsmParser::applyModifierToExpr(const MCExpr *E,
945 MCSymbolRefExpr::VariantKind Variant) {
946 // Ask the target implementation about this expression first.
947 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
950 // Recurse over the given expression, rebuilding it to apply the given variant
951 // if there is exactly one symbol.
952 switch (E->getKind()) {
954 case MCExpr::Constant:
957 case MCExpr::SymbolRef: {
958 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
960 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
961 TokError("invalid variant on expression '" + getTok().getIdentifier() +
962 "' (already modified)");
966 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
969 case MCExpr::Unary: {
970 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
971 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
974 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
977 case MCExpr::Binary: {
978 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
979 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
980 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
990 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
994 llvm_unreachable("Invalid expression kind!");
997 /// \brief Parse an expression and return it.
999 /// expr ::= expr &&,|| expr -> lowest.
1000 /// expr ::= expr |,^,&,! expr
1001 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1002 /// expr ::= expr <<,>> expr
1003 /// expr ::= expr +,- expr
1004 /// expr ::= expr *,/,% expr -> highest.
1005 /// expr ::= primaryexpr
1007 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1008 // Parse the expression.
1010 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1013 // As a special case, we support 'a op b @ modifier' by rewriting the
1014 // expression to include the modifier. This is inefficient, but in general we
1015 // expect users to use 'a@modifier op b'.
1016 if (Lexer.getKind() == AsmToken::At) {
1019 if (Lexer.isNot(AsmToken::Identifier))
1020 return TokError("unexpected symbol modifier following '@'");
1022 MCSymbolRefExpr::VariantKind Variant =
1023 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1024 if (Variant == MCSymbolRefExpr::VK_Invalid)
1025 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1027 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1029 return TokError("invalid modifier '" + getTok().getIdentifier() +
1030 "' (no symbols present)");
1037 // Try to constant fold it up front, if possible.
1039 if (Res->EvaluateAsAbsolute(Value))
1040 Res = MCConstantExpr::Create(Value, getContext());
1045 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1047 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1050 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1053 SMLoc StartLoc = Lexer.getLoc();
1054 if (parseExpression(Expr))
1057 if (!Expr->EvaluateAsAbsolute(Res))
1058 return Error(StartLoc, "expected absolute expression");
1063 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1064 MCBinaryExpr::Opcode &Kind) {
1067 return 0; // not a binop.
1069 // Lowest Precedence: &&, ||
1070 case AsmToken::AmpAmp:
1071 Kind = MCBinaryExpr::LAnd;
1073 case AsmToken::PipePipe:
1074 Kind = MCBinaryExpr::LOr;
1077 // Low Precedence: |, &, ^
1079 // FIXME: gas seems to support '!' as an infix operator?
1080 case AsmToken::Pipe:
1081 Kind = MCBinaryExpr::Or;
1083 case AsmToken::Caret:
1084 Kind = MCBinaryExpr::Xor;
1087 Kind = MCBinaryExpr::And;
1090 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1091 case AsmToken::EqualEqual:
1092 Kind = MCBinaryExpr::EQ;
1094 case AsmToken::ExclaimEqual:
1095 case AsmToken::LessGreater:
1096 Kind = MCBinaryExpr::NE;
1098 case AsmToken::Less:
1099 Kind = MCBinaryExpr::LT;
1101 case AsmToken::LessEqual:
1102 Kind = MCBinaryExpr::LTE;
1104 case AsmToken::Greater:
1105 Kind = MCBinaryExpr::GT;
1107 case AsmToken::GreaterEqual:
1108 Kind = MCBinaryExpr::GTE;
1111 // Intermediate Precedence: <<, >>
1112 case AsmToken::LessLess:
1113 Kind = MCBinaryExpr::Shl;
1115 case AsmToken::GreaterGreater:
1116 Kind = MCBinaryExpr::Shr;
1119 // High Intermediate Precedence: +, -
1120 case AsmToken::Plus:
1121 Kind = MCBinaryExpr::Add;
1123 case AsmToken::Minus:
1124 Kind = MCBinaryExpr::Sub;
1127 // Highest Precedence: *, /, %
1128 case AsmToken::Star:
1129 Kind = MCBinaryExpr::Mul;
1131 case AsmToken::Slash:
1132 Kind = MCBinaryExpr::Div;
1134 case AsmToken::Percent:
1135 Kind = MCBinaryExpr::Mod;
1140 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1141 /// Res contains the LHS of the expression on input.
1142 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1145 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1146 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1148 // If the next token is lower precedence than we are allowed to eat, return
1149 // successfully with what we ate already.
1150 if (TokPrec < Precedence)
1155 // Eat the next primary expression.
1157 if (parsePrimaryExpr(RHS, EndLoc))
1160 // If BinOp binds less tightly with RHS than the operator after RHS, let
1161 // the pending operator take RHS as its LHS.
1162 MCBinaryExpr::Opcode Dummy;
1163 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1164 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1167 // Merge LHS and RHS according to operator.
1168 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1173 /// ::= EndOfStatement
1174 /// ::= Label* Directive ...Operands... EndOfStatement
1175 /// ::= Label* Identifier OperandList* EndOfStatement
1176 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1177 if (Lexer.is(AsmToken::EndOfStatement)) {
1183 // Statements always start with an identifier or are a full line comment.
1184 AsmToken ID = getTok();
1185 SMLoc IDLoc = ID.getLoc();
1187 int64_t LocalLabelVal = -1;
1188 // A full line comment is a '#' as the first token.
1189 if (Lexer.is(AsmToken::Hash))
1190 return parseCppHashLineFilenameComment(IDLoc);
1192 // Allow an integer followed by a ':' as a directional local label.
1193 if (Lexer.is(AsmToken::Integer)) {
1194 LocalLabelVal = getTok().getIntVal();
1195 if (LocalLabelVal < 0) {
1196 if (!TheCondState.Ignore)
1197 return TokError("unexpected token at start of statement");
1200 IDVal = getTok().getString();
1201 Lex(); // Consume the integer token to be used as an identifier token.
1202 if (Lexer.getKind() != AsmToken::Colon) {
1203 if (!TheCondState.Ignore)
1204 return TokError("unexpected token at start of statement");
1207 } else if (Lexer.is(AsmToken::Dot)) {
1208 // Treat '.' as a valid identifier in this context.
1211 } else if (parseIdentifier(IDVal)) {
1212 if (!TheCondState.Ignore)
1213 return TokError("unexpected token at start of statement");
1217 // Handle conditional assembly here before checking for skipping. We
1218 // have to do this so that .endif isn't skipped in a ".if 0" block for
1220 StringMap<DirectiveKind>::const_iterator DirKindIt =
1221 DirectiveKindMap.find(IDVal);
1222 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1224 : DirKindIt->getValue();
1229 return parseDirectiveIf(IDLoc);
1231 return parseDirectiveIfb(IDLoc, true);
1233 return parseDirectiveIfb(IDLoc, false);
1235 return parseDirectiveIfc(IDLoc, true);
1237 return parseDirectiveIfc(IDLoc, false);
1239 return parseDirectiveIfdef(IDLoc, true);
1242 return parseDirectiveIfdef(IDLoc, false);
1244 return parseDirectiveElseIf(IDLoc);
1246 return parseDirectiveElse(IDLoc);
1248 return parseDirectiveEndIf(IDLoc);
1251 // Ignore the statement if in the middle of inactive conditional
1253 if (TheCondState.Ignore) {
1254 eatToEndOfStatement();
1258 // FIXME: Recurse on local labels?
1260 // See what kind of statement we have.
1261 switch (Lexer.getKind()) {
1262 case AsmToken::Colon: {
1263 checkForValidSection();
1265 // identifier ':' -> Label.
1268 // Diagnose attempt to use '.' as a label.
1270 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1272 // Diagnose attempt to use a variable as a label.
1274 // FIXME: Diagnostics. Note the location of the definition as a label.
1275 // FIXME: This doesn't diagnose assignment to a symbol which has been
1276 // implicitly marked as external.
1278 if (LocalLabelVal == -1)
1279 Sym = getContext().GetOrCreateSymbol(IDVal);
1281 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1282 if (!Sym->isUndefined() || Sym->isVariable())
1283 return Error(IDLoc, "invalid symbol redefinition");
1286 if (!ParsingInlineAsm)
1289 // If we are generating dwarf for assembly source files then gather the
1290 // info to make a dwarf label entry for this label if needed.
1291 if (getContext().getGenDwarfForAssembly())
1292 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1295 getTargetParser().onLabelParsed(Sym);
1297 // Consume any end of statement token, if present, to avoid spurious
1298 // AddBlankLine calls().
1299 if (Lexer.is(AsmToken::EndOfStatement)) {
1301 if (Lexer.is(AsmToken::Eof))
1308 case AsmToken::Equal:
1309 // identifier '=' ... -> assignment statement
1312 return parseAssignment(IDVal, true);
1314 default: // Normal instruction or directive.
1318 // If macros are enabled, check to see if this is a macro instantiation.
1319 if (areMacrosEnabled())
1320 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1321 return handleMacroEntry(M, IDLoc);
1324 // Otherwise, we have a normal instruction or directive.
1326 // Directives start with "."
1327 if (IDVal[0] == '.' && IDVal != ".") {
1328 // There are several entities interested in parsing directives:
1330 // 1. The target-specific assembly parser. Some directives are target
1331 // specific or may potentially behave differently on certain targets.
1332 // 2. Asm parser extensions. For example, platform-specific parsers
1333 // (like the ELF parser) register themselves as extensions.
1334 // 3. The generic directive parser implemented by this class. These are
1335 // all the directives that behave in a target and platform independent
1336 // manner, or at least have a default behavior that's shared between
1337 // all targets and platforms.
1339 // First query the target-specific parser. It will return 'true' if it
1340 // isn't interested in this directive.
1341 if (!getTargetParser().ParseDirective(ID))
1344 // Next, check the extention directive map to see if any extension has
1345 // registered itself to parse this directive.
1346 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1347 ExtensionDirectiveMap.lookup(IDVal);
1349 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1351 // Finally, if no one else is interested in this directive, it must be
1352 // generic and familiar to this class.
1358 return parseDirectiveSet(IDVal, true);
1360 return parseDirectiveSet(IDVal, false);
1362 return parseDirectiveAscii(IDVal, false);
1365 return parseDirectiveAscii(IDVal, true);
1367 return parseDirectiveValue(1);
1371 return parseDirectiveValue(2);
1375 return parseDirectiveValue(4);
1378 return parseDirectiveValue(8);
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 const MCAsmMacroParameters &Parameters,
1728 const MCAsmMacroArguments &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].first == 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:
1865 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA,
1866 AsmToken::TokenKind &ArgumentDelimiter) {
1867 unsigned ParenLevel = 0;
1868 unsigned AddTokens = 0;
1870 // gas accepts arguments separated by whitespace, except on Darwin
1872 Lexer.setSkipSpace(false);
1875 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1876 Lexer.setSkipSpace(true);
1877 return TokError("unexpected token in macro instantiation");
1880 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1881 // Spaces and commas cannot be mixed to delimit parameters
1882 if (ArgumentDelimiter == AsmToken::Eof)
1883 ArgumentDelimiter = AsmToken::Comma;
1884 else if (ArgumentDelimiter != AsmToken::Comma) {
1885 Lexer.setSkipSpace(true);
1886 return TokError("expected ' ' for macro argument separator");
1891 if (Lexer.is(AsmToken::Space)) {
1892 Lex(); // Eat spaces
1894 // Spaces can delimit parameters, but could also be part an expression.
1895 // If the token after a space is an operator, add the token and the next
1896 // one into this argument
1897 if (ArgumentDelimiter == AsmToken::Space ||
1898 ArgumentDelimiter == AsmToken::Eof) {
1899 if (isOperator(Lexer.getKind())) {
1900 // Check to see whether the token is used as an operator,
1901 // or part of an identifier
1902 const char *NextChar = getTok().getEndLoc().getPointer();
1903 if (*NextChar == ' ')
1907 if (!AddTokens && ParenLevel == 0) {
1908 if (ArgumentDelimiter == AsmToken::Eof &&
1909 !isOperator(Lexer.getKind()))
1910 ArgumentDelimiter = AsmToken::Space;
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 Lexer.setSkipSpace(true);
1935 if (ParenLevel != 0)
1936 return TokError("unbalanced parentheses in macro argument");
1940 // Parse the macro instantiation arguments.
1941 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1942 MCAsmMacroArguments &A) {
1943 const unsigned NParameters = M ? M->Parameters.size() : 0;
1944 // Argument delimiter is initially unknown. It will be set by
1945 // parseMacroArgument()
1946 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1948 // Parse two kinds of macro invocations:
1949 // - macros defined without any parameters accept an arbitrary number of them
1950 // - macros defined with parameters accept at most that many of them
1951 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1953 MCAsmMacroArgument MA;
1955 if (parseMacroArgument(MA, ArgumentDelimiter))
1958 if (!MA.empty() || !NParameters)
1960 else if (NParameters) {
1961 if (!M->Parameters[Parameter].second.empty())
1962 A.push_back(M->Parameters[Parameter].second);
1965 // At the end of the statement, fill in remaining arguments that have
1966 // default values. If there aren't any, then the next argument is
1967 // required but missing
1968 if (Lexer.is(AsmToken::EndOfStatement)) {
1969 if (NParameters && Parameter < NParameters - 1) {
1970 if (M->Parameters[Parameter + 1].second.empty())
1971 return TokError("macro argument '" +
1972 Twine(M->Parameters[Parameter + 1].first) +
1980 if (Lexer.is(AsmToken::Comma))
1983 return TokError("Too many arguments");
1986 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
1987 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1988 return (I == MacroMap.end()) ? NULL : I->getValue();
1991 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
1992 MacroMap[Name] = new MCAsmMacro(Macro);
1995 void AsmParser::undefineMacro(StringRef Name) {
1996 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1997 if (I != MacroMap.end()) {
1998 delete I->getValue();
2003 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2004 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2005 // this, although we should protect against infinite loops.
2006 if (ActiveMacros.size() == 20)
2007 return TokError("macros cannot be nested more than 20 levels deep");
2009 MCAsmMacroArguments A;
2010 if (parseMacroArguments(M, A))
2013 // Remove any trailing empty arguments. Do this after-the-fact as we have
2014 // to keep empty arguments in the middle of the list or positionality
2015 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
2016 while (!A.empty() && A.back().empty())
2019 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2020 // to hold the macro body with substitutions.
2021 SmallString<256> Buf;
2022 StringRef Body = M->Body;
2023 raw_svector_ostream OS(Buf);
2025 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2028 // We include the .endmacro in the buffer as our cue to exit the macro
2030 OS << ".endmacro\n";
2032 MemoryBuffer *Instantiation =
2033 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2035 // Create the macro instantiation object and add to the current macro
2036 // instantiation stack.
2037 MacroInstantiation *MI = new MacroInstantiation(
2038 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2039 ActiveMacros.push_back(MI);
2041 // Jump to the macro instantiation and prime the lexer.
2042 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2043 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2049 void AsmParser::handleMacroExit() {
2050 // Jump to the EndOfStatement we should return to, and consume it.
2051 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2054 // Pop the instantiation entry.
2055 delete ActiveMacros.back();
2056 ActiveMacros.pop_back();
2059 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2060 switch (Value->getKind()) {
2061 case MCExpr::Binary: {
2062 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2063 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2065 case MCExpr::Target:
2066 case MCExpr::Constant:
2068 case MCExpr::SymbolRef: {
2070 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2072 return isUsedIn(Sym, S.getVariableValue());
2076 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2079 llvm_unreachable("Unknown expr kind!");
2082 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2084 // FIXME: Use better location, we should use proper tokens.
2085 SMLoc EqualLoc = Lexer.getLoc();
2087 const MCExpr *Value;
2088 if (parseExpression(Value))
2091 // Note: we don't count b as used in "a = b". This is to allow
2095 if (Lexer.isNot(AsmToken::EndOfStatement))
2096 return TokError("unexpected token in assignment");
2098 // Error on assignment to '.'.
2100 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2101 "(use '.space' or '.org').)"));
2104 // Eat the end of statement marker.
2107 // Validate that the LHS is allowed to be a variable (either it has not been
2108 // used as a symbol, or it is an absolute symbol).
2109 MCSymbol *Sym = getContext().LookupSymbol(Name);
2111 // Diagnose assignment to a label.
2113 // FIXME: Diagnostics. Note the location of the definition as a label.
2114 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2115 if (isUsedIn(Sym, Value))
2116 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2117 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2118 ; // Allow redefinitions of undefined symbols only used in directives.
2119 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2120 ; // Allow redefinitions of variables that haven't yet been used.
2121 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2122 return Error(EqualLoc, "redefinition of '" + Name + "'");
2123 else if (!Sym->isVariable())
2124 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2125 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2126 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2129 // Don't count these checks as uses.
2130 Sym->setUsed(false);
2132 Sym = getContext().GetOrCreateSymbol(Name);
2134 // FIXME: Handle '.'.
2136 // Do the assignment.
2137 Out.EmitAssignment(Sym, Value);
2139 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2144 /// parseIdentifier:
2147 bool AsmParser::parseIdentifier(StringRef &Res) {
2148 // The assembler has relaxed rules for accepting identifiers, in particular we
2149 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2150 // separate tokens. At this level, we have already lexed so we cannot (currently)
2151 // handle this as a context dependent token, instead we detect adjacent tokens
2152 // and return the combined identifier.
2153 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2154 SMLoc PrefixLoc = getLexer().getLoc();
2156 // Consume the prefix character, and check for a following identifier.
2158 if (Lexer.isNot(AsmToken::Identifier))
2161 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2162 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2165 // Construct the joined identifier and consume the token.
2167 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2172 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2175 Res = getTok().getIdentifier();
2177 Lex(); // Consume the identifier token.
2182 /// parseDirectiveSet:
2183 /// ::= .equ identifier ',' expression
2184 /// ::= .equiv identifier ',' expression
2185 /// ::= .set identifier ',' expression
2186 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2189 if (parseIdentifier(Name))
2190 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2192 if (getLexer().isNot(AsmToken::Comma))
2193 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2196 return parseAssignment(Name, allow_redef, true);
2199 bool AsmParser::parseEscapedString(std::string &Data) {
2200 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2203 StringRef Str = getTok().getStringContents();
2204 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2205 if (Str[i] != '\\') {
2210 // Recognize escaped characters. Note that this escape semantics currently
2211 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2214 return TokError("unexpected backslash at end of string");
2216 // Recognize octal sequences.
2217 if ((unsigned)(Str[i] - '0') <= 7) {
2218 // Consume up to three octal characters.
2219 unsigned Value = Str[i] - '0';
2221 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2223 Value = Value * 8 + (Str[i] - '0');
2225 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2227 Value = Value * 8 + (Str[i] - '0');
2232 return TokError("invalid octal escape sequence (out of range)");
2234 Data += (unsigned char)Value;
2238 // Otherwise recognize individual escapes.
2241 // Just reject invalid escape sequences for now.
2242 return TokError("invalid escape sequence (unrecognized character)");
2244 case 'b': Data += '\b'; break;
2245 case 'f': Data += '\f'; break;
2246 case 'n': Data += '\n'; break;
2247 case 'r': Data += '\r'; break;
2248 case 't': Data += '\t'; break;
2249 case '"': Data += '"'; break;
2250 case '\\': Data += '\\'; break;
2257 /// parseDirectiveAscii:
2258 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2259 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2260 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2261 checkForValidSection();
2264 if (getLexer().isNot(AsmToken::String))
2265 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2268 if (parseEscapedString(Data))
2271 getStreamer().EmitBytes(Data);
2273 getStreamer().EmitBytes(StringRef("\0", 1));
2277 if (getLexer().is(AsmToken::EndOfStatement))
2280 if (getLexer().isNot(AsmToken::Comma))
2281 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2290 /// parseDirectiveValue
2291 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2292 bool AsmParser::parseDirectiveValue(unsigned Size) {
2293 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2294 checkForValidSection();
2297 const MCExpr *Value;
2298 SMLoc ExprLoc = getLexer().getLoc();
2299 if (parseExpression(Value))
2302 // Special case constant expressions to match code generator.
2303 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2304 assert(Size <= 8 && "Invalid size");
2305 uint64_t IntValue = MCE->getValue();
2306 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2307 return Error(ExprLoc, "literal value out of range for directive");
2308 getStreamer().EmitIntValue(IntValue, Size);
2310 getStreamer().EmitValue(Value, Size);
2312 if (getLexer().is(AsmToken::EndOfStatement))
2315 // FIXME: Improve diagnostic.
2316 if (getLexer().isNot(AsmToken::Comma))
2317 return TokError("unexpected token in directive");
2326 /// parseDirectiveRealValue
2327 /// ::= (.single | .double) [ expression (, expression)* ]
2328 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2329 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2330 checkForValidSection();
2333 // We don't truly support arithmetic on floating point expressions, so we
2334 // have to manually parse unary prefixes.
2336 if (getLexer().is(AsmToken::Minus)) {
2339 } else if (getLexer().is(AsmToken::Plus))
2342 if (getLexer().isNot(AsmToken::Integer) &&
2343 getLexer().isNot(AsmToken::Real) &&
2344 getLexer().isNot(AsmToken::Identifier))
2345 return TokError("unexpected token in directive");
2347 // Convert to an APFloat.
2348 APFloat Value(Semantics);
2349 StringRef IDVal = getTok().getString();
2350 if (getLexer().is(AsmToken::Identifier)) {
2351 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2352 Value = APFloat::getInf(Semantics);
2353 else if (!IDVal.compare_lower("nan"))
2354 Value = APFloat::getNaN(Semantics, false, ~0);
2356 return TokError("invalid floating point literal");
2357 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2358 APFloat::opInvalidOp)
2359 return TokError("invalid floating point literal");
2363 // Consume the numeric token.
2366 // Emit the value as an integer.
2367 APInt AsInt = Value.bitcastToAPInt();
2368 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2369 AsInt.getBitWidth() / 8);
2371 if (getLexer().is(AsmToken::EndOfStatement))
2374 if (getLexer().isNot(AsmToken::Comma))
2375 return TokError("unexpected token in directive");
2384 /// parseDirectiveZero
2385 /// ::= .zero expression
2386 bool AsmParser::parseDirectiveZero() {
2387 checkForValidSection();
2390 if (parseAbsoluteExpression(NumBytes))
2394 if (getLexer().is(AsmToken::Comma)) {
2396 if (parseAbsoluteExpression(Val))
2400 if (getLexer().isNot(AsmToken::EndOfStatement))
2401 return TokError("unexpected token in '.zero' directive");
2405 getStreamer().EmitFill(NumBytes, Val);
2410 /// parseDirectiveFill
2411 /// ::= .fill expression [ , expression [ , expression ] ]
2412 bool AsmParser::parseDirectiveFill() {
2413 checkForValidSection();
2416 if (parseAbsoluteExpression(NumValues))
2419 int64_t FillSize = 1;
2420 int64_t FillExpr = 0;
2422 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2423 if (getLexer().isNot(AsmToken::Comma))
2424 return TokError("unexpected token in '.fill' directive");
2427 if (parseAbsoluteExpression(FillSize))
2430 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2431 if (getLexer().isNot(AsmToken::Comma))
2432 return TokError("unexpected token in '.fill' directive");
2435 if (parseAbsoluteExpression(FillExpr))
2438 if (getLexer().isNot(AsmToken::EndOfStatement))
2439 return TokError("unexpected token in '.fill' directive");
2445 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2446 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2448 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2449 getStreamer().EmitIntValue(FillExpr, FillSize);
2454 /// parseDirectiveOrg
2455 /// ::= .org expression [ , expression ]
2456 bool AsmParser::parseDirectiveOrg() {
2457 checkForValidSection();
2459 const MCExpr *Offset;
2460 SMLoc Loc = getTok().getLoc();
2461 if (parseExpression(Offset))
2464 // Parse optional fill expression.
2465 int64_t FillExpr = 0;
2466 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2467 if (getLexer().isNot(AsmToken::Comma))
2468 return TokError("unexpected token in '.org' directive");
2471 if (parseAbsoluteExpression(FillExpr))
2474 if (getLexer().isNot(AsmToken::EndOfStatement))
2475 return TokError("unexpected token in '.org' directive");
2480 // Only limited forms of relocatable expressions are accepted here, it
2481 // has to be relative to the current section. The streamer will return
2482 // 'true' if the expression wasn't evaluatable.
2483 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2484 return Error(Loc, "expected assembly-time absolute expression");
2489 /// parseDirectiveAlign
2490 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2491 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2492 checkForValidSection();
2494 SMLoc AlignmentLoc = getLexer().getLoc();
2496 if (parseAbsoluteExpression(Alignment))
2500 bool HasFillExpr = false;
2501 int64_t FillExpr = 0;
2502 int64_t MaxBytesToFill = 0;
2503 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2504 if (getLexer().isNot(AsmToken::Comma))
2505 return TokError("unexpected token in directive");
2508 // The fill expression can be omitted while specifying a maximum number of
2509 // alignment bytes, e.g:
2511 if (getLexer().isNot(AsmToken::Comma)) {
2513 if (parseAbsoluteExpression(FillExpr))
2517 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2518 if (getLexer().isNot(AsmToken::Comma))
2519 return TokError("unexpected token in directive");
2522 MaxBytesLoc = getLexer().getLoc();
2523 if (parseAbsoluteExpression(MaxBytesToFill))
2526 if (getLexer().isNot(AsmToken::EndOfStatement))
2527 return TokError("unexpected token in directive");
2536 // Compute alignment in bytes.
2538 // FIXME: Diagnose overflow.
2539 if (Alignment >= 32) {
2540 Error(AlignmentLoc, "invalid alignment value");
2544 Alignment = 1ULL << Alignment;
2546 // Reject alignments that aren't a power of two, for gas compatibility.
2547 if (!isPowerOf2_64(Alignment))
2548 Error(AlignmentLoc, "alignment must be a power of 2");
2551 // Diagnose non-sensical max bytes to align.
2552 if (MaxBytesLoc.isValid()) {
2553 if (MaxBytesToFill < 1) {
2554 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2555 "many bytes, ignoring maximum bytes expression");
2559 if (MaxBytesToFill >= Alignment) {
2560 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2566 // Check whether we should use optimal code alignment for this .align
2568 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2569 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2570 ValueSize == 1 && UseCodeAlign) {
2571 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2573 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2574 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2581 /// parseDirectiveFile
2582 /// ::= .file [number] filename
2583 /// ::= .file number directory filename
2584 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2585 // FIXME: I'm not sure what this is.
2586 int64_t FileNumber = -1;
2587 SMLoc FileNumberLoc = getLexer().getLoc();
2588 if (getLexer().is(AsmToken::Integer)) {
2589 FileNumber = getTok().getIntVal();
2593 return TokError("file number less than one");
2596 if (getLexer().isNot(AsmToken::String))
2597 return TokError("unexpected token in '.file' directive");
2599 // Usually the directory and filename together, otherwise just the directory.
2600 // Allow the strings to have escaped octal character sequence.
2601 std::string Path = getTok().getString();
2602 if (parseEscapedString(Path))
2606 StringRef Directory;
2608 std::string FilenameData;
2609 if (getLexer().is(AsmToken::String)) {
2610 if (FileNumber == -1)
2611 return TokError("explicit path specified, but no file number");
2612 if (parseEscapedString(FilenameData))
2614 Filename = FilenameData;
2621 if (getLexer().isNot(AsmToken::EndOfStatement))
2622 return TokError("unexpected token in '.file' directive");
2624 if (FileNumber == -1)
2625 getStreamer().EmitFileDirective(Filename);
2627 if (getContext().getGenDwarfForAssembly() == true)
2629 "input can't have .file dwarf directives when -g is "
2630 "used to generate dwarf debug info for assembly code");
2632 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2633 Error(FileNumberLoc, "file number already allocated");
2639 /// parseDirectiveLine
2640 /// ::= .line [number]
2641 bool AsmParser::parseDirectiveLine() {
2642 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2643 if (getLexer().isNot(AsmToken::Integer))
2644 return TokError("unexpected token in '.line' directive");
2646 int64_t LineNumber = getTok().getIntVal();
2650 // FIXME: Do something with the .line.
2653 if (getLexer().isNot(AsmToken::EndOfStatement))
2654 return TokError("unexpected token in '.line' directive");
2659 /// parseDirectiveLoc
2660 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2661 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2662 /// The first number is a file number, must have been previously assigned with
2663 /// a .file directive, the second number is the line number and optionally the
2664 /// third number is a column position (zero if not specified). The remaining
2665 /// optional items are .loc sub-directives.
2666 bool AsmParser::parseDirectiveLoc() {
2667 if (getLexer().isNot(AsmToken::Integer))
2668 return TokError("unexpected token in '.loc' directive");
2669 int64_t FileNumber = getTok().getIntVal();
2671 return TokError("file number less than one in '.loc' directive");
2672 if (!getContext().isValidDwarfFileNumber(FileNumber))
2673 return TokError("unassigned file number in '.loc' directive");
2676 int64_t LineNumber = 0;
2677 if (getLexer().is(AsmToken::Integer)) {
2678 LineNumber = getTok().getIntVal();
2680 return TokError("line number less than zero in '.loc' directive");
2684 int64_t ColumnPos = 0;
2685 if (getLexer().is(AsmToken::Integer)) {
2686 ColumnPos = getTok().getIntVal();
2688 return TokError("column position less than zero in '.loc' directive");
2692 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2694 int64_t Discriminator = 0;
2695 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2697 if (getLexer().is(AsmToken::EndOfStatement))
2701 SMLoc Loc = getTok().getLoc();
2702 if (parseIdentifier(Name))
2703 return TokError("unexpected token in '.loc' directive");
2705 if (Name == "basic_block")
2706 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2707 else if (Name == "prologue_end")
2708 Flags |= DWARF2_FLAG_PROLOGUE_END;
2709 else if (Name == "epilogue_begin")
2710 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2711 else if (Name == "is_stmt") {
2712 Loc = getTok().getLoc();
2713 const MCExpr *Value;
2714 if (parseExpression(Value))
2716 // The expression must be the constant 0 or 1.
2717 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2718 int Value = MCE->getValue();
2720 Flags &= ~DWARF2_FLAG_IS_STMT;
2721 else if (Value == 1)
2722 Flags |= DWARF2_FLAG_IS_STMT;
2724 return Error(Loc, "is_stmt value not 0 or 1");
2726 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2728 } else if (Name == "isa") {
2729 Loc = getTok().getLoc();
2730 const MCExpr *Value;
2731 if (parseExpression(Value))
2733 // The expression must be a constant greater or equal to 0.
2734 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2735 int Value = MCE->getValue();
2737 return Error(Loc, "isa number less than zero");
2740 return Error(Loc, "isa number not a constant value");
2742 } else if (Name == "discriminator") {
2743 if (parseAbsoluteExpression(Discriminator))
2746 return Error(Loc, "unknown sub-directive in '.loc' directive");
2749 if (getLexer().is(AsmToken::EndOfStatement))
2754 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2755 Isa, Discriminator, StringRef());
2760 /// parseDirectiveStabs
2761 /// ::= .stabs string, number, number, number
2762 bool AsmParser::parseDirectiveStabs() {
2763 return TokError("unsupported directive '.stabs'");
2766 /// parseDirectiveCFISections
2767 /// ::= .cfi_sections section [, section]
2768 bool AsmParser::parseDirectiveCFISections() {
2773 if (parseIdentifier(Name))
2774 return TokError("Expected an identifier");
2776 if (Name == ".eh_frame")
2778 else if (Name == ".debug_frame")
2781 if (getLexer().is(AsmToken::Comma)) {
2784 if (parseIdentifier(Name))
2785 return TokError("Expected an identifier");
2787 if (Name == ".eh_frame")
2789 else if (Name == ".debug_frame")
2793 getStreamer().EmitCFISections(EH, Debug);
2797 /// parseDirectiveCFIStartProc
2798 /// ::= .cfi_startproc
2799 bool AsmParser::parseDirectiveCFIStartProc() {
2800 getStreamer().EmitCFIStartProc();
2804 /// parseDirectiveCFIEndProc
2805 /// ::= .cfi_endproc
2806 bool AsmParser::parseDirectiveCFIEndProc() {
2807 getStreamer().EmitCFIEndProc();
2811 /// \brief parse register name or number.
2812 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2813 SMLoc DirectiveLoc) {
2816 if (getLexer().isNot(AsmToken::Integer)) {
2817 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2819 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2821 return parseAbsoluteExpression(Register);
2826 /// parseDirectiveCFIDefCfa
2827 /// ::= .cfi_def_cfa register, offset
2828 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2829 int64_t Register = 0;
2830 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2833 if (getLexer().isNot(AsmToken::Comma))
2834 return TokError("unexpected token in directive");
2838 if (parseAbsoluteExpression(Offset))
2841 getStreamer().EmitCFIDefCfa(Register, Offset);
2845 /// parseDirectiveCFIDefCfaOffset
2846 /// ::= .cfi_def_cfa_offset offset
2847 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2849 if (parseAbsoluteExpression(Offset))
2852 getStreamer().EmitCFIDefCfaOffset(Offset);
2856 /// parseDirectiveCFIRegister
2857 /// ::= .cfi_register register, register
2858 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2859 int64_t Register1 = 0;
2860 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2863 if (getLexer().isNot(AsmToken::Comma))
2864 return TokError("unexpected token in directive");
2867 int64_t Register2 = 0;
2868 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2871 getStreamer().EmitCFIRegister(Register1, Register2);
2875 /// parseDirectiveCFIWindowSave
2876 /// ::= .cfi_window_save
2877 bool AsmParser::parseDirectiveCFIWindowSave() {
2878 getStreamer().EmitCFIWindowSave();
2882 /// parseDirectiveCFIAdjustCfaOffset
2883 /// ::= .cfi_adjust_cfa_offset adjustment
2884 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2885 int64_t Adjustment = 0;
2886 if (parseAbsoluteExpression(Adjustment))
2889 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2893 /// parseDirectiveCFIDefCfaRegister
2894 /// ::= .cfi_def_cfa_register register
2895 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2896 int64_t Register = 0;
2897 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2900 getStreamer().EmitCFIDefCfaRegister(Register);
2904 /// parseDirectiveCFIOffset
2905 /// ::= .cfi_offset register, offset
2906 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2907 int64_t Register = 0;
2910 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2913 if (getLexer().isNot(AsmToken::Comma))
2914 return TokError("unexpected token in directive");
2917 if (parseAbsoluteExpression(Offset))
2920 getStreamer().EmitCFIOffset(Register, Offset);
2924 /// parseDirectiveCFIRelOffset
2925 /// ::= .cfi_rel_offset register, offset
2926 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2927 int64_t Register = 0;
2929 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2932 if (getLexer().isNot(AsmToken::Comma))
2933 return TokError("unexpected token in directive");
2937 if (parseAbsoluteExpression(Offset))
2940 getStreamer().EmitCFIRelOffset(Register, Offset);
2944 static bool isValidEncoding(int64_t Encoding) {
2945 if (Encoding & ~0xff)
2948 if (Encoding == dwarf::DW_EH_PE_omit)
2951 const unsigned Format = Encoding & 0xf;
2952 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2953 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2954 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2955 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2958 const unsigned Application = Encoding & 0x70;
2959 if (Application != dwarf::DW_EH_PE_absptr &&
2960 Application != dwarf::DW_EH_PE_pcrel)
2966 /// parseDirectiveCFIPersonalityOrLsda
2967 /// IsPersonality true for cfi_personality, false for cfi_lsda
2968 /// ::= .cfi_personality encoding, [symbol_name]
2969 /// ::= .cfi_lsda encoding, [symbol_name]
2970 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2971 int64_t Encoding = 0;
2972 if (parseAbsoluteExpression(Encoding))
2974 if (Encoding == dwarf::DW_EH_PE_omit)
2977 if (!isValidEncoding(Encoding))
2978 return TokError("unsupported encoding.");
2980 if (getLexer().isNot(AsmToken::Comma))
2981 return TokError("unexpected token in directive");
2985 if (parseIdentifier(Name))
2986 return TokError("expected identifier in directive");
2988 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2991 getStreamer().EmitCFIPersonality(Sym, Encoding);
2993 getStreamer().EmitCFILsda(Sym, Encoding);
2997 /// parseDirectiveCFIRememberState
2998 /// ::= .cfi_remember_state
2999 bool AsmParser::parseDirectiveCFIRememberState() {
3000 getStreamer().EmitCFIRememberState();
3004 /// parseDirectiveCFIRestoreState
3005 /// ::= .cfi_remember_state
3006 bool AsmParser::parseDirectiveCFIRestoreState() {
3007 getStreamer().EmitCFIRestoreState();
3011 /// parseDirectiveCFISameValue
3012 /// ::= .cfi_same_value register
3013 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3014 int64_t Register = 0;
3016 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3019 getStreamer().EmitCFISameValue(Register);
3023 /// parseDirectiveCFIRestore
3024 /// ::= .cfi_restore register
3025 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3026 int64_t Register = 0;
3027 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3030 getStreamer().EmitCFIRestore(Register);
3034 /// parseDirectiveCFIEscape
3035 /// ::= .cfi_escape expression[,...]
3036 bool AsmParser::parseDirectiveCFIEscape() {
3039 if (parseAbsoluteExpression(CurrValue))
3042 Values.push_back((uint8_t)CurrValue);
3044 while (getLexer().is(AsmToken::Comma)) {
3047 if (parseAbsoluteExpression(CurrValue))
3050 Values.push_back((uint8_t)CurrValue);
3053 getStreamer().EmitCFIEscape(Values);
3057 /// parseDirectiveCFISignalFrame
3058 /// ::= .cfi_signal_frame
3059 bool AsmParser::parseDirectiveCFISignalFrame() {
3060 if (getLexer().isNot(AsmToken::EndOfStatement))
3061 return Error(getLexer().getLoc(),
3062 "unexpected token in '.cfi_signal_frame'");
3064 getStreamer().EmitCFISignalFrame();
3068 /// parseDirectiveCFIUndefined
3069 /// ::= .cfi_undefined register
3070 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3071 int64_t Register = 0;
3073 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3076 getStreamer().EmitCFIUndefined(Register);
3080 /// parseDirectiveMacrosOnOff
3083 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3084 if (getLexer().isNot(AsmToken::EndOfStatement))
3085 return Error(getLexer().getLoc(),
3086 "unexpected token in '" + Directive + "' directive");
3088 setMacrosEnabled(Directive == ".macros_on");
3092 /// parseDirectiveMacro
3093 /// ::= .macro name [parameters]
3094 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3096 if (parseIdentifier(Name))
3097 return TokError("expected identifier in '.macro' directive");
3099 MCAsmMacroParameters Parameters;
3100 // Argument delimiter is initially unknown. It will be set by
3101 // parseMacroArgument()
3102 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3103 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3105 MCAsmMacroParameter Parameter;
3106 if (parseIdentifier(Parameter.first))
3107 return TokError("expected identifier in '.macro' directive");
3109 if (getLexer().is(AsmToken::Equal)) {
3111 if (parseMacroArgument(Parameter.second, ArgumentDelimiter))
3115 Parameters.push_back(Parameter);
3117 if (getLexer().is(AsmToken::Comma))
3119 else if (getLexer().is(AsmToken::EndOfStatement))
3124 // Eat the end of statement.
3127 AsmToken EndToken, StartToken = getTok();
3129 // Lex the macro definition.
3131 // Check whether we have reached the end of the file.
3132 if (getLexer().is(AsmToken::Eof))
3133 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3135 // Otherwise, check whether we have reach the .endmacro.
3136 if (getLexer().is(AsmToken::Identifier) &&
3137 (getTok().getIdentifier() == ".endm" ||
3138 getTok().getIdentifier() == ".endmacro")) {
3139 EndToken = getTok();
3141 if (getLexer().isNot(AsmToken::EndOfStatement))
3142 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3147 // Otherwise, scan til the end of the statement.
3148 eatToEndOfStatement();
3151 if (lookupMacro(Name)) {
3152 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3155 const char *BodyStart = StartToken.getLoc().getPointer();
3156 const char *BodyEnd = EndToken.getLoc().getPointer();
3157 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3158 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3159 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3163 /// checkForBadMacro
3165 /// With the support added for named parameters there may be code out there that
3166 /// is transitioning from positional parameters. In versions of gas that did
3167 /// not support named parameters they would be ignored on the macro defintion.
3168 /// But to support both styles of parameters this is not possible so if a macro
3169 /// defintion has named parameters but does not use them and has what appears
3170 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3171 /// warning that the positional parameter found in body which have no effect.
3172 /// Hoping the developer will either remove the named parameters from the macro
3173 /// definiton so the positional parameters get used if that was what was
3174 /// intended or change the macro to use the named parameters. It is possible
3175 /// this warning will trigger when the none of the named parameters are used
3176 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3177 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3179 MCAsmMacroParameters Parameters) {
3180 // If this macro is not defined with named parameters the warning we are
3181 // checking for here doesn't apply.
3182 unsigned NParameters = Parameters.size();
3183 if (NParameters == 0)
3186 bool NamedParametersFound = false;
3187 bool PositionalParametersFound = false;
3189 // Look at the body of the macro for use of both the named parameters and what
3190 // are likely to be positional parameters. This is what expandMacro() is
3191 // doing when it finds the parameters in the body.
3192 while (!Body.empty()) {
3193 // Scan for the next possible parameter.
3194 std::size_t End = Body.size(), Pos = 0;
3195 for (; Pos != End; ++Pos) {
3196 // Check for a substitution or escape.
3197 // This macro is defined with parameters, look for \foo, \bar, etc.
3198 if (Body[Pos] == '\\' && Pos + 1 != End)
3201 // This macro should have parameters, but look for $0, $1, ..., $n too.
3202 if (Body[Pos] != '$' || Pos + 1 == End)
3204 char Next = Body[Pos + 1];
3205 if (Next == '$' || Next == 'n' ||
3206 isdigit(static_cast<unsigned char>(Next)))
3210 // Check if we reached the end.
3214 if (Body[Pos] == '$') {
3215 switch (Body[Pos + 1]) {
3220 // $n => number of arguments
3222 PositionalParametersFound = true;
3225 // $[0-9] => argument
3227 PositionalParametersFound = true;
3233 unsigned I = Pos + 1;
3234 while (isIdentifierChar(Body[I]) && I + 1 != End)
3237 const char *Begin = Body.data() + Pos + 1;
3238 StringRef Argument(Begin, I - (Pos + 1));
3240 for (; Index < NParameters; ++Index)
3241 if (Parameters[Index].first == Argument)
3244 if (Index == NParameters) {
3245 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3251 NamedParametersFound = true;
3252 Pos += 1 + Argument.size();
3255 // Update the scan point.
3256 Body = Body.substr(Pos);
3259 if (!NamedParametersFound && PositionalParametersFound)
3260 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3261 "used in macro body, possible positional parameter "
3262 "found in body which will have no effect");
3265 /// parseDirectiveEndMacro
3268 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3269 if (getLexer().isNot(AsmToken::EndOfStatement))
3270 return TokError("unexpected token in '" + Directive + "' directive");
3272 // If we are inside a macro instantiation, terminate the current
3274 if (isInsideMacroInstantiation()) {
3279 // Otherwise, this .endmacro is a stray entry in the file; well formed
3280 // .endmacro directives are handled during the macro definition parsing.
3281 return TokError("unexpected '" + Directive + "' in file, "
3282 "no current macro definition");
3285 /// parseDirectivePurgeMacro
3287 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3289 if (parseIdentifier(Name))
3290 return TokError("expected identifier in '.purgem' directive");
3292 if (getLexer().isNot(AsmToken::EndOfStatement))
3293 return TokError("unexpected token in '.purgem' directive");
3295 if (!lookupMacro(Name))
3296 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3298 undefineMacro(Name);
3302 /// parseDirectiveBundleAlignMode
3303 /// ::= {.bundle_align_mode} expression
3304 bool AsmParser::parseDirectiveBundleAlignMode() {
3305 checkForValidSection();
3307 // Expect a single argument: an expression that evaluates to a constant
3308 // in the inclusive range 0-30.
3309 SMLoc ExprLoc = getLexer().getLoc();
3310 int64_t AlignSizePow2;
3311 if (parseAbsoluteExpression(AlignSizePow2))
3313 else if (getLexer().isNot(AsmToken::EndOfStatement))
3314 return TokError("unexpected token after expression in"
3315 " '.bundle_align_mode' directive");
3316 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3317 return Error(ExprLoc,
3318 "invalid bundle alignment size (expected between 0 and 30)");
3322 // Because of AlignSizePow2's verified range we can safely truncate it to
3324 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3328 /// parseDirectiveBundleLock
3329 /// ::= {.bundle_lock} [align_to_end]
3330 bool AsmParser::parseDirectiveBundleLock() {
3331 checkForValidSection();
3332 bool AlignToEnd = false;
3334 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3336 SMLoc Loc = getTok().getLoc();
3337 const char *kInvalidOptionError =
3338 "invalid option for '.bundle_lock' directive";
3340 if (parseIdentifier(Option))
3341 return Error(Loc, kInvalidOptionError);
3343 if (Option != "align_to_end")
3344 return Error(Loc, kInvalidOptionError);
3345 else if (getLexer().isNot(AsmToken::EndOfStatement))
3347 "unexpected token after '.bundle_lock' directive option");
3353 getStreamer().EmitBundleLock(AlignToEnd);
3357 /// parseDirectiveBundleLock
3358 /// ::= {.bundle_lock}
3359 bool AsmParser::parseDirectiveBundleUnlock() {
3360 checkForValidSection();
3362 if (getLexer().isNot(AsmToken::EndOfStatement))
3363 return TokError("unexpected token in '.bundle_unlock' directive");
3366 getStreamer().EmitBundleUnlock();
3370 /// parseDirectiveSpace
3371 /// ::= (.skip | .space) expression [ , expression ]
3372 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3373 checkForValidSection();
3376 if (parseAbsoluteExpression(NumBytes))
3379 int64_t FillExpr = 0;
3380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3381 if (getLexer().isNot(AsmToken::Comma))
3382 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3385 if (parseAbsoluteExpression(FillExpr))
3388 if (getLexer().isNot(AsmToken::EndOfStatement))
3389 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3395 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3398 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3399 getStreamer().EmitFill(NumBytes, FillExpr);
3404 /// parseDirectiveLEB128
3405 /// ::= (.sleb128 | .uleb128) expression
3406 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3407 checkForValidSection();
3408 const MCExpr *Value;
3410 if (parseExpression(Value))
3413 if (getLexer().isNot(AsmToken::EndOfStatement))
3414 return TokError("unexpected token in directive");
3417 getStreamer().EmitSLEB128Value(Value);
3419 getStreamer().EmitULEB128Value(Value);
3424 /// parseDirectiveSymbolAttribute
3425 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3426 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3427 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3430 SMLoc Loc = getTok().getLoc();
3432 if (parseIdentifier(Name))
3433 return Error(Loc, "expected identifier in directive");
3435 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3437 // Assembler local symbols don't make any sense here. Complain loudly.
3438 if (Sym->isTemporary())
3439 return Error(Loc, "non-local symbol required in directive");
3441 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3442 return Error(Loc, "unable to emit symbol attribute");
3444 if (getLexer().is(AsmToken::EndOfStatement))
3447 if (getLexer().isNot(AsmToken::Comma))
3448 return TokError("unexpected token in directive");
3457 /// parseDirectiveComm
3458 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3459 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3460 checkForValidSection();
3462 SMLoc IDLoc = getLexer().getLoc();
3464 if (parseIdentifier(Name))
3465 return TokError("expected identifier in directive");
3467 // Handle the identifier as the key symbol.
3468 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3470 if (getLexer().isNot(AsmToken::Comma))
3471 return TokError("unexpected token in directive");
3475 SMLoc SizeLoc = getLexer().getLoc();
3476 if (parseAbsoluteExpression(Size))
3479 int64_t Pow2Alignment = 0;
3480 SMLoc Pow2AlignmentLoc;
3481 if (getLexer().is(AsmToken::Comma)) {
3483 Pow2AlignmentLoc = getLexer().getLoc();
3484 if (parseAbsoluteExpression(Pow2Alignment))
3487 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3488 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3489 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3491 // If this target takes alignments in bytes (not log) validate and convert.
3492 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3493 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3494 if (!isPowerOf2_64(Pow2Alignment))
3495 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3496 Pow2Alignment = Log2_64(Pow2Alignment);
3500 if (getLexer().isNot(AsmToken::EndOfStatement))
3501 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3505 // NOTE: a size of zero for a .comm should create a undefined symbol
3506 // but a size of .lcomm creates a bss symbol of size zero.
3508 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3509 "be less than zero");
3511 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3512 // may internally end up wanting an alignment in bytes.
3513 // FIXME: Diagnose overflow.
3514 if (Pow2Alignment < 0)
3515 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3516 "alignment, can't be less than zero");
3518 if (!Sym->isUndefined())
3519 return Error(IDLoc, "invalid symbol redefinition");
3521 // Create the Symbol as a common or local common with Size and Pow2Alignment
3523 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3527 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3531 /// parseDirectiveAbort
3532 /// ::= .abort [... message ...]
3533 bool AsmParser::parseDirectiveAbort() {
3534 // FIXME: Use loc from directive.
3535 SMLoc Loc = getLexer().getLoc();
3537 StringRef Str = parseStringToEndOfStatement();
3538 if (getLexer().isNot(AsmToken::EndOfStatement))
3539 return TokError("unexpected token in '.abort' directive");
3544 Error(Loc, ".abort detected. Assembly stopping.");
3546 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3547 // FIXME: Actually abort assembly here.
3552 /// parseDirectiveInclude
3553 /// ::= .include "filename"
3554 bool AsmParser::parseDirectiveInclude() {
3555 if (getLexer().isNot(AsmToken::String))
3556 return TokError("expected string in '.include' directive");
3558 // Allow the strings to have escaped octal character sequence.
3559 std::string Filename;
3560 if (parseEscapedString(Filename))
3562 SMLoc IncludeLoc = getLexer().getLoc();
3565 if (getLexer().isNot(AsmToken::EndOfStatement))
3566 return TokError("unexpected token in '.include' directive");
3568 // Attempt to switch the lexer to the included file before consuming the end
3569 // of statement to avoid losing it when we switch.
3570 if (enterIncludeFile(Filename)) {
3571 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3578 /// parseDirectiveIncbin
3579 /// ::= .incbin "filename"
3580 bool AsmParser::parseDirectiveIncbin() {
3581 if (getLexer().isNot(AsmToken::String))
3582 return TokError("expected string in '.incbin' directive");
3584 // Allow the strings to have escaped octal character sequence.
3585 std::string Filename;
3586 if (parseEscapedString(Filename))
3588 SMLoc IncbinLoc = getLexer().getLoc();
3591 if (getLexer().isNot(AsmToken::EndOfStatement))
3592 return TokError("unexpected token in '.incbin' directive");
3594 // Attempt to process the included file.
3595 if (processIncbinFile(Filename)) {
3596 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3603 /// parseDirectiveIf
3604 /// ::= .if expression
3605 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3606 TheCondStack.push_back(TheCondState);
3607 TheCondState.TheCond = AsmCond::IfCond;
3608 if (TheCondState.Ignore) {
3609 eatToEndOfStatement();
3612 if (parseAbsoluteExpression(ExprValue))
3615 if (getLexer().isNot(AsmToken::EndOfStatement))
3616 return TokError("unexpected token in '.if' directive");
3620 TheCondState.CondMet = ExprValue;
3621 TheCondState.Ignore = !TheCondState.CondMet;
3627 /// parseDirectiveIfb
3629 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3630 TheCondStack.push_back(TheCondState);
3631 TheCondState.TheCond = AsmCond::IfCond;
3633 if (TheCondState.Ignore) {
3634 eatToEndOfStatement();
3636 StringRef Str = parseStringToEndOfStatement();
3638 if (getLexer().isNot(AsmToken::EndOfStatement))
3639 return TokError("unexpected token in '.ifb' directive");
3643 TheCondState.CondMet = ExpectBlank == Str.empty();
3644 TheCondState.Ignore = !TheCondState.CondMet;
3650 /// parseDirectiveIfc
3651 /// ::= .ifc string1, string2
3652 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3653 TheCondStack.push_back(TheCondState);
3654 TheCondState.TheCond = AsmCond::IfCond;
3656 if (TheCondState.Ignore) {
3657 eatToEndOfStatement();
3659 StringRef Str1 = parseStringToComma();
3661 if (getLexer().isNot(AsmToken::Comma))
3662 return TokError("unexpected token in '.ifc' directive");
3666 StringRef Str2 = parseStringToEndOfStatement();
3668 if (getLexer().isNot(AsmToken::EndOfStatement))
3669 return TokError("unexpected token in '.ifc' directive");
3673 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3674 TheCondState.Ignore = !TheCondState.CondMet;
3680 /// parseDirectiveIfdef
3681 /// ::= .ifdef symbol
3682 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3684 TheCondStack.push_back(TheCondState);
3685 TheCondState.TheCond = AsmCond::IfCond;
3687 if (TheCondState.Ignore) {
3688 eatToEndOfStatement();
3690 if (parseIdentifier(Name))
3691 return TokError("expected identifier after '.ifdef'");
3695 MCSymbol *Sym = getContext().LookupSymbol(Name);
3698 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3700 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3701 TheCondState.Ignore = !TheCondState.CondMet;
3707 /// parseDirectiveElseIf
3708 /// ::= .elseif expression
3709 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3710 if (TheCondState.TheCond != AsmCond::IfCond &&
3711 TheCondState.TheCond != AsmCond::ElseIfCond)
3712 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3714 TheCondState.TheCond = AsmCond::ElseIfCond;
3716 bool LastIgnoreState = false;
3717 if (!TheCondStack.empty())
3718 LastIgnoreState = TheCondStack.back().Ignore;
3719 if (LastIgnoreState || TheCondState.CondMet) {
3720 TheCondState.Ignore = true;
3721 eatToEndOfStatement();
3724 if (parseAbsoluteExpression(ExprValue))
3727 if (getLexer().isNot(AsmToken::EndOfStatement))
3728 return TokError("unexpected token in '.elseif' directive");
3731 TheCondState.CondMet = ExprValue;
3732 TheCondState.Ignore = !TheCondState.CondMet;
3738 /// parseDirectiveElse
3740 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3741 if (getLexer().isNot(AsmToken::EndOfStatement))
3742 return TokError("unexpected token in '.else' directive");
3746 if (TheCondState.TheCond != AsmCond::IfCond &&
3747 TheCondState.TheCond != AsmCond::ElseIfCond)
3748 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3750 TheCondState.TheCond = AsmCond::ElseCond;
3751 bool LastIgnoreState = false;
3752 if (!TheCondStack.empty())
3753 LastIgnoreState = TheCondStack.back().Ignore;
3754 if (LastIgnoreState || TheCondState.CondMet)
3755 TheCondState.Ignore = true;
3757 TheCondState.Ignore = false;
3762 /// parseDirectiveEnd
3764 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3765 if (getLexer().isNot(AsmToken::EndOfStatement))
3766 return TokError("unexpected token in '.end' directive");
3770 while (Lexer.isNot(AsmToken::Eof))
3776 /// parseDirectiveEndIf
3778 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3779 if (getLexer().isNot(AsmToken::EndOfStatement))
3780 return TokError("unexpected token in '.endif' directive");
3784 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3785 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3787 if (!TheCondStack.empty()) {
3788 TheCondState = TheCondStack.back();
3789 TheCondStack.pop_back();
3795 void AsmParser::initializeDirectiveKindMap() {
3796 DirectiveKindMap[".set"] = DK_SET;
3797 DirectiveKindMap[".equ"] = DK_EQU;
3798 DirectiveKindMap[".equiv"] = DK_EQUIV;
3799 DirectiveKindMap[".ascii"] = DK_ASCII;
3800 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3801 DirectiveKindMap[".string"] = DK_STRING;
3802 DirectiveKindMap[".byte"] = DK_BYTE;
3803 DirectiveKindMap[".short"] = DK_SHORT;
3804 DirectiveKindMap[".value"] = DK_VALUE;
3805 DirectiveKindMap[".2byte"] = DK_2BYTE;
3806 DirectiveKindMap[".long"] = DK_LONG;
3807 DirectiveKindMap[".int"] = DK_INT;
3808 DirectiveKindMap[".4byte"] = DK_4BYTE;
3809 DirectiveKindMap[".quad"] = DK_QUAD;
3810 DirectiveKindMap[".8byte"] = DK_8BYTE;
3811 DirectiveKindMap[".single"] = DK_SINGLE;
3812 DirectiveKindMap[".float"] = DK_FLOAT;
3813 DirectiveKindMap[".double"] = DK_DOUBLE;
3814 DirectiveKindMap[".align"] = DK_ALIGN;
3815 DirectiveKindMap[".align32"] = DK_ALIGN32;
3816 DirectiveKindMap[".balign"] = DK_BALIGN;
3817 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3818 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3819 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3820 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3821 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3822 DirectiveKindMap[".org"] = DK_ORG;
3823 DirectiveKindMap[".fill"] = DK_FILL;
3824 DirectiveKindMap[".zero"] = DK_ZERO;
3825 DirectiveKindMap[".extern"] = DK_EXTERN;
3826 DirectiveKindMap[".globl"] = DK_GLOBL;
3827 DirectiveKindMap[".global"] = DK_GLOBAL;
3828 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3829 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3830 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3831 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3832 DirectiveKindMap[".reference"] = DK_REFERENCE;
3833 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3834 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3835 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3836 DirectiveKindMap[".comm"] = DK_COMM;
3837 DirectiveKindMap[".common"] = DK_COMMON;
3838 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3839 DirectiveKindMap[".abort"] = DK_ABORT;
3840 DirectiveKindMap[".include"] = DK_INCLUDE;
3841 DirectiveKindMap[".incbin"] = DK_INCBIN;
3842 DirectiveKindMap[".code16"] = DK_CODE16;
3843 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3844 DirectiveKindMap[".rept"] = DK_REPT;
3845 DirectiveKindMap[".rep"] = DK_REPT;
3846 DirectiveKindMap[".irp"] = DK_IRP;
3847 DirectiveKindMap[".irpc"] = DK_IRPC;
3848 DirectiveKindMap[".endr"] = DK_ENDR;
3849 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3850 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3851 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3852 DirectiveKindMap[".if"] = DK_IF;
3853 DirectiveKindMap[".ifb"] = DK_IFB;
3854 DirectiveKindMap[".ifnb"] = DK_IFNB;
3855 DirectiveKindMap[".ifc"] = DK_IFC;
3856 DirectiveKindMap[".ifnc"] = DK_IFNC;
3857 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3858 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3859 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3860 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3861 DirectiveKindMap[".else"] = DK_ELSE;
3862 DirectiveKindMap[".end"] = DK_END;
3863 DirectiveKindMap[".endif"] = DK_ENDIF;
3864 DirectiveKindMap[".skip"] = DK_SKIP;
3865 DirectiveKindMap[".space"] = DK_SPACE;
3866 DirectiveKindMap[".file"] = DK_FILE;
3867 DirectiveKindMap[".line"] = DK_LINE;
3868 DirectiveKindMap[".loc"] = DK_LOC;
3869 DirectiveKindMap[".stabs"] = DK_STABS;
3870 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3871 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3872 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3873 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3874 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3875 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3876 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3877 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3878 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3879 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3880 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3881 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3882 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3883 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3884 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3885 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3886 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3887 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3888 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3889 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3890 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3891 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
3892 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3893 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3894 DirectiveKindMap[".macro"] = DK_MACRO;
3895 DirectiveKindMap[".endm"] = DK_ENDM;
3896 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3897 DirectiveKindMap[".purgem"] = DK_PURGEM;
3900 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
3901 AsmToken EndToken, StartToken = getTok();
3903 unsigned NestLevel = 0;
3905 // Check whether we have reached the end of the file.
3906 if (getLexer().is(AsmToken::Eof)) {
3907 Error(DirectiveLoc, "no matching '.endr' in definition");
3911 if (Lexer.is(AsmToken::Identifier) &&
3912 (getTok().getIdentifier() == ".rept")) {
3916 // Otherwise, check whether we have reached the .endr.
3917 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
3918 if (NestLevel == 0) {
3919 EndToken = getTok();
3921 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3922 TokError("unexpected token in '.endr' directive");
3930 // Otherwise, scan till the end of the statement.
3931 eatToEndOfStatement();
3934 const char *BodyStart = StartToken.getLoc().getPointer();
3935 const char *BodyEnd = EndToken.getLoc().getPointer();
3936 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3938 // We Are Anonymous.
3940 MCAsmMacroParameters Parameters;
3941 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3942 return &MacroLikeBodies.back();
3945 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3946 raw_svector_ostream &OS) {
3949 MemoryBuffer *Instantiation =
3950 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3952 // Create the macro instantiation object and add to the current macro
3953 // instantiation stack.
3954 MacroInstantiation *MI = new MacroInstantiation(
3955 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
3956 ActiveMacros.push_back(MI);
3958 // Jump to the macro instantiation and prime the lexer.
3959 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3960 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3964 /// parseDirectiveRept
3965 /// ::= .rep | .rept count
3966 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
3967 const MCExpr *CountExpr;
3968 SMLoc CountLoc = getTok().getLoc();
3969 if (parseExpression(CountExpr))
3973 if (!CountExpr->EvaluateAsAbsolute(Count)) {
3974 eatToEndOfStatement();
3975 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
3979 return Error(CountLoc, "Count is negative");
3981 if (Lexer.isNot(AsmToken::EndOfStatement))
3982 return TokError("unexpected token in '" + Dir + "' directive");
3984 // Eat the end of statement.
3987 // Lex the rept definition.
3988 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
3992 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3993 // to hold the macro body with substitutions.
3994 SmallString<256> Buf;
3995 MCAsmMacroParameters Parameters;
3996 MCAsmMacroArguments A;
3997 raw_svector_ostream OS(Buf);
3999 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
4002 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4007 /// parseDirectiveIrp
4008 /// ::= .irp symbol,values
4009 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4010 MCAsmMacroParameters Parameters;
4011 MCAsmMacroParameter Parameter;
4013 if (parseIdentifier(Parameter.first))
4014 return TokError("expected identifier in '.irp' directive");
4016 Parameters.push_back(Parameter);
4018 if (Lexer.isNot(AsmToken::Comma))
4019 return TokError("expected comma in '.irp' directive");
4023 MCAsmMacroArguments A;
4024 if (parseMacroArguments(0, A))
4027 // Eat the end of statement.
4030 // Lex the irp definition.
4031 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4035 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4036 // to hold the macro body with substitutions.
4037 SmallString<256> Buf;
4038 raw_svector_ostream OS(Buf);
4040 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4041 MCAsmMacroArguments Args;
4044 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4048 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4053 /// parseDirectiveIrpc
4054 /// ::= .irpc symbol,values
4055 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4056 MCAsmMacroParameters Parameters;
4057 MCAsmMacroParameter Parameter;
4059 if (parseIdentifier(Parameter.first))
4060 return TokError("expected identifier in '.irpc' directive");
4062 Parameters.push_back(Parameter);
4064 if (Lexer.isNot(AsmToken::Comma))
4065 return TokError("expected comma in '.irpc' directive");
4069 MCAsmMacroArguments A;
4070 if (parseMacroArguments(0, A))
4073 if (A.size() != 1 || A.front().size() != 1)
4074 return TokError("unexpected token in '.irpc' directive");
4076 // Eat the end of statement.
4079 // Lex the irpc definition.
4080 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4084 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4085 // to hold the macro body with substitutions.
4086 SmallString<256> Buf;
4087 raw_svector_ostream OS(Buf);
4089 StringRef Values = A.front().front().getString();
4090 std::size_t I, End = Values.size();
4091 for (I = 0; I < End; ++I) {
4092 MCAsmMacroArgument Arg;
4093 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4095 MCAsmMacroArguments Args;
4096 Args.push_back(Arg);
4098 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4102 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4107 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4108 if (ActiveMacros.empty())
4109 return TokError("unmatched '.endr' directive");
4111 // The only .repl that should get here are the ones created by
4112 // instantiateMacroLikeBody.
4113 assert(getLexer().is(AsmToken::EndOfStatement));
4119 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4121 const MCExpr *Value;
4122 SMLoc ExprLoc = getLexer().getLoc();
4123 if (parseExpression(Value))
4125 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4127 return Error(ExprLoc, "unexpected expression in _emit");
4128 uint64_t IntValue = MCE->getValue();
4129 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4130 return Error(ExprLoc, "literal value out of range for directive");
4132 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4136 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4137 const MCExpr *Value;
4138 SMLoc ExprLoc = getLexer().getLoc();
4139 if (parseExpression(Value))
4141 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4143 return Error(ExprLoc, "unexpected expression in align");
4144 uint64_t IntValue = MCE->getValue();
4145 if (!isPowerOf2_64(IntValue))
4146 return Error(ExprLoc, "literal value not a power of two greater then zero");
4148 Info.AsmRewrites->push_back(
4149 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4153 // We are comparing pointers, but the pointers are relative to a single string.
4154 // Thus, this should always be deterministic.
4155 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4156 const AsmRewrite *AsmRewriteB) {
4157 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4159 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4162 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4163 // rewrite to the same location. Make sure the SizeDirective rewrite is
4164 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4165 // ensures the sort algorithm is stable.
4166 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4167 AsmRewritePrecedence[AsmRewriteB->Kind])
4170 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4171 AsmRewritePrecedence[AsmRewriteB->Kind])
4173 llvm_unreachable("Unstable rewrite sort.");
4176 bool AsmParser::parseMSInlineAsm(
4177 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4178 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4179 SmallVectorImpl<std::string> &Constraints,
4180 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4181 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4182 SmallVector<void *, 4> InputDecls;
4183 SmallVector<void *, 4> OutputDecls;
4184 SmallVector<bool, 4> InputDeclsAddressOf;
4185 SmallVector<bool, 4> OutputDeclsAddressOf;
4186 SmallVector<std::string, 4> InputConstraints;
4187 SmallVector<std::string, 4> OutputConstraints;
4188 SmallVector<unsigned, 4> ClobberRegs;
4190 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4195 // While we have input, parse each statement.
4196 unsigned InputIdx = 0;
4197 unsigned OutputIdx = 0;
4198 while (getLexer().isNot(AsmToken::Eof)) {
4199 ParseStatementInfo Info(&AsmStrRewrites);
4200 if (parseStatement(Info))
4203 if (Info.ParseError)
4206 if (Info.Opcode == ~0U)
4209 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4211 // Build the list of clobbers, outputs and inputs.
4212 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4213 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4216 if (Operand->isImm())
4219 // Register operand.
4220 if (Operand->isReg() && !Operand->needAddressOf()) {
4221 unsigned NumDefs = Desc.getNumDefs();
4223 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4224 ClobberRegs.push_back(Operand->getReg());
4228 // Expr/Input or Output.
4229 StringRef SymName = Operand->getSymName();
4230 if (SymName.empty())
4233 void *OpDecl = Operand->getOpDecl();
4237 bool isOutput = (i == 1) && Desc.mayStore();
4238 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4241 OutputDecls.push_back(OpDecl);
4242 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4243 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4244 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4246 InputDecls.push_back(OpDecl);
4247 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4248 InputConstraints.push_back(Operand->getConstraint().str());
4249 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4253 // Consider implicit defs to be clobbers. Think of cpuid and push.
4254 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4255 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4256 ClobberRegs.push_back(ImpDefs[I]);
4259 // Set the number of Outputs and Inputs.
4260 NumOutputs = OutputDecls.size();
4261 NumInputs = InputDecls.size();
4263 // Set the unique clobbers.
4264 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4265 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4267 Clobbers.assign(ClobberRegs.size(), std::string());
4268 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4269 raw_string_ostream OS(Clobbers[I]);
4270 IP->printRegName(OS, ClobberRegs[I]);
4273 // Merge the various outputs and inputs. Output are expected first.
4274 if (NumOutputs || NumInputs) {
4275 unsigned NumExprs = NumOutputs + NumInputs;
4276 OpDecls.resize(NumExprs);
4277 Constraints.resize(NumExprs);
4278 for (unsigned i = 0; i < NumOutputs; ++i) {
4279 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4280 Constraints[i] = OutputConstraints[i];
4282 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4283 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4284 Constraints[j] = InputConstraints[i];
4288 // Build the IR assembly string.
4289 std::string AsmStringIR;
4290 raw_string_ostream OS(AsmStringIR);
4291 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4292 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4293 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4294 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4295 E = AsmStrRewrites.end();
4297 AsmRewriteKind Kind = (*I).Kind;
4298 if (Kind == AOK_Delete)
4301 const char *Loc = (*I).Loc.getPointer();
4302 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4304 // Emit everything up to the immediate/expression.
4305 unsigned Len = Loc - AsmStart;
4307 OS << StringRef(AsmStart, Len);
4309 // Skip the original expression.
4310 if (Kind == AOK_Skip) {
4311 AsmStart = Loc + (*I).Len;
4315 unsigned AdditionalSkip = 0;
4316 // Rewrite expressions in $N notation.
4321 OS << "$$" << (*I).Val;
4327 OS << '$' << InputIdx++;
4330 OS << '$' << OutputIdx++;
4332 case AOK_SizeDirective:
4335 case 8: OS << "byte ptr "; break;
4336 case 16: OS << "word ptr "; break;
4337 case 32: OS << "dword ptr "; break;
4338 case 64: OS << "qword ptr "; break;
4339 case 80: OS << "xword ptr "; break;
4340 case 128: OS << "xmmword ptr "; break;
4341 case 256: OS << "ymmword ptr "; break;
4348 unsigned Val = (*I).Val;
4349 OS << ".align " << Val;
4351 // Skip the original immediate.
4352 assert(Val < 10 && "Expected alignment less then 2^10.");
4353 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4356 case AOK_DotOperator:
4361 // Skip the original expression.
4362 AsmStart = Loc + (*I).Len + AdditionalSkip;
4365 // Emit the remainder of the asm string.
4366 if (AsmStart != AsmEnd)
4367 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4369 AsmString = OS.str();
4373 /// \brief Create an MCAsmParser instance.
4374 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4375 MCStreamer &Out, const MCAsmInfo &MAI) {
4376 return new AsmParser(SM, C, Out, MAI);