1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 FatalAssemblerWarnings("fatal-assembler-warnings",
49 cl::desc("Consider warnings as error"));
51 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
55 /// \brief Helper types for tracking macro definitions.
56 typedef std::vector<AsmToken> MCAsmMacroArgument;
57 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
59 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
64 MCAsmMacroParameters Parameters;
67 MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
68 Name(N), Body(B), Parameters(P) {}
71 /// \brief Helper class for storing information about an active macro
73 struct MacroInstantiation {
74 /// The macro being instantiated.
75 const MCAsmMacro *TheMacro;
77 /// The macro instantiation with substitutions.
78 MemoryBuffer *Instantiation;
80 /// The location of the instantiation.
81 SMLoc InstantiationLoc;
83 /// The buffer where parsing should resume upon instantiation completion.
86 /// The location where parsing should resume upon instantiation completion.
90 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
94 struct ParseStatementInfo {
95 /// \brief The parsed operands from the last parsed statement.
96 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
98 /// \brief The opcode from the last parsed instruction.
101 /// \brief Was there an error parsing the inline assembly?
104 SmallVectorImpl<AsmRewrite> *AsmRewrites;
106 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
107 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
108 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
110 ~ParseStatementInfo() {
111 // Free any parsed operands.
112 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
113 delete ParsedOperands[i];
114 ParsedOperands.clear();
118 /// \brief The concrete assembly parser instance.
119 class AsmParser : public MCAsmParser {
120 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
121 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
126 const MCAsmInfo &MAI;
128 SourceMgr::DiagHandlerTy SavedDiagHandler;
129 void *SavedDiagContext;
130 MCAsmParserExtension *PlatformParser;
132 /// This is the current buffer index we're lexing from as managed by the
133 /// SourceMgr object.
136 AsmCond TheCondState;
137 std::vector<AsmCond> TheCondStack;
139 /// \brief maps directive names to handler methods in parser
140 /// extensions. Extensions register themselves in this map by calling
141 /// addDirectiveHandler.
142 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
144 /// \brief Map of currently defined macros.
145 StringMap<MCAsmMacro*> MacroMap;
147 /// \brief Stack of active macro instantiations.
148 std::vector<MacroInstantiation*> ActiveMacros;
150 /// \brief List of bodies of anonymous macros.
151 std::deque<MCAsmMacro> MacroLikeBodies;
153 /// Boolean tracking whether macro substitution is enabled.
154 unsigned MacrosEnabledFlag : 1;
156 /// Flag tracking whether any errors have been encountered.
157 unsigned HadError : 1;
159 /// The values from the last parsed cpp hash file line comment if any.
160 StringRef CppHashFilename;
161 int64_t CppHashLineNumber;
164 /// When generating dwarf for assembly source files we need to calculate the
165 /// logical line number based on the last parsed cpp hash file line comment
166 /// and current line. Since this is slow and messes up the SourceMgr's
167 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
168 SMLoc LastQueryIDLoc;
170 unsigned LastQueryLine;
172 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
173 unsigned AssemblerDialect;
175 /// \brief is Darwin compatibility enabled?
178 /// \brief Are we parsing ms-style inline assembly?
179 bool ParsingInlineAsm;
182 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
183 const MCAsmInfo &MAI);
184 virtual ~AsmParser();
186 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
188 virtual void addDirectiveHandler(StringRef Directive,
189 ExtensionDirectiveHandler Handler) {
190 ExtensionDirectiveMap[Directive] = Handler;
194 /// @name MCAsmParser Interface
197 virtual SourceMgr &getSourceManager() { return SrcMgr; }
198 virtual MCAsmLexer &getLexer() { return Lexer; }
199 virtual MCContext &getContext() { return Ctx; }
200 virtual MCStreamer &getStreamer() { return Out; }
201 virtual unsigned getAssemblerDialect() {
202 if (AssemblerDialect == ~0U)
203 return MAI.getAssemblerDialect();
205 return AssemblerDialect;
207 virtual void setAssemblerDialect(unsigned i) {
208 AssemblerDialect = i;
211 virtual void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None);
212 virtual bool Warning(SMLoc L, const Twine &Msg,
213 ArrayRef<SMRange> Ranges = None);
214 virtual bool Error(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None);
217 virtual const AsmToken &Lex();
219 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
220 bool isParsingInlineAsm() { return ParsingInlineAsm; }
222 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
223 unsigned &NumOutputs, unsigned &NumInputs,
224 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
225 SmallVectorImpl<std::string> &Constraints,
226 SmallVectorImpl<std::string> &Clobbers,
227 const MCInstrInfo *MII,
228 const MCInstPrinter *IP,
229 MCAsmParserSemaCallback &SI);
231 bool parseExpression(const MCExpr *&Res);
232 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
233 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
234 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
235 virtual bool parseAbsoluteExpression(int64_t &Res);
237 /// \brief Parse an identifier or string (as a quoted identifier)
238 /// and set \p Res to the identifier contents.
239 virtual bool parseIdentifier(StringRef &Res);
240 virtual void eatToEndOfStatement();
242 virtual void checkForValidSection();
247 bool parseStatement(ParseStatementInfo &Info);
248 void eatToEndOfLine();
249 bool parseCppHashLineFilenameComment(const SMLoc &L);
251 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
252 ArrayRef<MCAsmMacroParameter> Parameters);
253 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
254 ArrayRef<MCAsmMacroParameter> Parameters,
255 ArrayRef<MCAsmMacroArgument> A,
258 /// \brief Are macros enabled in the parser?
259 bool areMacrosEnabled() {return MacrosEnabledFlag;}
261 /// \brief Control a flag in the parser that enables or disables macros.
262 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
264 /// \brief Lookup a previously defined macro.
265 /// \param Name Macro name.
266 /// \returns Pointer to macro. NULL if no such macro was defined.
267 const MCAsmMacro* lookupMacro(StringRef Name);
269 /// \brief Define a new macro with the given name and information.
270 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
272 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
273 void undefineMacro(StringRef Name);
275 /// \brief Are we inside a macro instantiation?
276 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
278 /// \brief Handle entry to macro instantiation.
280 /// \param M The macro.
281 /// \param NameLoc Instantiation location.
282 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
284 /// \brief Handle exit from macro instantiation.
285 void handleMacroExit();
287 /// \brief Extract AsmTokens for a macro argument.
288 bool parseMacroArgument(MCAsmMacroArgument &MA);
290 /// \brief Parse all macro arguments for a given macro.
291 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
293 void printMacroInstantiations();
294 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
295 ArrayRef<SMRange> Ranges = None) const {
296 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
298 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
300 /// \brief Enter the specified file. This returns true on failure.
301 bool enterIncludeFile(const std::string &Filename);
303 /// \brief Process the specified file for the .incbin directive.
304 /// This returns true on failure.
305 bool processIncbinFile(const std::string &Filename);
307 /// \brief Reset the current lexer position to that given by \p Loc. The
308 /// current token is not set; clients should ensure Lex() is called
311 /// \param InBuffer If not -1, should be the known buffer id that contains the
313 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
315 /// \brief Parse up to the end of statement and a return the contents from the
316 /// current token until the end of the statement; the current token on exit
317 /// will be either the EndOfStatement or EOF.
318 virtual StringRef parseStringToEndOfStatement();
320 /// \brief Parse until the end of a statement or a comma is encountered,
321 /// return the contents from the current token up to the end or comma.
322 StringRef parseStringToComma();
324 bool parseAssignment(StringRef Name, bool allow_redef,
325 bool NoDeadStrip = false);
327 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
328 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
329 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
331 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
333 // Generic (target and platform independent) directive parsing.
335 DK_NO_DIRECTIVE, // Placeholder
336 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
337 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
338 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
339 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
340 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
341 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
342 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
343 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
344 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
345 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
346 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
347 DK_ELSEIF, DK_ELSE, DK_ENDIF,
348 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
349 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
350 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
351 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
352 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
353 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
354 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
355 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
356 DK_SLEB128, DK_ULEB128,
360 /// \brief Maps directive name --> DirectiveKind enum, for
361 /// directives parsed by this class.
362 StringMap<DirectiveKind> DirectiveKindMap;
364 // ".ascii", ".asciz", ".string"
365 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
366 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
367 bool parseDirectiveOctaValue(); // ".octa"
368 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
369 bool parseDirectiveFill(); // ".fill"
370 bool parseDirectiveZero(); // ".zero"
371 // ".set", ".equ", ".equiv"
372 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
373 bool parseDirectiveOrg(); // ".org"
374 // ".align{,32}", ".p2align{,w,l}"
375 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
377 // ".file", ".line", ".loc", ".stabs"
378 bool parseDirectiveFile(SMLoc DirectiveLoc);
379 bool parseDirectiveLine();
380 bool parseDirectiveLoc();
381 bool parseDirectiveStabs();
384 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
385 bool parseDirectiveCFIWindowSave();
386 bool parseDirectiveCFISections();
387 bool parseDirectiveCFIStartProc();
388 bool parseDirectiveCFIEndProc();
389 bool parseDirectiveCFIDefCfaOffset();
390 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
391 bool parseDirectiveCFIAdjustCfaOffset();
392 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
394 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
395 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
396 bool parseDirectiveCFIRememberState();
397 bool parseDirectiveCFIRestoreState();
398 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
400 bool parseDirectiveCFIEscape();
401 bool parseDirectiveCFISignalFrame();
402 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
405 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
406 bool parseDirectiveEndMacro(StringRef Directive);
407 bool parseDirectiveMacro(SMLoc DirectiveLoc);
408 bool parseDirectiveMacrosOnOff(StringRef Directive);
410 // ".bundle_align_mode"
411 bool parseDirectiveBundleAlignMode();
413 bool parseDirectiveBundleLock();
415 bool parseDirectiveBundleUnlock();
418 bool parseDirectiveSpace(StringRef IDVal);
420 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
421 bool parseDirectiveLEB128(bool Signed);
423 /// \brief Parse a directive like ".globl" which
424 /// accepts a single symbol (which should be a label or an external).
425 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
427 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
429 bool parseDirectiveAbort(); // ".abort"
430 bool parseDirectiveInclude(); // ".include"
431 bool parseDirectiveIncbin(); // ".incbin"
433 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
434 // ".ifb" or ".ifnb", depending on ExpectBlank.
435 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
436 // ".ifc" or ".ifnc", depending on ExpectEqual.
437 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
438 // ".ifdef" or ".ifndef", depending on expect_defined
439 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
440 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
441 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
442 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
443 virtual bool parseEscapedString(std::string &Data);
445 const MCExpr *applyModifierToExpr(const MCExpr *E,
446 MCSymbolRefExpr::VariantKind Variant);
448 // Macro-like directives
449 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
450 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
451 raw_svector_ostream &OS);
452 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
453 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
454 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
455 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
457 // "_emit" or "__emit"
458 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
462 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
465 bool parseDirectiveEnd(SMLoc DirectiveLoc);
467 void initializeDirectiveKindMap();
473 extern MCAsmParserExtension *createDarwinAsmParser();
474 extern MCAsmParserExtension *createELFAsmParser();
475 extern MCAsmParserExtension *createCOFFAsmParser();
479 enum { DEFAULT_ADDRSPACE = 0 };
481 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
482 const MCAsmInfo &_MAI)
483 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
484 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
485 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
486 ParsingInlineAsm(false) {
487 // Save the old handler.
488 SavedDiagHandler = SrcMgr.getDiagHandler();
489 SavedDiagContext = SrcMgr.getDiagContext();
490 // Set our own handler which calls the saved handler.
491 SrcMgr.setDiagHandler(DiagHandler, this);
492 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
494 // Initialize the platform / file format parser.
495 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
496 case MCObjectFileInfo::IsCOFF:
497 PlatformParser = createCOFFAsmParser();
498 PlatformParser->Initialize(*this);
500 case MCObjectFileInfo::IsMachO:
501 PlatformParser = createDarwinAsmParser();
502 PlatformParser->Initialize(*this);
505 case MCObjectFileInfo::IsELF:
506 PlatformParser = createELFAsmParser();
507 PlatformParser->Initialize(*this);
511 initializeDirectiveKindMap();
514 AsmParser::~AsmParser() {
515 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
517 // Destroy any macros.
518 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
521 delete it->getValue();
523 delete PlatformParser;
526 void AsmParser::printMacroInstantiations() {
527 // Print the active macro instantiation stack.
528 for (std::vector<MacroInstantiation *>::const_reverse_iterator
529 it = ActiveMacros.rbegin(),
530 ie = ActiveMacros.rend();
532 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
533 "while in macro instantiation");
536 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
537 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
538 printMacroInstantiations();
541 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
542 if (FatalAssemblerWarnings)
543 return Error(L, Msg, Ranges);
544 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
545 printMacroInstantiations();
549 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
551 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
552 printMacroInstantiations();
556 bool AsmParser::enterIncludeFile(const std::string &Filename) {
557 std::string IncludedFile;
558 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
564 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
569 /// Process the specified .incbin file by searching for it in the include paths
570 /// then just emitting the byte contents of the file to the streamer. This
571 /// returns true on failure.
572 bool AsmParser::processIncbinFile(const std::string &Filename) {
573 std::string IncludedFile;
574 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
578 // Pick up the bytes from the file and emit them.
579 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
583 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
584 if (InBuffer != -1) {
585 CurBuffer = InBuffer;
587 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
589 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
592 const AsmToken &AsmParser::Lex() {
593 const AsmToken *tok = &Lexer.Lex();
595 if (tok->is(AsmToken::Eof)) {
596 // If this is the end of an included file, pop the parent file off the
598 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
599 if (ParentIncludeLoc != SMLoc()) {
600 jumpToLoc(ParentIncludeLoc);
605 if (tok->is(AsmToken::Error))
606 Error(Lexer.getErrLoc(), Lexer.getErr());
611 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
612 // Create the initial section, if requested.
613 if (!NoInitialTextSection)
620 AsmCond StartingCondState = TheCondState;
622 // If we are generating dwarf for assembly source files save the initial text
623 // section and generate a .file directive.
624 if (getContext().getGenDwarfForAssembly()) {
625 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
626 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
627 getStreamer().EmitLabel(SectionStartSym);
628 getContext().setGenDwarfSectionStartSym(SectionStartSym);
629 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
631 getContext().getMainFileName());
634 // While we have input, parse each statement.
635 while (Lexer.isNot(AsmToken::Eof)) {
636 ParseStatementInfo Info;
637 if (!parseStatement(Info))
640 // We had an error, validate that one was emitted and recover by skipping to
642 assert(HadError && "Parse statement returned an error, but none emitted!");
643 eatToEndOfStatement();
646 if (TheCondState.TheCond != StartingCondState.TheCond ||
647 TheCondState.Ignore != StartingCondState.Ignore)
648 return TokError("unmatched .ifs or .elses");
650 // Check to see there are no empty DwarfFile slots.
651 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
652 getContext().getMCDwarfFiles();
653 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
654 if (!MCDwarfFiles[i])
655 TokError("unassigned file number: " + Twine(i) + " for .file directives");
658 // Check to see that all assembler local symbols were actually defined.
659 // Targets that don't do subsections via symbols may not want this, though,
660 // so conservatively exclude them. Only do this if we're finalizing, though,
661 // as otherwise we won't necessarilly have seen everything yet.
662 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
663 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
664 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
667 MCSymbol *Sym = i->getValue();
668 // Variable symbols may not be marked as defined, so check those
669 // explicitly. If we know it's a variable, we have a definition for
670 // the purposes of this check.
671 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
672 // FIXME: We would really like to refer back to where the symbol was
673 // first referenced for a source location. We need to add something
674 // to track that. Currently, we just point to the end of the file.
676 getLexer().getLoc(), SourceMgr::DK_Error,
677 "assembler local symbol '" + Sym->getName() + "' not defined");
681 // Finalize the output stream if there are no errors and if the client wants
683 if (!HadError && !NoFinalize)
689 void AsmParser::checkForValidSection() {
690 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
691 TokError("expected section directive before assembly directive");
696 /// \brief Throw away the rest of the line for testing purposes.
697 void AsmParser::eatToEndOfStatement() {
698 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
702 if (Lexer.is(AsmToken::EndOfStatement))
706 StringRef AsmParser::parseStringToEndOfStatement() {
707 const char *Start = getTok().getLoc().getPointer();
709 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
712 const char *End = getTok().getLoc().getPointer();
713 return StringRef(Start, End - Start);
716 StringRef AsmParser::parseStringToComma() {
717 const char *Start = getTok().getLoc().getPointer();
719 while (Lexer.isNot(AsmToken::EndOfStatement) &&
720 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
723 const char *End = getTok().getLoc().getPointer();
724 return StringRef(Start, End - Start);
727 /// \brief Parse a paren expression and return it.
728 /// NOTE: This assumes the leading '(' has already been consumed.
730 /// parenexpr ::= expr)
732 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
733 if (parseExpression(Res))
735 if (Lexer.isNot(AsmToken::RParen))
736 return TokError("expected ')' in parentheses expression");
737 EndLoc = Lexer.getTok().getEndLoc();
742 /// \brief Parse a bracket expression and return it.
743 /// NOTE: This assumes the leading '[' has already been consumed.
745 /// bracketexpr ::= expr]
747 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
748 if (parseExpression(Res))
750 if (Lexer.isNot(AsmToken::RBrac))
751 return TokError("expected ']' in brackets expression");
752 EndLoc = Lexer.getTok().getEndLoc();
757 /// \brief Parse a primary expression and return it.
758 /// primaryexpr ::= (parenexpr
759 /// primaryexpr ::= symbol
760 /// primaryexpr ::= number
761 /// primaryexpr ::= '.'
762 /// primaryexpr ::= ~,+,- primaryexpr
763 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
764 SMLoc FirstTokenLoc = getLexer().getLoc();
765 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
766 switch (FirstTokenKind) {
768 return TokError("unknown token in expression");
769 // If we have an error assume that we've already handled it.
770 case AsmToken::Error:
772 case AsmToken::Exclaim:
773 Lex(); // Eat the operator.
774 if (parsePrimaryExpr(Res, EndLoc))
776 Res = MCUnaryExpr::CreateLNot(Res, getContext());
778 case AsmToken::Dollar:
780 case AsmToken::String:
781 case AsmToken::Identifier: {
782 StringRef Identifier;
783 if (parseIdentifier(Identifier)) {
784 if (FirstTokenKind == AsmToken::Dollar) {
785 if (Lexer.getMAI().getDollarIsPC()) {
786 // This is a '$' reference, which references the current PC. Emit a
787 // temporary label to the streamer and refer to it.
788 MCSymbol *Sym = Ctx.CreateTempSymbol();
790 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
792 EndLoc = FirstTokenLoc;
795 return Error(FirstTokenLoc, "invalid token in expression");
799 // Parse symbol variant
800 std::pair<StringRef, StringRef> Split;
801 if (!MAI.useParensForSymbolVariant()) {
802 Split = Identifier.split('@');
803 } else if (Lexer.is(AsmToken::LParen)) {
804 Lexer.Lex(); // eat (
806 parseIdentifier(VName);
807 if (Lexer.isNot(AsmToken::RParen)) {
808 return Error(Lexer.getTok().getLoc(),
809 "unexpected token in variant, expected ')'");
811 Lexer.Lex(); // eat )
812 Split = std::make_pair(Identifier, VName);
815 EndLoc = SMLoc::getFromPointer(Identifier.end());
817 // This is a symbol reference.
818 StringRef SymbolName = Identifier;
819 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
821 // Lookup the symbol variant if used.
822 if (Split.second.size()) {
823 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
824 if (Variant != MCSymbolRefExpr::VK_Invalid) {
825 SymbolName = Split.first;
826 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
827 Variant = MCSymbolRefExpr::VK_None;
829 Variant = MCSymbolRefExpr::VK_None;
830 return Error(SMLoc::getFromPointer(Split.second.begin()),
831 "invalid variant '" + Split.second + "'");
835 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
837 // If this is an absolute variable reference, substitute it now to preserve
838 // semantics in the face of reassignment.
839 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
841 return Error(EndLoc, "unexpected modifier on variable reference");
843 Res = Sym->getVariableValue();
847 // Otherwise create a symbol ref.
848 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
851 case AsmToken::BigNum:
852 return TokError("literal value out of range for directive");
853 case AsmToken::Integer: {
854 SMLoc Loc = getTok().getLoc();
855 int64_t IntVal = getTok().getIntVal();
856 Res = MCConstantExpr::Create(IntVal, getContext());
857 EndLoc = Lexer.getTok().getEndLoc();
859 // Look for 'b' or 'f' following an Integer as a directional label
860 if (Lexer.getKind() == AsmToken::Identifier) {
861 StringRef IDVal = getTok().getString();
862 // Lookup the symbol variant if used.
863 std::pair<StringRef, StringRef> Split = IDVal.split('@');
864 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
865 if (Split.first.size() != IDVal.size()) {
866 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
867 if (Variant == MCSymbolRefExpr::VK_Invalid) {
868 Variant = MCSymbolRefExpr::VK_None;
869 return TokError("invalid variant '" + Split.second + "'");
873 if (IDVal == "f" || IDVal == "b") {
875 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
876 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
877 if (IDVal == "b" && Sym->isUndefined())
878 return Error(Loc, "invalid reference to undefined symbol");
879 EndLoc = Lexer.getTok().getEndLoc();
880 Lex(); // Eat identifier.
885 case AsmToken::Real: {
886 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
887 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
888 Res = MCConstantExpr::Create(IntVal, getContext());
889 EndLoc = Lexer.getTok().getEndLoc();
893 case AsmToken::Dot: {
894 // This is a '.' reference, which references the current PC. Emit a
895 // temporary label to the streamer and refer to it.
896 MCSymbol *Sym = Ctx.CreateTempSymbol();
898 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
899 EndLoc = Lexer.getTok().getEndLoc();
900 Lex(); // Eat identifier.
903 case AsmToken::LParen:
904 Lex(); // Eat the '('.
905 return parseParenExpr(Res, EndLoc);
906 case AsmToken::LBrac:
907 if (!PlatformParser->HasBracketExpressions())
908 return TokError("brackets expression not supported on this target");
909 Lex(); // Eat the '['.
910 return parseBracketExpr(Res, EndLoc);
911 case AsmToken::Minus:
912 Lex(); // Eat the operator.
913 if (parsePrimaryExpr(Res, EndLoc))
915 Res = MCUnaryExpr::CreateMinus(Res, getContext());
918 Lex(); // Eat the operator.
919 if (parsePrimaryExpr(Res, EndLoc))
921 Res = MCUnaryExpr::CreatePlus(Res, getContext());
923 case AsmToken::Tilde:
924 Lex(); // Eat the operator.
925 if (parsePrimaryExpr(Res, EndLoc))
927 Res = MCUnaryExpr::CreateNot(Res, getContext());
932 bool AsmParser::parseExpression(const MCExpr *&Res) {
934 return parseExpression(Res, EndLoc);
938 AsmParser::applyModifierToExpr(const MCExpr *E,
939 MCSymbolRefExpr::VariantKind Variant) {
940 // Ask the target implementation about this expression first.
941 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
944 // Recurse over the given expression, rebuilding it to apply the given variant
945 // if there is exactly one symbol.
946 switch (E->getKind()) {
948 case MCExpr::Constant:
951 case MCExpr::SymbolRef: {
952 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
954 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
955 TokError("invalid variant on expression '" + getTok().getIdentifier() +
956 "' (already modified)");
960 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
963 case MCExpr::Unary: {
964 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
965 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
968 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
971 case MCExpr::Binary: {
972 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
973 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
974 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
984 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
988 llvm_unreachable("Invalid expression kind!");
991 /// \brief Parse an expression and return it.
993 /// expr ::= expr &&,|| expr -> lowest.
994 /// expr ::= expr |,^,&,! expr
995 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
996 /// expr ::= expr <<,>> expr
997 /// expr ::= expr +,- expr
998 /// expr ::= expr *,/,% expr -> highest.
999 /// expr ::= primaryexpr
1001 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1002 // Parse the expression.
1004 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1007 // As a special case, we support 'a op b @ modifier' by rewriting the
1008 // expression to include the modifier. This is inefficient, but in general we
1009 // expect users to use 'a@modifier op b'.
1010 if (Lexer.getKind() == AsmToken::At) {
1013 if (Lexer.isNot(AsmToken::Identifier))
1014 return TokError("unexpected symbol modifier following '@'");
1016 MCSymbolRefExpr::VariantKind Variant =
1017 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1018 if (Variant == MCSymbolRefExpr::VK_Invalid)
1019 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1021 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1023 return TokError("invalid modifier '" + getTok().getIdentifier() +
1024 "' (no symbols present)");
1031 // Try to constant fold it up front, if possible.
1033 if (Res->EvaluateAsAbsolute(Value))
1034 Res = MCConstantExpr::Create(Value, getContext());
1039 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1041 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1044 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1047 SMLoc StartLoc = Lexer.getLoc();
1048 if (parseExpression(Expr))
1051 if (!Expr->EvaluateAsAbsolute(Res))
1052 return Error(StartLoc, "expected absolute expression");
1057 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1058 MCBinaryExpr::Opcode &Kind) {
1061 return 0; // not a binop.
1063 // Lowest Precedence: &&, ||
1064 case AsmToken::AmpAmp:
1065 Kind = MCBinaryExpr::LAnd;
1067 case AsmToken::PipePipe:
1068 Kind = MCBinaryExpr::LOr;
1071 // Low Precedence: |, &, ^
1073 // FIXME: gas seems to support '!' as an infix operator?
1074 case AsmToken::Pipe:
1075 Kind = MCBinaryExpr::Or;
1077 case AsmToken::Caret:
1078 Kind = MCBinaryExpr::Xor;
1081 Kind = MCBinaryExpr::And;
1084 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1085 case AsmToken::EqualEqual:
1086 Kind = MCBinaryExpr::EQ;
1088 case AsmToken::ExclaimEqual:
1089 case AsmToken::LessGreater:
1090 Kind = MCBinaryExpr::NE;
1092 case AsmToken::Less:
1093 Kind = MCBinaryExpr::LT;
1095 case AsmToken::LessEqual:
1096 Kind = MCBinaryExpr::LTE;
1098 case AsmToken::Greater:
1099 Kind = MCBinaryExpr::GT;
1101 case AsmToken::GreaterEqual:
1102 Kind = MCBinaryExpr::GTE;
1105 // Intermediate Precedence: <<, >>
1106 case AsmToken::LessLess:
1107 Kind = MCBinaryExpr::Shl;
1109 case AsmToken::GreaterGreater:
1110 Kind = MCBinaryExpr::Shr;
1113 // High Intermediate Precedence: +, -
1114 case AsmToken::Plus:
1115 Kind = MCBinaryExpr::Add;
1117 case AsmToken::Minus:
1118 Kind = MCBinaryExpr::Sub;
1121 // Highest Precedence: *, /, %
1122 case AsmToken::Star:
1123 Kind = MCBinaryExpr::Mul;
1125 case AsmToken::Slash:
1126 Kind = MCBinaryExpr::Div;
1128 case AsmToken::Percent:
1129 Kind = MCBinaryExpr::Mod;
1134 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1135 /// Res contains the LHS of the expression on input.
1136 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1139 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1140 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1142 // If the next token is lower precedence than we are allowed to eat, return
1143 // successfully with what we ate already.
1144 if (TokPrec < Precedence)
1149 // Eat the next primary expression.
1151 if (parsePrimaryExpr(RHS, EndLoc))
1154 // If BinOp binds less tightly with RHS than the operator after RHS, let
1155 // the pending operator take RHS as its LHS.
1156 MCBinaryExpr::Opcode Dummy;
1157 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1158 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1161 // Merge LHS and RHS according to operator.
1162 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1167 /// ::= EndOfStatement
1168 /// ::= Label* Directive ...Operands... EndOfStatement
1169 /// ::= Label* Identifier OperandList* EndOfStatement
1170 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1171 if (Lexer.is(AsmToken::EndOfStatement)) {
1177 // Statements always start with an identifier or are a full line comment.
1178 AsmToken ID = getTok();
1179 SMLoc IDLoc = ID.getLoc();
1181 int64_t LocalLabelVal = -1;
1182 // A full line comment is a '#' as the first token.
1183 if (Lexer.is(AsmToken::Hash))
1184 return parseCppHashLineFilenameComment(IDLoc);
1186 // Allow an integer followed by a ':' as a directional local label.
1187 if (Lexer.is(AsmToken::Integer)) {
1188 LocalLabelVal = getTok().getIntVal();
1189 if (LocalLabelVal < 0) {
1190 if (!TheCondState.Ignore)
1191 return TokError("unexpected token at start of statement");
1194 IDVal = getTok().getString();
1195 Lex(); // Consume the integer token to be used as an identifier token.
1196 if (Lexer.getKind() != AsmToken::Colon) {
1197 if (!TheCondState.Ignore)
1198 return TokError("unexpected token at start of statement");
1201 } else if (Lexer.is(AsmToken::Dot)) {
1202 // Treat '.' as a valid identifier in this context.
1205 } else if (parseIdentifier(IDVal)) {
1206 if (!TheCondState.Ignore)
1207 return TokError("unexpected token at start of statement");
1211 // Handle conditional assembly here before checking for skipping. We
1212 // have to do this so that .endif isn't skipped in a ".if 0" block for
1214 StringMap<DirectiveKind>::const_iterator DirKindIt =
1215 DirectiveKindMap.find(IDVal);
1216 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1218 : DirKindIt->getValue();
1223 return parseDirectiveIf(IDLoc);
1225 return parseDirectiveIfb(IDLoc, true);
1227 return parseDirectiveIfb(IDLoc, false);
1229 return parseDirectiveIfc(IDLoc, true);
1231 return parseDirectiveIfc(IDLoc, false);
1233 return parseDirectiveIfdef(IDLoc, true);
1236 return parseDirectiveIfdef(IDLoc, false);
1238 return parseDirectiveElseIf(IDLoc);
1240 return parseDirectiveElse(IDLoc);
1242 return parseDirectiveEndIf(IDLoc);
1245 // Ignore the statement if in the middle of inactive conditional
1247 if (TheCondState.Ignore) {
1248 eatToEndOfStatement();
1252 // FIXME: Recurse on local labels?
1254 // See what kind of statement we have.
1255 switch (Lexer.getKind()) {
1256 case AsmToken::Colon: {
1257 checkForValidSection();
1259 // identifier ':' -> Label.
1262 // Diagnose attempt to use '.' as a label.
1264 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1266 // Diagnose attempt to use a variable as a label.
1268 // FIXME: Diagnostics. Note the location of the definition as a label.
1269 // FIXME: This doesn't diagnose assignment to a symbol which has been
1270 // implicitly marked as external.
1272 if (LocalLabelVal == -1)
1273 Sym = getContext().GetOrCreateSymbol(IDVal);
1275 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1276 if (!Sym->isUndefined() || Sym->isVariable())
1277 return Error(IDLoc, "invalid symbol redefinition");
1280 if (!ParsingInlineAsm)
1283 // If we are generating dwarf for assembly source files then gather the
1284 // info to make a dwarf label entry for this label if needed.
1285 if (getContext().getGenDwarfForAssembly())
1286 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1289 getTargetParser().onLabelParsed(Sym);
1291 // Consume any end of statement token, if present, to avoid spurious
1292 // AddBlankLine calls().
1293 if (Lexer.is(AsmToken::EndOfStatement)) {
1295 if (Lexer.is(AsmToken::Eof))
1302 case AsmToken::Equal:
1303 // identifier '=' ... -> assignment statement
1306 return parseAssignment(IDVal, true);
1308 default: // Normal instruction or directive.
1312 // If macros are enabled, check to see if this is a macro instantiation.
1313 if (areMacrosEnabled())
1314 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1315 return handleMacroEntry(M, IDLoc);
1318 // Otherwise, we have a normal instruction or directive.
1320 // Directives start with "."
1321 if (IDVal[0] == '.' && IDVal != ".") {
1322 // There are several entities interested in parsing directives:
1324 // 1. The target-specific assembly parser. Some directives are target
1325 // specific or may potentially behave differently on certain targets.
1326 // 2. Asm parser extensions. For example, platform-specific parsers
1327 // (like the ELF parser) register themselves as extensions.
1328 // 3. The generic directive parser implemented by this class. These are
1329 // all the directives that behave in a target and platform independent
1330 // manner, or at least have a default behavior that's shared between
1331 // all targets and platforms.
1333 // First query the target-specific parser. It will return 'true' if it
1334 // isn't interested in this directive.
1335 if (!getTargetParser().ParseDirective(ID))
1338 // Next, check the extension directive map to see if any extension has
1339 // registered itself to parse this directive.
1340 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1341 ExtensionDirectiveMap.lookup(IDVal);
1343 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1345 // Finally, if no one else is interested in this directive, it must be
1346 // generic and familiar to this class.
1352 return parseDirectiveSet(IDVal, true);
1354 return parseDirectiveSet(IDVal, false);
1356 return parseDirectiveAscii(IDVal, false);
1359 return parseDirectiveAscii(IDVal, true);
1361 return parseDirectiveValue(1);
1365 return parseDirectiveValue(2);
1369 return parseDirectiveValue(4);
1372 return parseDirectiveValue(8);
1374 return parseDirectiveOctaValue();
1377 return parseDirectiveRealValue(APFloat::IEEEsingle);
1379 return parseDirectiveRealValue(APFloat::IEEEdouble);
1381 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1382 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1385 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1386 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1389 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1391 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1393 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1395 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1397 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1399 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1401 return parseDirectiveOrg();
1403 return parseDirectiveFill();
1405 return parseDirectiveZero();
1407 eatToEndOfStatement(); // .extern is the default, ignore it.
1411 return parseDirectiveSymbolAttribute(MCSA_Global);
1412 case DK_LAZY_REFERENCE:
1413 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1414 case DK_NO_DEAD_STRIP:
1415 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1416 case DK_SYMBOL_RESOLVER:
1417 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1418 case DK_PRIVATE_EXTERN:
1419 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1421 return parseDirectiveSymbolAttribute(MCSA_Reference);
1422 case DK_WEAK_DEFINITION:
1423 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1424 case DK_WEAK_REFERENCE:
1425 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1426 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1427 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1430 return parseDirectiveComm(/*IsLocal=*/false);
1432 return parseDirectiveComm(/*IsLocal=*/true);
1434 return parseDirectiveAbort();
1436 return parseDirectiveInclude();
1438 return parseDirectiveIncbin();
1441 return TokError(Twine(IDVal) + " not supported yet");
1443 return parseDirectiveRept(IDLoc, IDVal);
1445 return parseDirectiveIrp(IDLoc);
1447 return parseDirectiveIrpc(IDLoc);
1449 return parseDirectiveEndr(IDLoc);
1450 case DK_BUNDLE_ALIGN_MODE:
1451 return parseDirectiveBundleAlignMode();
1452 case DK_BUNDLE_LOCK:
1453 return parseDirectiveBundleLock();
1454 case DK_BUNDLE_UNLOCK:
1455 return parseDirectiveBundleUnlock();
1457 return parseDirectiveLEB128(true);
1459 return parseDirectiveLEB128(false);
1462 return parseDirectiveSpace(IDVal);
1464 return parseDirectiveFile(IDLoc);
1466 return parseDirectiveLine();
1468 return parseDirectiveLoc();
1470 return parseDirectiveStabs();
1471 case DK_CFI_SECTIONS:
1472 return parseDirectiveCFISections();
1473 case DK_CFI_STARTPROC:
1474 return parseDirectiveCFIStartProc();
1475 case DK_CFI_ENDPROC:
1476 return parseDirectiveCFIEndProc();
1477 case DK_CFI_DEF_CFA:
1478 return parseDirectiveCFIDefCfa(IDLoc);
1479 case DK_CFI_DEF_CFA_OFFSET:
1480 return parseDirectiveCFIDefCfaOffset();
1481 case DK_CFI_ADJUST_CFA_OFFSET:
1482 return parseDirectiveCFIAdjustCfaOffset();
1483 case DK_CFI_DEF_CFA_REGISTER:
1484 return parseDirectiveCFIDefCfaRegister(IDLoc);
1486 return parseDirectiveCFIOffset(IDLoc);
1487 case DK_CFI_REL_OFFSET:
1488 return parseDirectiveCFIRelOffset(IDLoc);
1489 case DK_CFI_PERSONALITY:
1490 return parseDirectiveCFIPersonalityOrLsda(true);
1492 return parseDirectiveCFIPersonalityOrLsda(false);
1493 case DK_CFI_REMEMBER_STATE:
1494 return parseDirectiveCFIRememberState();
1495 case DK_CFI_RESTORE_STATE:
1496 return parseDirectiveCFIRestoreState();
1497 case DK_CFI_SAME_VALUE:
1498 return parseDirectiveCFISameValue(IDLoc);
1499 case DK_CFI_RESTORE:
1500 return parseDirectiveCFIRestore(IDLoc);
1502 return parseDirectiveCFIEscape();
1503 case DK_CFI_SIGNAL_FRAME:
1504 return parseDirectiveCFISignalFrame();
1505 case DK_CFI_UNDEFINED:
1506 return parseDirectiveCFIUndefined(IDLoc);
1507 case DK_CFI_REGISTER:
1508 return parseDirectiveCFIRegister(IDLoc);
1509 case DK_CFI_WINDOW_SAVE:
1510 return parseDirectiveCFIWindowSave();
1513 return parseDirectiveMacrosOnOff(IDVal);
1515 return parseDirectiveMacro(IDLoc);
1518 return parseDirectiveEndMacro(IDVal);
1520 return parseDirectivePurgeMacro(IDLoc);
1522 return parseDirectiveEnd(IDLoc);
1525 return Error(IDLoc, "unknown directive");
1528 // __asm _emit or __asm __emit
1529 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1530 IDVal == "_EMIT" || IDVal == "__EMIT"))
1531 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1534 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1535 return parseDirectiveMSAlign(IDLoc, Info);
1537 checkForValidSection();
1539 // Canonicalize the opcode to lower case.
1540 std::string OpcodeStr = IDVal.lower();
1541 ParseInstructionInfo IInfo(Info.AsmRewrites);
1542 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1543 Info.ParsedOperands);
1544 Info.ParseError = HadError;
1546 // Dump the parsed representation, if requested.
1547 if (getShowParsedOperands()) {
1548 SmallString<256> Str;
1549 raw_svector_ostream OS(Str);
1550 OS << "parsed instruction: [";
1551 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1554 Info.ParsedOperands[i]->print(OS);
1558 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1561 // If we are generating dwarf for assembly source files and the current
1562 // section is the initial text section then generate a .loc directive for
1564 if (!HadError && getContext().getGenDwarfForAssembly() &&
1565 getContext().getGenDwarfSection() ==
1566 getStreamer().getCurrentSection().first) {
1568 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1570 // If we previously parsed a cpp hash file line comment then make sure the
1571 // current Dwarf File is for the CppHashFilename if not then emit the
1572 // Dwarf File table for it and adjust the line number for the .loc.
1573 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1574 getContext().getMCDwarfFiles();
1575 if (CppHashFilename.size() != 0) {
1576 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1578 getStreamer().EmitDwarfFileDirective(
1579 getContext().nextGenDwarfFileNumber(), StringRef(),
1582 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1583 // cache with the different Loc from the call above we save the last
1584 // info we queried here with SrcMgr.FindLineNumber().
1585 unsigned CppHashLocLineNo;
1586 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1587 CppHashLocLineNo = LastQueryLine;
1589 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1590 LastQueryLine = CppHashLocLineNo;
1591 LastQueryIDLoc = CppHashLoc;
1592 LastQueryBuffer = CppHashBuf;
1594 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1597 getStreamer().EmitDwarfLocDirective(
1598 getContext().getGenDwarfFileNumber(), Line, 0,
1599 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1603 // If parsing succeeded, match the instruction.
1606 HadError = getTargetParser().MatchAndEmitInstruction(
1607 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1611 // Don't skip the rest of the line, the instruction parser is responsible for
1616 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1617 /// since they may not be able to be tokenized to get to the end of line token.
1618 void AsmParser::eatToEndOfLine() {
1619 if (!Lexer.is(AsmToken::EndOfStatement))
1620 Lexer.LexUntilEndOfLine();
1625 /// parseCppHashLineFilenameComment as this:
1626 /// ::= # number "filename"
1627 /// or just as a full line comment if it doesn't have a number and a string.
1628 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1629 Lex(); // Eat the hash token.
1631 if (getLexer().isNot(AsmToken::Integer)) {
1632 // Consume the line since in cases it is not a well-formed line directive,
1633 // as if were simply a full line comment.
1638 int64_t LineNumber = getTok().getIntVal();
1641 if (getLexer().isNot(AsmToken::String)) {
1646 StringRef Filename = getTok().getString();
1647 // Get rid of the enclosing quotes.
1648 Filename = Filename.substr(1, Filename.size() - 2);
1650 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1652 CppHashFilename = Filename;
1653 CppHashLineNumber = LineNumber;
1654 CppHashBuf = CurBuffer;
1656 // Ignore any trailing characters, they're just comment.
1661 /// \brief will use the last parsed cpp hash line filename comment
1662 /// for the Filename and LineNo if any in the diagnostic.
1663 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1664 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1665 raw_ostream &OS = errs();
1667 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1668 const SMLoc &DiagLoc = Diag.getLoc();
1669 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1670 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1672 // Like SourceMgr::printMessage() we need to print the include stack if any
1673 // before printing the message.
1674 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1675 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1676 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1677 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1680 // If we have not parsed a cpp hash line filename comment or the source
1681 // manager changed or buffer changed (like in a nested include) then just
1682 // print the normal diagnostic using its Filename and LineNo.
1683 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1684 DiagBuf != CppHashBuf) {
1685 if (Parser->SavedDiagHandler)
1686 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1692 // Use the CppHashFilename and calculate a line number based on the
1693 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1695 const std::string &Filename = Parser->CppHashFilename;
1697 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1698 int CppHashLocLineNo =
1699 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1701 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1703 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1704 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1705 Diag.getLineContents(), Diag.getRanges());
1707 if (Parser->SavedDiagHandler)
1708 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1710 NewDiag.print(0, OS);
1713 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1714 // difference being that that function accepts '@' as part of identifiers and
1715 // we can't do that. AsmLexer.cpp should probably be changed to handle
1716 // '@' as a special case when needed.
1717 static bool isIdentifierChar(char c) {
1718 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1722 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1723 ArrayRef<MCAsmMacroParameter> Parameters,
1724 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1725 unsigned NParameters = Parameters.size();
1726 if (NParameters != 0 && NParameters != A.size())
1727 return Error(L, "Wrong number of arguments");
1729 // A macro without parameters is handled differently on Darwin:
1730 // gas accepts no arguments and does no substitutions
1731 while (!Body.empty()) {
1732 // Scan for the next substitution.
1733 std::size_t End = Body.size(), Pos = 0;
1734 for (; Pos != End; ++Pos) {
1735 // Check for a substitution or escape.
1737 // This macro has no parameters, look for $0, $1, etc.
1738 if (Body[Pos] != '$' || Pos + 1 == End)
1741 char Next = Body[Pos + 1];
1742 if (Next == '$' || Next == 'n' ||
1743 isdigit(static_cast<unsigned char>(Next)))
1746 // This macro has parameters, look for \foo, \bar, etc.
1747 if (Body[Pos] == '\\' && Pos + 1 != End)
1753 OS << Body.slice(0, Pos);
1755 // Check if we reached the end.
1760 switch (Body[Pos + 1]) {
1766 // $n => number of arguments
1771 // $[0-9] => argument
1773 // Missing arguments are ignored.
1774 unsigned Index = Body[Pos + 1] - '0';
1775 if (Index >= A.size())
1778 // Otherwise substitute with the token values, with spaces eliminated.
1779 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1780 ie = A[Index].end();
1782 OS << it->getString();
1788 unsigned I = Pos + 1;
1789 while (isIdentifierChar(Body[I]) && I + 1 != End)
1792 const char *Begin = Body.data() + Pos + 1;
1793 StringRef Argument(Begin, I - (Pos + 1));
1795 for (; Index < NParameters; ++Index)
1796 if (Parameters[Index].first == Argument)
1799 if (Index == NParameters) {
1800 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1803 OS << '\\' << Argument;
1807 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1808 ie = A[Index].end();
1810 if (it->getKind() == AsmToken::String)
1811 OS << it->getStringContents();
1813 OS << it->getString();
1815 Pos += 1 + Argument.size();
1818 // Update the scan point.
1819 Body = Body.substr(Pos);
1825 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1826 SMLoc EL, MemoryBuffer *I)
1827 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1830 static bool isOperator(AsmToken::TokenKind kind) {
1834 case AsmToken::Plus:
1835 case AsmToken::Minus:
1836 case AsmToken::Tilde:
1837 case AsmToken::Slash:
1838 case AsmToken::Star:
1840 case AsmToken::Equal:
1841 case AsmToken::EqualEqual:
1842 case AsmToken::Pipe:
1843 case AsmToken::PipePipe:
1844 case AsmToken::Caret:
1846 case AsmToken::AmpAmp:
1847 case AsmToken::Exclaim:
1848 case AsmToken::ExclaimEqual:
1849 case AsmToken::Percent:
1850 case AsmToken::Less:
1851 case AsmToken::LessEqual:
1852 case AsmToken::LessLess:
1853 case AsmToken::LessGreater:
1854 case AsmToken::Greater:
1855 case AsmToken::GreaterEqual:
1856 case AsmToken::GreaterGreater:
1862 class AsmLexerSkipSpaceRAII {
1864 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1865 Lexer.setSkipSpace(SkipSpace);
1868 ~AsmLexerSkipSpaceRAII() {
1869 Lexer.setSkipSpace(true);
1877 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA) {
1878 unsigned ParenLevel = 0;
1879 unsigned AddTokens = 0;
1881 // Darwin doesn't use spaces to delmit arguments.
1882 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1885 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1886 return TokError("unexpected token in macro instantiation");
1888 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1891 if (Lexer.is(AsmToken::Space)) {
1892 Lex(); // Eat spaces
1894 // Spaces can delimit parameters, but could also be part an expression.
1895 // If the token after a space is an operator, add the token and the next
1896 // one into this argument
1898 if (isOperator(Lexer.getKind())) {
1899 // Check to see whether the token is used as an operator,
1900 // or part of an identifier
1901 const char *NextChar = getTok().getEndLoc().getPointer();
1902 if (*NextChar == ' ')
1906 if (!AddTokens && ParenLevel == 0) {
1912 // handleMacroEntry relies on not advancing the lexer here
1913 // to be able to fill in the remaining default parameter values
1914 if (Lexer.is(AsmToken::EndOfStatement))
1917 // Adjust the current parentheses level.
1918 if (Lexer.is(AsmToken::LParen))
1920 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1923 // Append the token to the current argument list.
1924 MA.push_back(getTok());
1930 if (ParenLevel != 0)
1931 return TokError("unbalanced parentheses in macro argument");
1935 // Parse the macro instantiation arguments.
1936 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1937 MCAsmMacroArguments &A) {
1938 const unsigned NParameters = M ? M->Parameters.size() : 0;
1940 // Parse two kinds of macro invocations:
1941 // - macros defined without any parameters accept an arbitrary number of them
1942 // - macros defined with parameters accept at most that many of them
1943 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1945 MCAsmMacroArgument MA;
1947 if (parseMacroArgument(MA))
1950 if (!MA.empty() || (!NParameters && !Lexer.is(AsmToken::EndOfStatement)))
1952 else if (NParameters) {
1953 if (!M->Parameters[Parameter].second.empty())
1954 A.push_back(M->Parameters[Parameter].second);
1959 // At the end of the statement, fill in remaining arguments that have
1960 // default values. If there aren't any, then the next argument is
1961 // required but missing
1962 if (Lexer.is(AsmToken::EndOfStatement)) {
1963 if (NParameters && Parameter < NParameters - 1) {
1969 if (Lexer.is(AsmToken::Comma))
1972 return TokError("Too many arguments");
1975 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
1976 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1977 return (I == MacroMap.end()) ? NULL : I->getValue();
1980 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
1981 MacroMap[Name] = new MCAsmMacro(Macro);
1984 void AsmParser::undefineMacro(StringRef Name) {
1985 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1986 if (I != MacroMap.end()) {
1987 delete I->getValue();
1992 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1993 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1994 // this, although we should protect against infinite loops.
1995 if (ActiveMacros.size() == 20)
1996 return TokError("macros cannot be nested more than 20 levels deep");
1998 MCAsmMacroArguments A;
1999 if (parseMacroArguments(M, A))
2002 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2003 // to hold the macro body with substitutions.
2004 SmallString<256> Buf;
2005 StringRef Body = M->Body;
2006 raw_svector_ostream OS(Buf);
2008 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2011 // We include the .endmacro in the buffer as our cue to exit the macro
2013 OS << ".endmacro\n";
2015 MemoryBuffer *Instantiation =
2016 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2018 // Create the macro instantiation object and add to the current macro
2019 // instantiation stack.
2020 MacroInstantiation *MI = new MacroInstantiation(
2021 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2022 ActiveMacros.push_back(MI);
2024 // Jump to the macro instantiation and prime the lexer.
2025 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2026 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2032 void AsmParser::handleMacroExit() {
2033 // Jump to the EndOfStatement we should return to, and consume it.
2034 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2037 // Pop the instantiation entry.
2038 delete ActiveMacros.back();
2039 ActiveMacros.pop_back();
2042 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2043 switch (Value->getKind()) {
2044 case MCExpr::Binary: {
2045 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2046 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2048 case MCExpr::Target:
2049 case MCExpr::Constant:
2051 case MCExpr::SymbolRef: {
2053 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2055 return isUsedIn(Sym, S.getVariableValue());
2059 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2062 llvm_unreachable("Unknown expr kind!");
2065 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2067 // FIXME: Use better location, we should use proper tokens.
2068 SMLoc EqualLoc = Lexer.getLoc();
2070 const MCExpr *Value;
2071 if (parseExpression(Value))
2074 // Note: we don't count b as used in "a = b". This is to allow
2078 if (Lexer.isNot(AsmToken::EndOfStatement))
2079 return TokError("unexpected token in assignment");
2081 // Error on assignment to '.'.
2083 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2084 "(use '.space' or '.org').)"));
2087 // Eat the end of statement marker.
2090 // Validate that the LHS is allowed to be a variable (either it has not been
2091 // used as a symbol, or it is an absolute symbol).
2092 MCSymbol *Sym = getContext().LookupSymbol(Name);
2094 // Diagnose assignment to a label.
2096 // FIXME: Diagnostics. Note the location of the definition as a label.
2097 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2098 if (isUsedIn(Sym, Value))
2099 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2100 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2101 ; // Allow redefinitions of undefined symbols only used in directives.
2102 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2103 ; // Allow redefinitions of variables that haven't yet been used.
2104 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2105 return Error(EqualLoc, "redefinition of '" + Name + "'");
2106 else if (!Sym->isVariable())
2107 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2108 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2109 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2112 // Don't count these checks as uses.
2113 Sym->setUsed(false);
2115 Sym = getContext().GetOrCreateSymbol(Name);
2117 // FIXME: Handle '.'.
2119 // Do the assignment.
2120 Out.EmitAssignment(Sym, Value);
2122 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2127 /// parseIdentifier:
2130 bool AsmParser::parseIdentifier(StringRef &Res) {
2131 // The assembler has relaxed rules for accepting identifiers, in particular we
2132 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2133 // separate tokens. At this level, we have already lexed so we cannot (currently)
2134 // handle this as a context dependent token, instead we detect adjacent tokens
2135 // and return the combined identifier.
2136 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2137 SMLoc PrefixLoc = getLexer().getLoc();
2139 // Consume the prefix character, and check for a following identifier.
2141 if (Lexer.isNot(AsmToken::Identifier))
2144 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2145 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2148 // Construct the joined identifier and consume the token.
2150 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2155 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2158 Res = getTok().getIdentifier();
2160 Lex(); // Consume the identifier token.
2165 /// parseDirectiveSet:
2166 /// ::= .equ identifier ',' expression
2167 /// ::= .equiv identifier ',' expression
2168 /// ::= .set identifier ',' expression
2169 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2172 if (parseIdentifier(Name))
2173 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2175 if (getLexer().isNot(AsmToken::Comma))
2176 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2179 return parseAssignment(Name, allow_redef, true);
2182 bool AsmParser::parseEscapedString(std::string &Data) {
2183 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2186 StringRef Str = getTok().getStringContents();
2187 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2188 if (Str[i] != '\\') {
2193 // Recognize escaped characters. Note that this escape semantics currently
2194 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2197 return TokError("unexpected backslash at end of string");
2199 // Recognize octal sequences.
2200 if ((unsigned)(Str[i] - '0') <= 7) {
2201 // Consume up to three octal characters.
2202 unsigned Value = Str[i] - '0';
2204 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2206 Value = Value * 8 + (Str[i] - '0');
2208 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2210 Value = Value * 8 + (Str[i] - '0');
2215 return TokError("invalid octal escape sequence (out of range)");
2217 Data += (unsigned char)Value;
2221 // Otherwise recognize individual escapes.
2224 // Just reject invalid escape sequences for now.
2225 return TokError("invalid escape sequence (unrecognized character)");
2227 case 'b': Data += '\b'; break;
2228 case 'f': Data += '\f'; break;
2229 case 'n': Data += '\n'; break;
2230 case 'r': Data += '\r'; break;
2231 case 't': Data += '\t'; break;
2232 case '"': Data += '"'; break;
2233 case '\\': Data += '\\'; break;
2240 /// parseDirectiveAscii:
2241 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2242 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2243 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2244 checkForValidSection();
2247 if (getLexer().isNot(AsmToken::String))
2248 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2251 if (parseEscapedString(Data))
2254 getStreamer().EmitBytes(Data);
2256 getStreamer().EmitBytes(StringRef("\0", 1));
2260 if (getLexer().is(AsmToken::EndOfStatement))
2263 if (getLexer().isNot(AsmToken::Comma))
2264 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2273 /// parseDirectiveValue
2274 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2275 bool AsmParser::parseDirectiveValue(unsigned Size) {
2276 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2277 checkForValidSection();
2280 const MCExpr *Value;
2281 SMLoc ExprLoc = getLexer().getLoc();
2282 if (parseExpression(Value))
2285 // Special case constant expressions to match code generator.
2286 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2287 assert(Size <= 8 && "Invalid size");
2288 uint64_t IntValue = MCE->getValue();
2289 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2290 return Error(ExprLoc, "literal value out of range for directive");
2291 getStreamer().EmitIntValue(IntValue, Size);
2293 getStreamer().EmitValue(Value, Size);
2295 if (getLexer().is(AsmToken::EndOfStatement))
2298 // FIXME: Improve diagnostic.
2299 if (getLexer().isNot(AsmToken::Comma))
2300 return TokError("unexpected token in directive");
2309 /// ParseDirectiveOctaValue
2310 /// ::= .octa [ hexconstant (, hexconstant)* ]
2311 bool AsmParser::parseDirectiveOctaValue() {
2312 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2313 checkForValidSection();
2316 if (Lexer.getKind() == AsmToken::Error)
2318 if (Lexer.getKind() != AsmToken::Integer &&
2319 Lexer.getKind() != AsmToken::BigNum)
2320 return TokError("unknown token in expression");
2322 SMLoc ExprLoc = getLexer().getLoc();
2323 APInt IntValue = getTok().getAPIntVal();
2327 if (IntValue.isIntN(64)) {
2329 lo = IntValue.getZExtValue();
2330 } else if (IntValue.isIntN(128)) {
2331 // It might actually have more than 128 bits, but the top ones are zero.
2332 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2333 lo = IntValue.getLoBits(64).getZExtValue();
2335 return Error(ExprLoc, "literal value out of range for directive");
2337 if (MAI.isLittleEndian()) {
2338 getStreamer().EmitIntValue(lo, 8);
2339 getStreamer().EmitIntValue(hi, 8);
2341 getStreamer().EmitIntValue(hi, 8);
2342 getStreamer().EmitIntValue(lo, 8);
2345 if (getLexer().is(AsmToken::EndOfStatement))
2348 // FIXME: Improve diagnostic.
2349 if (getLexer().isNot(AsmToken::Comma))
2350 return TokError("unexpected token in directive");
2359 /// parseDirectiveRealValue
2360 /// ::= (.single | .double) [ expression (, expression)* ]
2361 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2362 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2363 checkForValidSection();
2366 // We don't truly support arithmetic on floating point expressions, so we
2367 // have to manually parse unary prefixes.
2369 if (getLexer().is(AsmToken::Minus)) {
2372 } else if (getLexer().is(AsmToken::Plus))
2375 if (getLexer().isNot(AsmToken::Integer) &&
2376 getLexer().isNot(AsmToken::Real) &&
2377 getLexer().isNot(AsmToken::Identifier))
2378 return TokError("unexpected token in directive");
2380 // Convert to an APFloat.
2381 APFloat Value(Semantics);
2382 StringRef IDVal = getTok().getString();
2383 if (getLexer().is(AsmToken::Identifier)) {
2384 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2385 Value = APFloat::getInf(Semantics);
2386 else if (!IDVal.compare_lower("nan"))
2387 Value = APFloat::getNaN(Semantics, false, ~0);
2389 return TokError("invalid floating point literal");
2390 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2391 APFloat::opInvalidOp)
2392 return TokError("invalid floating point literal");
2396 // Consume the numeric token.
2399 // Emit the value as an integer.
2400 APInt AsInt = Value.bitcastToAPInt();
2401 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2402 AsInt.getBitWidth() / 8);
2404 if (getLexer().is(AsmToken::EndOfStatement))
2407 if (getLexer().isNot(AsmToken::Comma))
2408 return TokError("unexpected token in directive");
2417 /// parseDirectiveZero
2418 /// ::= .zero expression
2419 bool AsmParser::parseDirectiveZero() {
2420 checkForValidSection();
2423 if (parseAbsoluteExpression(NumBytes))
2427 if (getLexer().is(AsmToken::Comma)) {
2429 if (parseAbsoluteExpression(Val))
2433 if (getLexer().isNot(AsmToken::EndOfStatement))
2434 return TokError("unexpected token in '.zero' directive");
2438 getStreamer().EmitFill(NumBytes, Val);
2443 /// parseDirectiveFill
2444 /// ::= .fill expression [ , expression [ , expression ] ]
2445 bool AsmParser::parseDirectiveFill() {
2446 checkForValidSection();
2448 SMLoc RepeatLoc = getLexer().getLoc();
2450 if (parseAbsoluteExpression(NumValues))
2453 if (NumValues < 0) {
2455 "'.fill' directive with negative repeat count has no effect");
2459 int64_t FillSize = 1;
2460 int64_t FillExpr = 0;
2462 SMLoc SizeLoc, ExprLoc;
2463 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2464 if (getLexer().isNot(AsmToken::Comma))
2465 return TokError("unexpected token in '.fill' directive");
2468 SizeLoc = getLexer().getLoc();
2469 if (parseAbsoluteExpression(FillSize))
2472 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2473 if (getLexer().isNot(AsmToken::Comma))
2474 return TokError("unexpected token in '.fill' directive");
2477 ExprLoc = getLexer().getLoc();
2478 if (parseAbsoluteExpression(FillExpr))
2481 if (getLexer().isNot(AsmToken::EndOfStatement))
2482 return TokError("unexpected token in '.fill' directive");
2489 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2493 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2497 if (!isUInt<32>(FillExpr) && FillSize > 4)
2498 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2500 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2501 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2503 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2504 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2505 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2511 /// parseDirectiveOrg
2512 /// ::= .org expression [ , expression ]
2513 bool AsmParser::parseDirectiveOrg() {
2514 checkForValidSection();
2516 const MCExpr *Offset;
2517 SMLoc Loc = getTok().getLoc();
2518 if (parseExpression(Offset))
2521 // Parse optional fill expression.
2522 int64_t FillExpr = 0;
2523 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2524 if (getLexer().isNot(AsmToken::Comma))
2525 return TokError("unexpected token in '.org' directive");
2528 if (parseAbsoluteExpression(FillExpr))
2531 if (getLexer().isNot(AsmToken::EndOfStatement))
2532 return TokError("unexpected token in '.org' directive");
2537 // Only limited forms of relocatable expressions are accepted here, it
2538 // has to be relative to the current section. The streamer will return
2539 // 'true' if the expression wasn't evaluatable.
2540 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2541 return Error(Loc, "expected assembly-time absolute expression");
2546 /// parseDirectiveAlign
2547 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2548 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2549 checkForValidSection();
2551 SMLoc AlignmentLoc = getLexer().getLoc();
2553 if (parseAbsoluteExpression(Alignment))
2557 bool HasFillExpr = false;
2558 int64_t FillExpr = 0;
2559 int64_t MaxBytesToFill = 0;
2560 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2561 if (getLexer().isNot(AsmToken::Comma))
2562 return TokError("unexpected token in directive");
2565 // The fill expression can be omitted while specifying a maximum number of
2566 // alignment bytes, e.g:
2568 if (getLexer().isNot(AsmToken::Comma)) {
2570 if (parseAbsoluteExpression(FillExpr))
2574 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2575 if (getLexer().isNot(AsmToken::Comma))
2576 return TokError("unexpected token in directive");
2579 MaxBytesLoc = getLexer().getLoc();
2580 if (parseAbsoluteExpression(MaxBytesToFill))
2583 if (getLexer().isNot(AsmToken::EndOfStatement))
2584 return TokError("unexpected token in directive");
2593 // Compute alignment in bytes.
2595 // FIXME: Diagnose overflow.
2596 if (Alignment >= 32) {
2597 Error(AlignmentLoc, "invalid alignment value");
2601 Alignment = 1ULL << Alignment;
2603 // Reject alignments that aren't a power of two, for gas compatibility.
2604 if (!isPowerOf2_64(Alignment))
2605 Error(AlignmentLoc, "alignment must be a power of 2");
2608 // Diagnose non-sensical max bytes to align.
2609 if (MaxBytesLoc.isValid()) {
2610 if (MaxBytesToFill < 1) {
2611 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2612 "many bytes, ignoring maximum bytes expression");
2616 if (MaxBytesToFill >= Alignment) {
2617 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2623 // Check whether we should use optimal code alignment for this .align
2625 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2626 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2627 ValueSize == 1 && UseCodeAlign) {
2628 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2630 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2631 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2638 /// parseDirectiveFile
2639 /// ::= .file [number] filename
2640 /// ::= .file number directory filename
2641 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2642 // FIXME: I'm not sure what this is.
2643 int64_t FileNumber = -1;
2644 SMLoc FileNumberLoc = getLexer().getLoc();
2645 if (getLexer().is(AsmToken::Integer)) {
2646 FileNumber = getTok().getIntVal();
2650 return TokError("file number less than one");
2653 if (getLexer().isNot(AsmToken::String))
2654 return TokError("unexpected token in '.file' directive");
2656 // Usually the directory and filename together, otherwise just the directory.
2657 // Allow the strings to have escaped octal character sequence.
2658 std::string Path = getTok().getString();
2659 if (parseEscapedString(Path))
2663 StringRef Directory;
2665 std::string FilenameData;
2666 if (getLexer().is(AsmToken::String)) {
2667 if (FileNumber == -1)
2668 return TokError("explicit path specified, but no file number");
2669 if (parseEscapedString(FilenameData))
2671 Filename = FilenameData;
2678 if (getLexer().isNot(AsmToken::EndOfStatement))
2679 return TokError("unexpected token in '.file' directive");
2681 if (FileNumber == -1)
2682 getStreamer().EmitFileDirective(Filename);
2684 if (getContext().getGenDwarfForAssembly() == true)
2686 "input can't have .file dwarf directives when -g is "
2687 "used to generate dwarf debug info for assembly code");
2689 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2690 Error(FileNumberLoc, "file number already allocated");
2696 /// parseDirectiveLine
2697 /// ::= .line [number]
2698 bool AsmParser::parseDirectiveLine() {
2699 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2700 if (getLexer().isNot(AsmToken::Integer))
2701 return TokError("unexpected token in '.line' directive");
2703 int64_t LineNumber = getTok().getIntVal();
2707 // FIXME: Do something with the .line.
2710 if (getLexer().isNot(AsmToken::EndOfStatement))
2711 return TokError("unexpected token in '.line' directive");
2716 /// parseDirectiveLoc
2717 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2718 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2719 /// The first number is a file number, must have been previously assigned with
2720 /// a .file directive, the second number is the line number and optionally the
2721 /// third number is a column position (zero if not specified). The remaining
2722 /// optional items are .loc sub-directives.
2723 bool AsmParser::parseDirectiveLoc() {
2724 if (getLexer().isNot(AsmToken::Integer))
2725 return TokError("unexpected token in '.loc' directive");
2726 int64_t FileNumber = getTok().getIntVal();
2728 return TokError("file number less than one in '.loc' directive");
2729 if (!getContext().isValidDwarfFileNumber(FileNumber))
2730 return TokError("unassigned file number in '.loc' directive");
2733 int64_t LineNumber = 0;
2734 if (getLexer().is(AsmToken::Integer)) {
2735 LineNumber = getTok().getIntVal();
2737 return TokError("line number less than zero in '.loc' directive");
2741 int64_t ColumnPos = 0;
2742 if (getLexer().is(AsmToken::Integer)) {
2743 ColumnPos = getTok().getIntVal();
2745 return TokError("column position less than zero in '.loc' directive");
2749 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2751 int64_t Discriminator = 0;
2752 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2754 if (getLexer().is(AsmToken::EndOfStatement))
2758 SMLoc Loc = getTok().getLoc();
2759 if (parseIdentifier(Name))
2760 return TokError("unexpected token in '.loc' directive");
2762 if (Name == "basic_block")
2763 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2764 else if (Name == "prologue_end")
2765 Flags |= DWARF2_FLAG_PROLOGUE_END;
2766 else if (Name == "epilogue_begin")
2767 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2768 else if (Name == "is_stmt") {
2769 Loc = getTok().getLoc();
2770 const MCExpr *Value;
2771 if (parseExpression(Value))
2773 // The expression must be the constant 0 or 1.
2774 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2775 int Value = MCE->getValue();
2777 Flags &= ~DWARF2_FLAG_IS_STMT;
2778 else if (Value == 1)
2779 Flags |= DWARF2_FLAG_IS_STMT;
2781 return Error(Loc, "is_stmt value not 0 or 1");
2783 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2785 } else if (Name == "isa") {
2786 Loc = getTok().getLoc();
2787 const MCExpr *Value;
2788 if (parseExpression(Value))
2790 // The expression must be a constant greater or equal to 0.
2791 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2792 int Value = MCE->getValue();
2794 return Error(Loc, "isa number less than zero");
2797 return Error(Loc, "isa number not a constant value");
2799 } else if (Name == "discriminator") {
2800 if (parseAbsoluteExpression(Discriminator))
2803 return Error(Loc, "unknown sub-directive in '.loc' directive");
2806 if (getLexer().is(AsmToken::EndOfStatement))
2811 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2812 Isa, Discriminator, StringRef());
2817 /// parseDirectiveStabs
2818 /// ::= .stabs string, number, number, number
2819 bool AsmParser::parseDirectiveStabs() {
2820 return TokError("unsupported directive '.stabs'");
2823 /// parseDirectiveCFISections
2824 /// ::= .cfi_sections section [, section]
2825 bool AsmParser::parseDirectiveCFISections() {
2830 if (parseIdentifier(Name))
2831 return TokError("Expected an identifier");
2833 if (Name == ".eh_frame")
2835 else if (Name == ".debug_frame")
2838 if (getLexer().is(AsmToken::Comma)) {
2841 if (parseIdentifier(Name))
2842 return TokError("Expected an identifier");
2844 if (Name == ".eh_frame")
2846 else if (Name == ".debug_frame")
2850 getStreamer().EmitCFISections(EH, Debug);
2854 /// parseDirectiveCFIStartProc
2855 /// ::= .cfi_startproc [simple]
2856 bool AsmParser::parseDirectiveCFIStartProc() {
2858 if (getLexer().isNot(AsmToken::EndOfStatement))
2859 if (parseIdentifier(Simple) || Simple != "simple")
2860 return TokError("unexpected token in .cfi_startproc directive");
2862 getStreamer().EmitCFIStartProc(!Simple.empty());
2866 /// parseDirectiveCFIEndProc
2867 /// ::= .cfi_endproc
2868 bool AsmParser::parseDirectiveCFIEndProc() {
2869 getStreamer().EmitCFIEndProc();
2873 /// \brief parse register name or number.
2874 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2875 SMLoc DirectiveLoc) {
2878 if (getLexer().isNot(AsmToken::Integer)) {
2879 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2881 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2883 return parseAbsoluteExpression(Register);
2888 /// parseDirectiveCFIDefCfa
2889 /// ::= .cfi_def_cfa register, offset
2890 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2891 int64_t Register = 0;
2892 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2895 if (getLexer().isNot(AsmToken::Comma))
2896 return TokError("unexpected token in directive");
2900 if (parseAbsoluteExpression(Offset))
2903 getStreamer().EmitCFIDefCfa(Register, Offset);
2907 /// parseDirectiveCFIDefCfaOffset
2908 /// ::= .cfi_def_cfa_offset offset
2909 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2911 if (parseAbsoluteExpression(Offset))
2914 getStreamer().EmitCFIDefCfaOffset(Offset);
2918 /// parseDirectiveCFIRegister
2919 /// ::= .cfi_register register, register
2920 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2921 int64_t Register1 = 0;
2922 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2925 if (getLexer().isNot(AsmToken::Comma))
2926 return TokError("unexpected token in directive");
2929 int64_t Register2 = 0;
2930 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2933 getStreamer().EmitCFIRegister(Register1, Register2);
2937 /// parseDirectiveCFIWindowSave
2938 /// ::= .cfi_window_save
2939 bool AsmParser::parseDirectiveCFIWindowSave() {
2940 getStreamer().EmitCFIWindowSave();
2944 /// parseDirectiveCFIAdjustCfaOffset
2945 /// ::= .cfi_adjust_cfa_offset adjustment
2946 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2947 int64_t Adjustment = 0;
2948 if (parseAbsoluteExpression(Adjustment))
2951 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2955 /// parseDirectiveCFIDefCfaRegister
2956 /// ::= .cfi_def_cfa_register register
2957 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2958 int64_t Register = 0;
2959 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2962 getStreamer().EmitCFIDefCfaRegister(Register);
2966 /// parseDirectiveCFIOffset
2967 /// ::= .cfi_offset register, offset
2968 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2969 int64_t Register = 0;
2972 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2975 if (getLexer().isNot(AsmToken::Comma))
2976 return TokError("unexpected token in directive");
2979 if (parseAbsoluteExpression(Offset))
2982 getStreamer().EmitCFIOffset(Register, Offset);
2986 /// parseDirectiveCFIRelOffset
2987 /// ::= .cfi_rel_offset register, offset
2988 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2989 int64_t Register = 0;
2991 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2994 if (getLexer().isNot(AsmToken::Comma))
2995 return TokError("unexpected token in directive");
2999 if (parseAbsoluteExpression(Offset))
3002 getStreamer().EmitCFIRelOffset(Register, Offset);
3006 static bool isValidEncoding(int64_t Encoding) {
3007 if (Encoding & ~0xff)
3010 if (Encoding == dwarf::DW_EH_PE_omit)
3013 const unsigned Format = Encoding & 0xf;
3014 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3015 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3016 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3017 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3020 const unsigned Application = Encoding & 0x70;
3021 if (Application != dwarf::DW_EH_PE_absptr &&
3022 Application != dwarf::DW_EH_PE_pcrel)
3028 /// parseDirectiveCFIPersonalityOrLsda
3029 /// IsPersonality true for cfi_personality, false for cfi_lsda
3030 /// ::= .cfi_personality encoding, [symbol_name]
3031 /// ::= .cfi_lsda encoding, [symbol_name]
3032 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3033 int64_t Encoding = 0;
3034 if (parseAbsoluteExpression(Encoding))
3036 if (Encoding == dwarf::DW_EH_PE_omit)
3039 if (!isValidEncoding(Encoding))
3040 return TokError("unsupported encoding.");
3042 if (getLexer().isNot(AsmToken::Comma))
3043 return TokError("unexpected token in directive");
3047 if (parseIdentifier(Name))
3048 return TokError("expected identifier in directive");
3050 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3053 getStreamer().EmitCFIPersonality(Sym, Encoding);
3055 getStreamer().EmitCFILsda(Sym, Encoding);
3059 /// parseDirectiveCFIRememberState
3060 /// ::= .cfi_remember_state
3061 bool AsmParser::parseDirectiveCFIRememberState() {
3062 getStreamer().EmitCFIRememberState();
3066 /// parseDirectiveCFIRestoreState
3067 /// ::= .cfi_remember_state
3068 bool AsmParser::parseDirectiveCFIRestoreState() {
3069 getStreamer().EmitCFIRestoreState();
3073 /// parseDirectiveCFISameValue
3074 /// ::= .cfi_same_value register
3075 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3076 int64_t Register = 0;
3078 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3081 getStreamer().EmitCFISameValue(Register);
3085 /// parseDirectiveCFIRestore
3086 /// ::= .cfi_restore register
3087 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3088 int64_t Register = 0;
3089 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3092 getStreamer().EmitCFIRestore(Register);
3096 /// parseDirectiveCFIEscape
3097 /// ::= .cfi_escape expression[,...]
3098 bool AsmParser::parseDirectiveCFIEscape() {
3101 if (parseAbsoluteExpression(CurrValue))
3104 Values.push_back((uint8_t)CurrValue);
3106 while (getLexer().is(AsmToken::Comma)) {
3109 if (parseAbsoluteExpression(CurrValue))
3112 Values.push_back((uint8_t)CurrValue);
3115 getStreamer().EmitCFIEscape(Values);
3119 /// parseDirectiveCFISignalFrame
3120 /// ::= .cfi_signal_frame
3121 bool AsmParser::parseDirectiveCFISignalFrame() {
3122 if (getLexer().isNot(AsmToken::EndOfStatement))
3123 return Error(getLexer().getLoc(),
3124 "unexpected token in '.cfi_signal_frame'");
3126 getStreamer().EmitCFISignalFrame();
3130 /// parseDirectiveCFIUndefined
3131 /// ::= .cfi_undefined register
3132 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3133 int64_t Register = 0;
3135 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3138 getStreamer().EmitCFIUndefined(Register);
3142 /// parseDirectiveMacrosOnOff
3145 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3146 if (getLexer().isNot(AsmToken::EndOfStatement))
3147 return Error(getLexer().getLoc(),
3148 "unexpected token in '" + Directive + "' directive");
3150 setMacrosEnabled(Directive == ".macros_on");
3154 /// parseDirectiveMacro
3155 /// ::= .macro name [parameters]
3156 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3158 if (parseIdentifier(Name))
3159 return TokError("expected identifier in '.macro' directive");
3161 MCAsmMacroParameters Parameters;
3162 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3163 MCAsmMacroParameter Parameter;
3164 if (parseIdentifier(Parameter.first))
3165 return TokError("expected identifier in '.macro' directive");
3167 if (getLexer().is(AsmToken::Equal)) {
3169 if (parseMacroArgument(Parameter.second))
3173 Parameters.push_back(Parameter);
3175 if (getLexer().is(AsmToken::Comma))
3179 // Eat the end of statement.
3182 AsmToken EndToken, StartToken = getTok();
3183 unsigned MacroDepth = 0;
3185 // Lex the macro definition.
3187 // Check whether we have reached the end of the file.
3188 if (getLexer().is(AsmToken::Eof))
3189 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3191 // Otherwise, check whether we have reach the .endmacro.
3192 if (getLexer().is(AsmToken::Identifier)) {
3193 if (getTok().getIdentifier() == ".endm" ||
3194 getTok().getIdentifier() == ".endmacro") {
3195 if (MacroDepth == 0) { // Outermost macro.
3196 EndToken = getTok();
3198 if (getLexer().isNot(AsmToken::EndOfStatement))
3199 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3203 // Otherwise we just found the end of an inner macro.
3206 } else if (getTok().getIdentifier() == ".macro") {
3207 // We allow nested macros. Those aren't instantiated until the outermost
3208 // macro is expanded so just ignore them for now.
3213 // Otherwise, scan til the end of the statement.
3214 eatToEndOfStatement();
3217 if (lookupMacro(Name)) {
3218 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3221 const char *BodyStart = StartToken.getLoc().getPointer();
3222 const char *BodyEnd = EndToken.getLoc().getPointer();
3223 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3224 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3225 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3229 /// checkForBadMacro
3231 /// With the support added for named parameters there may be code out there that
3232 /// is transitioning from positional parameters. In versions of gas that did
3233 /// not support named parameters they would be ignored on the macro definition.
3234 /// But to support both styles of parameters this is not possible so if a macro
3235 /// definition has named parameters but does not use them and has what appears
3236 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3237 /// warning that the positional parameter found in body which have no effect.
3238 /// Hoping the developer will either remove the named parameters from the macro
3239 /// definition so the positional parameters get used if that was what was
3240 /// intended or change the macro to use the named parameters. It is possible
3241 /// this warning will trigger when the none of the named parameters are used
3242 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3243 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3245 ArrayRef<MCAsmMacroParameter> Parameters) {
3246 // If this macro is not defined with named parameters the warning we are
3247 // checking for here doesn't apply.
3248 unsigned NParameters = Parameters.size();
3249 if (NParameters == 0)
3252 bool NamedParametersFound = false;
3253 bool PositionalParametersFound = false;
3255 // Look at the body of the macro for use of both the named parameters and what
3256 // are likely to be positional parameters. This is what expandMacro() is
3257 // doing when it finds the parameters in the body.
3258 while (!Body.empty()) {
3259 // Scan for the next possible parameter.
3260 std::size_t End = Body.size(), Pos = 0;
3261 for (; Pos != End; ++Pos) {
3262 // Check for a substitution or escape.
3263 // This macro is defined with parameters, look for \foo, \bar, etc.
3264 if (Body[Pos] == '\\' && Pos + 1 != End)
3267 // This macro should have parameters, but look for $0, $1, ..., $n too.
3268 if (Body[Pos] != '$' || Pos + 1 == End)
3270 char Next = Body[Pos + 1];
3271 if (Next == '$' || Next == 'n' ||
3272 isdigit(static_cast<unsigned char>(Next)))
3276 // Check if we reached the end.
3280 if (Body[Pos] == '$') {
3281 switch (Body[Pos + 1]) {
3286 // $n => number of arguments
3288 PositionalParametersFound = true;
3291 // $[0-9] => argument
3293 PositionalParametersFound = true;
3299 unsigned I = Pos + 1;
3300 while (isIdentifierChar(Body[I]) && I + 1 != End)
3303 const char *Begin = Body.data() + Pos + 1;
3304 StringRef Argument(Begin, I - (Pos + 1));
3306 for (; Index < NParameters; ++Index)
3307 if (Parameters[Index].first == Argument)
3310 if (Index == NParameters) {
3311 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3317 NamedParametersFound = true;
3318 Pos += 1 + Argument.size();
3321 // Update the scan point.
3322 Body = Body.substr(Pos);
3325 if (!NamedParametersFound && PositionalParametersFound)
3326 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3327 "used in macro body, possible positional parameter "
3328 "found in body which will have no effect");
3331 /// parseDirectiveEndMacro
3334 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3335 if (getLexer().isNot(AsmToken::EndOfStatement))
3336 return TokError("unexpected token in '" + Directive + "' directive");
3338 // If we are inside a macro instantiation, terminate the current
3340 if (isInsideMacroInstantiation()) {
3345 // Otherwise, this .endmacro is a stray entry in the file; well formed
3346 // .endmacro directives are handled during the macro definition parsing.
3347 return TokError("unexpected '" + Directive + "' in file, "
3348 "no current macro definition");
3351 /// parseDirectivePurgeMacro
3353 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3355 if (parseIdentifier(Name))
3356 return TokError("expected identifier in '.purgem' directive");
3358 if (getLexer().isNot(AsmToken::EndOfStatement))
3359 return TokError("unexpected token in '.purgem' directive");
3361 if (!lookupMacro(Name))
3362 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3364 undefineMacro(Name);
3368 /// parseDirectiveBundleAlignMode
3369 /// ::= {.bundle_align_mode} expression
3370 bool AsmParser::parseDirectiveBundleAlignMode() {
3371 checkForValidSection();
3373 // Expect a single argument: an expression that evaluates to a constant
3374 // in the inclusive range 0-30.
3375 SMLoc ExprLoc = getLexer().getLoc();
3376 int64_t AlignSizePow2;
3377 if (parseAbsoluteExpression(AlignSizePow2))
3379 else if (getLexer().isNot(AsmToken::EndOfStatement))
3380 return TokError("unexpected token after expression in"
3381 " '.bundle_align_mode' directive");
3382 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3383 return Error(ExprLoc,
3384 "invalid bundle alignment size (expected between 0 and 30)");
3388 // Because of AlignSizePow2's verified range we can safely truncate it to
3390 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3394 /// parseDirectiveBundleLock
3395 /// ::= {.bundle_lock} [align_to_end]
3396 bool AsmParser::parseDirectiveBundleLock() {
3397 checkForValidSection();
3398 bool AlignToEnd = false;
3400 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3402 SMLoc Loc = getTok().getLoc();
3403 const char *kInvalidOptionError =
3404 "invalid option for '.bundle_lock' directive";
3406 if (parseIdentifier(Option))
3407 return Error(Loc, kInvalidOptionError);
3409 if (Option != "align_to_end")
3410 return Error(Loc, kInvalidOptionError);
3411 else if (getLexer().isNot(AsmToken::EndOfStatement))
3413 "unexpected token after '.bundle_lock' directive option");
3419 getStreamer().EmitBundleLock(AlignToEnd);
3423 /// parseDirectiveBundleLock
3424 /// ::= {.bundle_lock}
3425 bool AsmParser::parseDirectiveBundleUnlock() {
3426 checkForValidSection();
3428 if (getLexer().isNot(AsmToken::EndOfStatement))
3429 return TokError("unexpected token in '.bundle_unlock' directive");
3432 getStreamer().EmitBundleUnlock();
3436 /// parseDirectiveSpace
3437 /// ::= (.skip | .space) expression [ , expression ]
3438 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3439 checkForValidSection();
3442 if (parseAbsoluteExpression(NumBytes))
3445 int64_t FillExpr = 0;
3446 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3447 if (getLexer().isNot(AsmToken::Comma))
3448 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3451 if (parseAbsoluteExpression(FillExpr))
3454 if (getLexer().isNot(AsmToken::EndOfStatement))
3455 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3461 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3464 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3465 getStreamer().EmitFill(NumBytes, FillExpr);
3470 /// parseDirectiveLEB128
3471 /// ::= (.sleb128 | .uleb128) expression
3472 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3473 checkForValidSection();
3474 const MCExpr *Value;
3476 if (parseExpression(Value))
3479 if (getLexer().isNot(AsmToken::EndOfStatement))
3480 return TokError("unexpected token in directive");
3483 getStreamer().EmitSLEB128Value(Value);
3485 getStreamer().EmitULEB128Value(Value);
3490 /// parseDirectiveSymbolAttribute
3491 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3492 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3493 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3496 SMLoc Loc = getTok().getLoc();
3498 if (parseIdentifier(Name))
3499 return Error(Loc, "expected identifier in directive");
3501 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3503 // Assembler local symbols don't make any sense here. Complain loudly.
3504 if (Sym->isTemporary())
3505 return Error(Loc, "non-local symbol required in directive");
3507 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3508 return Error(Loc, "unable to emit symbol attribute");
3510 if (getLexer().is(AsmToken::EndOfStatement))
3513 if (getLexer().isNot(AsmToken::Comma))
3514 return TokError("unexpected token in directive");
3523 /// parseDirectiveComm
3524 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3525 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3526 checkForValidSection();
3528 SMLoc IDLoc = getLexer().getLoc();
3530 if (parseIdentifier(Name))
3531 return TokError("expected identifier in directive");
3533 // Handle the identifier as the key symbol.
3534 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3536 if (getLexer().isNot(AsmToken::Comma))
3537 return TokError("unexpected token in directive");
3541 SMLoc SizeLoc = getLexer().getLoc();
3542 if (parseAbsoluteExpression(Size))
3545 int64_t Pow2Alignment = 0;
3546 SMLoc Pow2AlignmentLoc;
3547 if (getLexer().is(AsmToken::Comma)) {
3549 Pow2AlignmentLoc = getLexer().getLoc();
3550 if (parseAbsoluteExpression(Pow2Alignment))
3553 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3554 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3555 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3557 // If this target takes alignments in bytes (not log) validate and convert.
3558 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3559 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3560 if (!isPowerOf2_64(Pow2Alignment))
3561 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3562 Pow2Alignment = Log2_64(Pow2Alignment);
3566 if (getLexer().isNot(AsmToken::EndOfStatement))
3567 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3571 // NOTE: a size of zero for a .comm should create a undefined symbol
3572 // but a size of .lcomm creates a bss symbol of size zero.
3574 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3575 "be less than zero");
3577 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3578 // may internally end up wanting an alignment in bytes.
3579 // FIXME: Diagnose overflow.
3580 if (Pow2Alignment < 0)
3581 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3582 "alignment, can't be less than zero");
3584 if (!Sym->isUndefined())
3585 return Error(IDLoc, "invalid symbol redefinition");
3587 // Create the Symbol as a common or local common with Size and Pow2Alignment
3589 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3593 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3597 /// parseDirectiveAbort
3598 /// ::= .abort [... message ...]
3599 bool AsmParser::parseDirectiveAbort() {
3600 // FIXME: Use loc from directive.
3601 SMLoc Loc = getLexer().getLoc();
3603 StringRef Str = parseStringToEndOfStatement();
3604 if (getLexer().isNot(AsmToken::EndOfStatement))
3605 return TokError("unexpected token in '.abort' directive");
3610 Error(Loc, ".abort detected. Assembly stopping.");
3612 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3613 // FIXME: Actually abort assembly here.
3618 /// parseDirectiveInclude
3619 /// ::= .include "filename"
3620 bool AsmParser::parseDirectiveInclude() {
3621 if (getLexer().isNot(AsmToken::String))
3622 return TokError("expected string in '.include' directive");
3624 // Allow the strings to have escaped octal character sequence.
3625 std::string Filename;
3626 if (parseEscapedString(Filename))
3628 SMLoc IncludeLoc = getLexer().getLoc();
3631 if (getLexer().isNot(AsmToken::EndOfStatement))
3632 return TokError("unexpected token in '.include' directive");
3634 // Attempt to switch the lexer to the included file before consuming the end
3635 // of statement to avoid losing it when we switch.
3636 if (enterIncludeFile(Filename)) {
3637 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3644 /// parseDirectiveIncbin
3645 /// ::= .incbin "filename"
3646 bool AsmParser::parseDirectiveIncbin() {
3647 if (getLexer().isNot(AsmToken::String))
3648 return TokError("expected string in '.incbin' directive");
3650 // Allow the strings to have escaped octal character sequence.
3651 std::string Filename;
3652 if (parseEscapedString(Filename))
3654 SMLoc IncbinLoc = getLexer().getLoc();
3657 if (getLexer().isNot(AsmToken::EndOfStatement))
3658 return TokError("unexpected token in '.incbin' directive");
3660 // Attempt to process the included file.
3661 if (processIncbinFile(Filename)) {
3662 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3669 /// parseDirectiveIf
3670 /// ::= .if expression
3671 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3672 TheCondStack.push_back(TheCondState);
3673 TheCondState.TheCond = AsmCond::IfCond;
3674 if (TheCondState.Ignore) {
3675 eatToEndOfStatement();
3678 if (parseAbsoluteExpression(ExprValue))
3681 if (getLexer().isNot(AsmToken::EndOfStatement))
3682 return TokError("unexpected token in '.if' directive");
3686 TheCondState.CondMet = ExprValue;
3687 TheCondState.Ignore = !TheCondState.CondMet;
3693 /// parseDirectiveIfb
3695 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3696 TheCondStack.push_back(TheCondState);
3697 TheCondState.TheCond = AsmCond::IfCond;
3699 if (TheCondState.Ignore) {
3700 eatToEndOfStatement();
3702 StringRef Str = parseStringToEndOfStatement();
3704 if (getLexer().isNot(AsmToken::EndOfStatement))
3705 return TokError("unexpected token in '.ifb' directive");
3709 TheCondState.CondMet = ExpectBlank == Str.empty();
3710 TheCondState.Ignore = !TheCondState.CondMet;
3716 /// parseDirectiveIfc
3717 /// ::= .ifc string1, string2
3718 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3719 TheCondStack.push_back(TheCondState);
3720 TheCondState.TheCond = AsmCond::IfCond;
3722 if (TheCondState.Ignore) {
3723 eatToEndOfStatement();
3725 StringRef Str1 = parseStringToComma();
3727 if (getLexer().isNot(AsmToken::Comma))
3728 return TokError("unexpected token in '.ifc' directive");
3732 StringRef Str2 = parseStringToEndOfStatement();
3734 if (getLexer().isNot(AsmToken::EndOfStatement))
3735 return TokError("unexpected token in '.ifc' directive");
3739 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3740 TheCondState.Ignore = !TheCondState.CondMet;
3746 /// parseDirectiveIfdef
3747 /// ::= .ifdef symbol
3748 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3750 TheCondStack.push_back(TheCondState);
3751 TheCondState.TheCond = AsmCond::IfCond;
3753 if (TheCondState.Ignore) {
3754 eatToEndOfStatement();
3756 if (parseIdentifier(Name))
3757 return TokError("expected identifier after '.ifdef'");
3761 MCSymbol *Sym = getContext().LookupSymbol(Name);
3764 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3766 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3767 TheCondState.Ignore = !TheCondState.CondMet;
3773 /// parseDirectiveElseIf
3774 /// ::= .elseif expression
3775 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3776 if (TheCondState.TheCond != AsmCond::IfCond &&
3777 TheCondState.TheCond != AsmCond::ElseIfCond)
3778 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3780 TheCondState.TheCond = AsmCond::ElseIfCond;
3782 bool LastIgnoreState = false;
3783 if (!TheCondStack.empty())
3784 LastIgnoreState = TheCondStack.back().Ignore;
3785 if (LastIgnoreState || TheCondState.CondMet) {
3786 TheCondState.Ignore = true;
3787 eatToEndOfStatement();
3790 if (parseAbsoluteExpression(ExprValue))
3793 if (getLexer().isNot(AsmToken::EndOfStatement))
3794 return TokError("unexpected token in '.elseif' directive");
3797 TheCondState.CondMet = ExprValue;
3798 TheCondState.Ignore = !TheCondState.CondMet;
3804 /// parseDirectiveElse
3806 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3807 if (getLexer().isNot(AsmToken::EndOfStatement))
3808 return TokError("unexpected token in '.else' directive");
3812 if (TheCondState.TheCond != AsmCond::IfCond &&
3813 TheCondState.TheCond != AsmCond::ElseIfCond)
3814 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3816 TheCondState.TheCond = AsmCond::ElseCond;
3817 bool LastIgnoreState = false;
3818 if (!TheCondStack.empty())
3819 LastIgnoreState = TheCondStack.back().Ignore;
3820 if (LastIgnoreState || TheCondState.CondMet)
3821 TheCondState.Ignore = true;
3823 TheCondState.Ignore = false;
3828 /// parseDirectiveEnd
3830 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3831 if (getLexer().isNot(AsmToken::EndOfStatement))
3832 return TokError("unexpected token in '.end' directive");
3836 while (Lexer.isNot(AsmToken::Eof))
3842 /// parseDirectiveEndIf
3844 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3845 if (getLexer().isNot(AsmToken::EndOfStatement))
3846 return TokError("unexpected token in '.endif' directive");
3850 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3851 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3853 if (!TheCondStack.empty()) {
3854 TheCondState = TheCondStack.back();
3855 TheCondStack.pop_back();
3861 void AsmParser::initializeDirectiveKindMap() {
3862 DirectiveKindMap[".set"] = DK_SET;
3863 DirectiveKindMap[".equ"] = DK_EQU;
3864 DirectiveKindMap[".equiv"] = DK_EQUIV;
3865 DirectiveKindMap[".ascii"] = DK_ASCII;
3866 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3867 DirectiveKindMap[".string"] = DK_STRING;
3868 DirectiveKindMap[".byte"] = DK_BYTE;
3869 DirectiveKindMap[".short"] = DK_SHORT;
3870 DirectiveKindMap[".value"] = DK_VALUE;
3871 DirectiveKindMap[".2byte"] = DK_2BYTE;
3872 DirectiveKindMap[".long"] = DK_LONG;
3873 DirectiveKindMap[".int"] = DK_INT;
3874 DirectiveKindMap[".4byte"] = DK_4BYTE;
3875 DirectiveKindMap[".quad"] = DK_QUAD;
3876 DirectiveKindMap[".8byte"] = DK_8BYTE;
3877 DirectiveKindMap[".octa"] = DK_OCTA;
3878 DirectiveKindMap[".single"] = DK_SINGLE;
3879 DirectiveKindMap[".float"] = DK_FLOAT;
3880 DirectiveKindMap[".double"] = DK_DOUBLE;
3881 DirectiveKindMap[".align"] = DK_ALIGN;
3882 DirectiveKindMap[".align32"] = DK_ALIGN32;
3883 DirectiveKindMap[".balign"] = DK_BALIGN;
3884 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3885 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3886 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3887 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3888 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3889 DirectiveKindMap[".org"] = DK_ORG;
3890 DirectiveKindMap[".fill"] = DK_FILL;
3891 DirectiveKindMap[".zero"] = DK_ZERO;
3892 DirectiveKindMap[".extern"] = DK_EXTERN;
3893 DirectiveKindMap[".globl"] = DK_GLOBL;
3894 DirectiveKindMap[".global"] = DK_GLOBAL;
3895 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3896 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3897 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3898 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3899 DirectiveKindMap[".reference"] = DK_REFERENCE;
3900 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3901 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3902 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3903 DirectiveKindMap[".comm"] = DK_COMM;
3904 DirectiveKindMap[".common"] = DK_COMMON;
3905 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3906 DirectiveKindMap[".abort"] = DK_ABORT;
3907 DirectiveKindMap[".include"] = DK_INCLUDE;
3908 DirectiveKindMap[".incbin"] = DK_INCBIN;
3909 DirectiveKindMap[".code16"] = DK_CODE16;
3910 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3911 DirectiveKindMap[".rept"] = DK_REPT;
3912 DirectiveKindMap[".rep"] = DK_REPT;
3913 DirectiveKindMap[".irp"] = DK_IRP;
3914 DirectiveKindMap[".irpc"] = DK_IRPC;
3915 DirectiveKindMap[".endr"] = DK_ENDR;
3916 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3917 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3918 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3919 DirectiveKindMap[".if"] = DK_IF;
3920 DirectiveKindMap[".ifb"] = DK_IFB;
3921 DirectiveKindMap[".ifnb"] = DK_IFNB;
3922 DirectiveKindMap[".ifc"] = DK_IFC;
3923 DirectiveKindMap[".ifnc"] = DK_IFNC;
3924 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3925 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3926 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3927 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3928 DirectiveKindMap[".else"] = DK_ELSE;
3929 DirectiveKindMap[".end"] = DK_END;
3930 DirectiveKindMap[".endif"] = DK_ENDIF;
3931 DirectiveKindMap[".skip"] = DK_SKIP;
3932 DirectiveKindMap[".space"] = DK_SPACE;
3933 DirectiveKindMap[".file"] = DK_FILE;
3934 DirectiveKindMap[".line"] = DK_LINE;
3935 DirectiveKindMap[".loc"] = DK_LOC;
3936 DirectiveKindMap[".stabs"] = DK_STABS;
3937 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3938 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3939 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3940 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3941 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3942 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3943 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3944 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3945 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3946 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3947 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3948 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3949 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3950 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3951 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3952 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3953 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3954 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3955 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3956 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3957 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3958 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
3959 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3960 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3961 DirectiveKindMap[".macro"] = DK_MACRO;
3962 DirectiveKindMap[".endm"] = DK_ENDM;
3963 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3964 DirectiveKindMap[".purgem"] = DK_PURGEM;
3967 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
3968 AsmToken EndToken, StartToken = getTok();
3970 unsigned NestLevel = 0;
3972 // Check whether we have reached the end of the file.
3973 if (getLexer().is(AsmToken::Eof)) {
3974 Error(DirectiveLoc, "no matching '.endr' in definition");
3978 if (Lexer.is(AsmToken::Identifier) &&
3979 (getTok().getIdentifier() == ".rept")) {
3983 // Otherwise, check whether we have reached the .endr.
3984 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
3985 if (NestLevel == 0) {
3986 EndToken = getTok();
3988 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3989 TokError("unexpected token in '.endr' directive");
3997 // Otherwise, scan till the end of the statement.
3998 eatToEndOfStatement();
4001 const char *BodyStart = StartToken.getLoc().getPointer();
4002 const char *BodyEnd = EndToken.getLoc().getPointer();
4003 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4005 // We Are Anonymous.
4006 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4007 return &MacroLikeBodies.back();
4010 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4011 raw_svector_ostream &OS) {
4014 MemoryBuffer *Instantiation =
4015 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4017 // Create the macro instantiation object and add to the current macro
4018 // instantiation stack.
4019 MacroInstantiation *MI = new MacroInstantiation(
4020 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4021 ActiveMacros.push_back(MI);
4023 // Jump to the macro instantiation and prime the lexer.
4024 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4025 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4029 /// parseDirectiveRept
4030 /// ::= .rep | .rept count
4031 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4032 const MCExpr *CountExpr;
4033 SMLoc CountLoc = getTok().getLoc();
4034 if (parseExpression(CountExpr))
4038 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4039 eatToEndOfStatement();
4040 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4044 return Error(CountLoc, "Count is negative");
4046 if (Lexer.isNot(AsmToken::EndOfStatement))
4047 return TokError("unexpected token in '" + Dir + "' directive");
4049 // Eat the end of statement.
4052 // Lex the rept definition.
4053 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4057 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4058 // to hold the macro body with substitutions.
4059 SmallString<256> Buf;
4060 raw_svector_ostream OS(Buf);
4062 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4065 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4070 /// parseDirectiveIrp
4071 /// ::= .irp symbol,values
4072 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4073 MCAsmMacroParameter Parameter;
4075 if (parseIdentifier(Parameter.first))
4076 return TokError("expected identifier in '.irp' directive");
4078 if (Lexer.isNot(AsmToken::Comma))
4079 return TokError("expected comma in '.irp' directive");
4083 MCAsmMacroArguments A;
4084 if (parseMacroArguments(0, A))
4087 // Eat the end of statement.
4090 // Lex the irp definition.
4091 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4095 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4096 // to hold the macro body with substitutions.
4097 SmallString<256> Buf;
4098 raw_svector_ostream OS(Buf);
4100 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4101 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4105 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4110 /// parseDirectiveIrpc
4111 /// ::= .irpc symbol,values
4112 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4113 MCAsmMacroParameter Parameter;
4115 if (parseIdentifier(Parameter.first))
4116 return TokError("expected identifier in '.irpc' directive");
4118 if (Lexer.isNot(AsmToken::Comma))
4119 return TokError("expected comma in '.irpc' directive");
4123 MCAsmMacroArguments A;
4124 if (parseMacroArguments(0, A))
4127 if (A.size() != 1 || A.front().size() != 1)
4128 return TokError("unexpected token in '.irpc' directive");
4130 // Eat the end of statement.
4133 // Lex the irpc definition.
4134 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4138 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4139 // to hold the macro body with substitutions.
4140 SmallString<256> Buf;
4141 raw_svector_ostream OS(Buf);
4143 StringRef Values = A.front().front().getString();
4144 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4145 MCAsmMacroArgument Arg;
4146 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4148 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4152 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4157 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4158 if (ActiveMacros.empty())
4159 return TokError("unmatched '.endr' directive");
4161 // The only .repl that should get here are the ones created by
4162 // instantiateMacroLikeBody.
4163 assert(getLexer().is(AsmToken::EndOfStatement));
4169 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4171 const MCExpr *Value;
4172 SMLoc ExprLoc = getLexer().getLoc();
4173 if (parseExpression(Value))
4175 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4177 return Error(ExprLoc, "unexpected expression in _emit");
4178 uint64_t IntValue = MCE->getValue();
4179 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4180 return Error(ExprLoc, "literal value out of range for directive");
4182 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4186 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4187 const MCExpr *Value;
4188 SMLoc ExprLoc = getLexer().getLoc();
4189 if (parseExpression(Value))
4191 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4193 return Error(ExprLoc, "unexpected expression in align");
4194 uint64_t IntValue = MCE->getValue();
4195 if (!isPowerOf2_64(IntValue))
4196 return Error(ExprLoc, "literal value not a power of two greater then zero");
4198 Info.AsmRewrites->push_back(
4199 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4203 // We are comparing pointers, but the pointers are relative to a single string.
4204 // Thus, this should always be deterministic.
4205 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4206 const AsmRewrite *AsmRewriteB) {
4207 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4209 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4212 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4213 // rewrite to the same location. Make sure the SizeDirective rewrite is
4214 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4215 // ensures the sort algorithm is stable.
4216 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4217 AsmRewritePrecedence[AsmRewriteB->Kind])
4220 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4221 AsmRewritePrecedence[AsmRewriteB->Kind])
4223 llvm_unreachable("Unstable rewrite sort.");
4226 bool AsmParser::parseMSInlineAsm(
4227 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4228 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4229 SmallVectorImpl<std::string> &Constraints,
4230 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4231 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4232 SmallVector<void *, 4> InputDecls;
4233 SmallVector<void *, 4> OutputDecls;
4234 SmallVector<bool, 4> InputDeclsAddressOf;
4235 SmallVector<bool, 4> OutputDeclsAddressOf;
4236 SmallVector<std::string, 4> InputConstraints;
4237 SmallVector<std::string, 4> OutputConstraints;
4238 SmallVector<unsigned, 4> ClobberRegs;
4240 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4245 // While we have input, parse each statement.
4246 unsigned InputIdx = 0;
4247 unsigned OutputIdx = 0;
4248 while (getLexer().isNot(AsmToken::Eof)) {
4249 ParseStatementInfo Info(&AsmStrRewrites);
4250 if (parseStatement(Info))
4253 if (Info.ParseError)
4256 if (Info.Opcode == ~0U)
4259 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4261 // Build the list of clobbers, outputs and inputs.
4262 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4263 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4266 if (Operand->isImm())
4269 // Register operand.
4270 if (Operand->isReg() && !Operand->needAddressOf()) {
4271 unsigned NumDefs = Desc.getNumDefs();
4273 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4274 ClobberRegs.push_back(Operand->getReg());
4278 // Expr/Input or Output.
4279 StringRef SymName = Operand->getSymName();
4280 if (SymName.empty())
4283 void *OpDecl = Operand->getOpDecl();
4287 bool isOutput = (i == 1) && Desc.mayStore();
4288 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4291 OutputDecls.push_back(OpDecl);
4292 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4293 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4294 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4296 InputDecls.push_back(OpDecl);
4297 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4298 InputConstraints.push_back(Operand->getConstraint().str());
4299 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4303 // Consider implicit defs to be clobbers. Think of cpuid and push.
4304 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4305 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4306 ClobberRegs.push_back(ImpDefs[I]);
4309 // Set the number of Outputs and Inputs.
4310 NumOutputs = OutputDecls.size();
4311 NumInputs = InputDecls.size();
4313 // Set the unique clobbers.
4314 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4315 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4317 Clobbers.assign(ClobberRegs.size(), std::string());
4318 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4319 raw_string_ostream OS(Clobbers[I]);
4320 IP->printRegName(OS, ClobberRegs[I]);
4323 // Merge the various outputs and inputs. Output are expected first.
4324 if (NumOutputs || NumInputs) {
4325 unsigned NumExprs = NumOutputs + NumInputs;
4326 OpDecls.resize(NumExprs);
4327 Constraints.resize(NumExprs);
4328 for (unsigned i = 0; i < NumOutputs; ++i) {
4329 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4330 Constraints[i] = OutputConstraints[i];
4332 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4333 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4334 Constraints[j] = InputConstraints[i];
4338 // Build the IR assembly string.
4339 std::string AsmStringIR;
4340 raw_string_ostream OS(AsmStringIR);
4341 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4342 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4343 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4344 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4345 E = AsmStrRewrites.end();
4347 AsmRewriteKind Kind = (*I).Kind;
4348 if (Kind == AOK_Delete)
4351 const char *Loc = (*I).Loc.getPointer();
4352 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4354 // Emit everything up to the immediate/expression.
4355 unsigned Len = Loc - AsmStart;
4357 OS << StringRef(AsmStart, Len);
4359 // Skip the original expression.
4360 if (Kind == AOK_Skip) {
4361 AsmStart = Loc + (*I).Len;
4365 unsigned AdditionalSkip = 0;
4366 // Rewrite expressions in $N notation.
4371 OS << "$$" << (*I).Val;
4377 OS << '$' << InputIdx++;
4380 OS << '$' << OutputIdx++;
4382 case AOK_SizeDirective:
4385 case 8: OS << "byte ptr "; break;
4386 case 16: OS << "word ptr "; break;
4387 case 32: OS << "dword ptr "; break;
4388 case 64: OS << "qword ptr "; break;
4389 case 80: OS << "xword ptr "; break;
4390 case 128: OS << "xmmword ptr "; break;
4391 case 256: OS << "ymmword ptr "; break;
4398 unsigned Val = (*I).Val;
4399 OS << ".align " << Val;
4401 // Skip the original immediate.
4402 assert(Val < 10 && "Expected alignment less then 2^10.");
4403 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4406 case AOK_DotOperator:
4411 // Skip the original expression.
4412 AsmStart = Loc + (*I).Len + AdditionalSkip;
4415 // Emit the remainder of the asm string.
4416 if (AsmStart != AsmEnd)
4417 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4419 AsmString = OS.str();
4423 /// \brief Create an MCAsmParser instance.
4424 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4425 MCStreamer &Out, const MCAsmInfo &MAI) {
4426 return new AsmParser(SM, C, Out, MAI);