1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 FatalAssemblerWarnings("fatal-assembler-warnings",
49 cl::desc("Consider warnings as error"));
51 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
54 /// \brief Helper types for tracking macro definitions.
55 typedef std::vector<AsmToken> MCAsmMacroArgument;
56 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58 struct MCAsmMacroParameter {
60 MCAsmMacroArgument Value;
63 MCAsmMacroParameter() : Required(false) { }
66 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
71 MCAsmMacroParameters Parameters;
74 MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
75 Name(N), Body(B), Parameters(P) {}
78 /// \brief Helper class for storing information about an active macro
80 struct MacroInstantiation {
81 /// The macro being instantiated.
82 const MCAsmMacro *TheMacro;
84 /// The macro instantiation with substitutions.
85 MemoryBuffer *Instantiation;
87 /// The location of the instantiation.
88 SMLoc InstantiationLoc;
90 /// The buffer where parsing should resume upon instantiation completion.
93 /// The location where parsing should resume upon instantiation completion.
97 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
101 struct ParseStatementInfo {
102 /// \brief The parsed operands from the last parsed statement.
103 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
105 /// \brief The opcode from the last parsed instruction.
108 /// \brief Was there an error parsing the inline assembly?
111 SmallVectorImpl<AsmRewrite> *AsmRewrites;
113 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
114 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
115 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
117 ~ParseStatementInfo() {
118 // Free any parsed operands.
119 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
120 delete ParsedOperands[i];
121 ParsedOperands.clear();
125 /// \brief The concrete assembly parser instance.
126 class AsmParser : public MCAsmParser {
127 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
128 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
133 const MCAsmInfo &MAI;
135 SourceMgr::DiagHandlerTy SavedDiagHandler;
136 void *SavedDiagContext;
137 MCAsmParserExtension *PlatformParser;
139 /// This is the current buffer index we're lexing from as managed by the
140 /// SourceMgr object.
143 AsmCond TheCondState;
144 std::vector<AsmCond> TheCondStack;
146 /// \brief maps directive names to handler methods in parser
147 /// extensions. Extensions register themselves in this map by calling
148 /// addDirectiveHandler.
149 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
151 /// \brief Map of currently defined macros.
152 StringMap<MCAsmMacro*> MacroMap;
154 /// \brief Stack of active macro instantiations.
155 std::vector<MacroInstantiation*> ActiveMacros;
157 /// \brief List of bodies of anonymous macros.
158 std::deque<MCAsmMacro> MacroLikeBodies;
160 /// Boolean tracking whether macro substitution is enabled.
161 unsigned MacrosEnabledFlag : 1;
163 /// Flag tracking whether any errors have been encountered.
164 unsigned HadError : 1;
166 /// The values from the last parsed cpp hash file line comment if any.
167 StringRef CppHashFilename;
168 int64_t CppHashLineNumber;
171 /// When generating dwarf for assembly source files we need to calculate the
172 /// logical line number based on the last parsed cpp hash file line comment
173 /// and current line. Since this is slow and messes up the SourceMgr's
174 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
175 SMLoc LastQueryIDLoc;
177 unsigned LastQueryLine;
179 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
180 unsigned AssemblerDialect;
182 /// \brief is Darwin compatibility enabled?
185 /// \brief Are we parsing ms-style inline assembly?
186 bool ParsingInlineAsm;
189 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
190 const MCAsmInfo &MAI);
191 virtual ~AsmParser();
193 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
195 virtual void addDirectiveHandler(StringRef Directive,
196 ExtensionDirectiveHandler Handler) {
197 ExtensionDirectiveMap[Directive] = Handler;
201 /// @name MCAsmParser Interface
204 virtual SourceMgr &getSourceManager() { return SrcMgr; }
205 virtual MCAsmLexer &getLexer() { return Lexer; }
206 virtual MCContext &getContext() { return Ctx; }
207 virtual MCStreamer &getStreamer() { return Out; }
208 virtual unsigned getAssemblerDialect() {
209 if (AssemblerDialect == ~0U)
210 return MAI.getAssemblerDialect();
212 return AssemblerDialect;
214 virtual void setAssemblerDialect(unsigned i) {
215 AssemblerDialect = i;
218 virtual void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None);
219 virtual bool Warning(SMLoc L, const Twine &Msg,
220 ArrayRef<SMRange> Ranges = None);
221 virtual bool Error(SMLoc L, const Twine &Msg,
222 ArrayRef<SMRange> Ranges = None);
224 virtual const AsmToken &Lex();
226 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
227 bool isParsingInlineAsm() { return ParsingInlineAsm; }
229 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
230 unsigned &NumOutputs, unsigned &NumInputs,
231 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
232 SmallVectorImpl<std::string> &Constraints,
233 SmallVectorImpl<std::string> &Clobbers,
234 const MCInstrInfo *MII,
235 const MCInstPrinter *IP,
236 MCAsmParserSemaCallback &SI);
238 bool parseExpression(const MCExpr *&Res);
239 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
240 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
241 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
242 virtual bool parseAbsoluteExpression(int64_t &Res);
244 /// \brief Parse an identifier or string (as a quoted identifier)
245 /// and set \p Res to the identifier contents.
246 virtual bool parseIdentifier(StringRef &Res);
247 virtual void eatToEndOfStatement();
249 virtual void checkForValidSection();
254 bool parseStatement(ParseStatementInfo &Info);
255 void eatToEndOfLine();
256 bool parseCppHashLineFilenameComment(const SMLoc &L);
258 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
259 ArrayRef<MCAsmMacroParameter> Parameters);
260 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
261 ArrayRef<MCAsmMacroParameter> Parameters,
262 ArrayRef<MCAsmMacroArgument> A,
265 /// \brief Are macros enabled in the parser?
266 bool areMacrosEnabled() {return MacrosEnabledFlag;}
268 /// \brief Control a flag in the parser that enables or disables macros.
269 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
271 /// \brief Lookup a previously defined macro.
272 /// \param Name Macro name.
273 /// \returns Pointer to macro. NULL if no such macro was defined.
274 const MCAsmMacro* lookupMacro(StringRef Name);
276 /// \brief Define a new macro with the given name and information.
277 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
279 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
280 void undefineMacro(StringRef Name);
282 /// \brief Are we inside a macro instantiation?
283 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
285 /// \brief Handle entry to macro instantiation.
287 /// \param M The macro.
288 /// \param NameLoc Instantiation location.
289 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
291 /// \brief Handle exit from macro instantiation.
292 void handleMacroExit();
294 /// \brief Extract AsmTokens for a macro argument.
295 bool parseMacroArgument(MCAsmMacroArgument &MA);
297 /// \brief Parse all macro arguments for a given macro.
298 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
300 void printMacroInstantiations();
301 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
302 ArrayRef<SMRange> Ranges = None) const {
303 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
305 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
307 /// \brief Enter the specified file. This returns true on failure.
308 bool enterIncludeFile(const std::string &Filename);
310 /// \brief Process the specified file for the .incbin directive.
311 /// This returns true on failure.
312 bool processIncbinFile(const std::string &Filename);
314 /// \brief Reset the current lexer position to that given by \p Loc. The
315 /// current token is not set; clients should ensure Lex() is called
318 /// \param InBuffer If not -1, should be the known buffer id that contains the
320 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
322 /// \brief Parse up to the end of statement and a return the contents from the
323 /// current token until the end of the statement; the current token on exit
324 /// will be either the EndOfStatement or EOF.
325 virtual StringRef parseStringToEndOfStatement();
327 /// \brief Parse until the end of a statement or a comma is encountered,
328 /// return the contents from the current token up to the end or comma.
329 StringRef parseStringToComma();
331 bool parseAssignment(StringRef Name, bool allow_redef,
332 bool NoDeadStrip = false);
334 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
335 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
338 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
340 // Generic (target and platform independent) directive parsing.
342 DK_NO_DIRECTIVE, // Placeholder
343 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
344 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
345 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
346 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
347 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
348 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
349 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
350 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
351 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
352 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
353 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
354 DK_ELSEIF, DK_ELSE, DK_ENDIF,
355 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
356 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
357 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
358 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
359 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
360 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
361 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
362 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
363 DK_SLEB128, DK_ULEB128,
368 /// \brief Maps directive name --> DirectiveKind enum, for
369 /// directives parsed by this class.
370 StringMap<DirectiveKind> DirectiveKindMap;
372 // ".ascii", ".asciz", ".string"
373 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
374 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
375 bool parseDirectiveOctaValue(); // ".octa"
376 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
377 bool parseDirectiveFill(); // ".fill"
378 bool parseDirectiveZero(); // ".zero"
379 // ".set", ".equ", ".equiv"
380 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
381 bool parseDirectiveOrg(); // ".org"
382 // ".align{,32}", ".p2align{,w,l}"
383 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
385 // ".file", ".line", ".loc", ".stabs"
386 bool parseDirectiveFile(SMLoc DirectiveLoc);
387 bool parseDirectiveLine();
388 bool parseDirectiveLoc();
389 bool parseDirectiveStabs();
392 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIWindowSave();
394 bool parseDirectiveCFISections();
395 bool parseDirectiveCFIStartProc();
396 bool parseDirectiveCFIEndProc();
397 bool parseDirectiveCFIDefCfaOffset();
398 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIAdjustCfaOffset();
400 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
404 bool parseDirectiveCFIRememberState();
405 bool parseDirectiveCFIRestoreState();
406 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
407 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
408 bool parseDirectiveCFIEscape();
409 bool parseDirectiveCFISignalFrame();
410 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
413 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
414 bool parseDirectiveEndMacro(StringRef Directive);
415 bool parseDirectiveMacro(SMLoc DirectiveLoc);
416 bool parseDirectiveMacrosOnOff(StringRef Directive);
418 // ".bundle_align_mode"
419 bool parseDirectiveBundleAlignMode();
421 bool parseDirectiveBundleLock();
423 bool parseDirectiveBundleUnlock();
426 bool parseDirectiveSpace(StringRef IDVal);
428 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
429 bool parseDirectiveLEB128(bool Signed);
431 /// \brief Parse a directive like ".globl" which
432 /// accepts a single symbol (which should be a label or an external).
433 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
435 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
437 bool parseDirectiveAbort(); // ".abort"
438 bool parseDirectiveInclude(); // ".include"
439 bool parseDirectiveIncbin(); // ".incbin"
441 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
442 // ".ifb" or ".ifnb", depending on ExpectBlank.
443 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
444 // ".ifc" or ".ifnc", depending on ExpectEqual.
445 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
446 // ".ifdef" or ".ifndef", depending on expect_defined
447 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
448 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
449 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
450 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
451 virtual bool parseEscapedString(std::string &Data);
453 const MCExpr *applyModifierToExpr(const MCExpr *E,
454 MCSymbolRefExpr::VariantKind Variant);
456 // Macro-like directives
457 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
458 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
459 raw_svector_ostream &OS);
460 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
461 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
462 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
463 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
465 // "_emit" or "__emit"
466 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
470 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
473 bool parseDirectiveEnd(SMLoc DirectiveLoc);
476 bool parseDirectiveErr(SMLoc DirectiveLoc);
478 void initializeDirectiveKindMap();
484 extern MCAsmParserExtension *createDarwinAsmParser();
485 extern MCAsmParserExtension *createELFAsmParser();
486 extern MCAsmParserExtension *createCOFFAsmParser();
490 enum { DEFAULT_ADDRSPACE = 0 };
492 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
493 const MCAsmInfo &_MAI)
494 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
495 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
496 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
497 ParsingInlineAsm(false) {
498 // Save the old handler.
499 SavedDiagHandler = SrcMgr.getDiagHandler();
500 SavedDiagContext = SrcMgr.getDiagContext();
501 // Set our own handler which calls the saved handler.
502 SrcMgr.setDiagHandler(DiagHandler, this);
503 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
505 // Initialize the platform / file format parser.
506 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
507 case MCObjectFileInfo::IsCOFF:
508 PlatformParser = createCOFFAsmParser();
509 PlatformParser->Initialize(*this);
511 case MCObjectFileInfo::IsMachO:
512 PlatformParser = createDarwinAsmParser();
513 PlatformParser->Initialize(*this);
516 case MCObjectFileInfo::IsELF:
517 PlatformParser = createELFAsmParser();
518 PlatformParser->Initialize(*this);
522 initializeDirectiveKindMap();
525 AsmParser::~AsmParser() {
526 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
528 // Destroy any macros.
529 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
532 delete it->getValue();
534 delete PlatformParser;
537 void AsmParser::printMacroInstantiations() {
538 // Print the active macro instantiation stack.
539 for (std::vector<MacroInstantiation *>::const_reverse_iterator
540 it = ActiveMacros.rbegin(),
541 ie = ActiveMacros.rend();
543 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
544 "while in macro instantiation");
547 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
548 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
549 printMacroInstantiations();
552 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
553 if (FatalAssemblerWarnings)
554 return Error(L, Msg, Ranges);
555 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
556 printMacroInstantiations();
560 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
562 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
563 printMacroInstantiations();
567 bool AsmParser::enterIncludeFile(const std::string &Filename) {
568 std::string IncludedFile;
569 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
575 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
580 /// Process the specified .incbin file by searching for it in the include paths
581 /// then just emitting the byte contents of the file to the streamer. This
582 /// returns true on failure.
583 bool AsmParser::processIncbinFile(const std::string &Filename) {
584 std::string IncludedFile;
585 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
589 // Pick up the bytes from the file and emit them.
590 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
594 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
595 if (InBuffer != -1) {
596 CurBuffer = InBuffer;
598 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
600 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
603 const AsmToken &AsmParser::Lex() {
604 const AsmToken *tok = &Lexer.Lex();
606 if (tok->is(AsmToken::Eof)) {
607 // If this is the end of an included file, pop the parent file off the
609 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
610 if (ParentIncludeLoc != SMLoc()) {
611 jumpToLoc(ParentIncludeLoc);
616 if (tok->is(AsmToken::Error))
617 Error(Lexer.getErrLoc(), Lexer.getErr());
622 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
623 // Create the initial section, if requested.
624 if (!NoInitialTextSection)
631 AsmCond StartingCondState = TheCondState;
633 // If we are generating dwarf for assembly source files save the initial text
634 // section and generate a .file directive.
635 if (getContext().getGenDwarfForAssembly()) {
636 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
637 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
638 getStreamer().EmitLabel(SectionStartSym);
639 getContext().setGenDwarfSectionStartSym(SectionStartSym);
640 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
642 getContext().getMainFileName());
645 // While we have input, parse each statement.
646 while (Lexer.isNot(AsmToken::Eof)) {
647 ParseStatementInfo Info;
648 if (!parseStatement(Info))
651 // We had an error, validate that one was emitted and recover by skipping to
653 assert(HadError && "Parse statement returned an error, but none emitted!");
654 eatToEndOfStatement();
657 if (TheCondState.TheCond != StartingCondState.TheCond ||
658 TheCondState.Ignore != StartingCondState.Ignore)
659 return TokError("unmatched .ifs or .elses");
661 // Check to see there are no empty DwarfFile slots.
662 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
663 getContext().getMCDwarfFiles();
664 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
665 if (!MCDwarfFiles[i])
666 TokError("unassigned file number: " + Twine(i) + " for .file directives");
669 // Check to see that all assembler local symbols were actually defined.
670 // Targets that don't do subsections via symbols may not want this, though,
671 // so conservatively exclude them. Only do this if we're finalizing, though,
672 // as otherwise we won't necessarilly have seen everything yet.
673 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
674 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
675 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
678 MCSymbol *Sym = i->getValue();
679 // Variable symbols may not be marked as defined, so check those
680 // explicitly. If we know it's a variable, we have a definition for
681 // the purposes of this check.
682 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
683 // FIXME: We would really like to refer back to where the symbol was
684 // first referenced for a source location. We need to add something
685 // to track that. Currently, we just point to the end of the file.
687 getLexer().getLoc(), SourceMgr::DK_Error,
688 "assembler local symbol '" + Sym->getName() + "' not defined");
692 // Finalize the output stream if there are no errors and if the client wants
694 if (!HadError && !NoFinalize)
700 void AsmParser::checkForValidSection() {
701 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
702 TokError("expected section directive before assembly directive");
707 /// \brief Throw away the rest of the line for testing purposes.
708 void AsmParser::eatToEndOfStatement() {
709 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
713 if (Lexer.is(AsmToken::EndOfStatement))
717 StringRef AsmParser::parseStringToEndOfStatement() {
718 const char *Start = getTok().getLoc().getPointer();
720 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
723 const char *End = getTok().getLoc().getPointer();
724 return StringRef(Start, End - Start);
727 StringRef AsmParser::parseStringToComma() {
728 const char *Start = getTok().getLoc().getPointer();
730 while (Lexer.isNot(AsmToken::EndOfStatement) &&
731 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
734 const char *End = getTok().getLoc().getPointer();
735 return StringRef(Start, End - Start);
738 /// \brief Parse a paren expression and return it.
739 /// NOTE: This assumes the leading '(' has already been consumed.
741 /// parenexpr ::= expr)
743 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
744 if (parseExpression(Res))
746 if (Lexer.isNot(AsmToken::RParen))
747 return TokError("expected ')' in parentheses expression");
748 EndLoc = Lexer.getTok().getEndLoc();
753 /// \brief Parse a bracket expression and return it.
754 /// NOTE: This assumes the leading '[' has already been consumed.
756 /// bracketexpr ::= expr]
758 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
759 if (parseExpression(Res))
761 if (Lexer.isNot(AsmToken::RBrac))
762 return TokError("expected ']' in brackets expression");
763 EndLoc = Lexer.getTok().getEndLoc();
768 /// \brief Parse a primary expression and return it.
769 /// primaryexpr ::= (parenexpr
770 /// primaryexpr ::= symbol
771 /// primaryexpr ::= number
772 /// primaryexpr ::= '.'
773 /// primaryexpr ::= ~,+,- primaryexpr
774 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
775 SMLoc FirstTokenLoc = getLexer().getLoc();
776 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
777 switch (FirstTokenKind) {
779 return TokError("unknown token in expression");
780 // If we have an error assume that we've already handled it.
781 case AsmToken::Error:
783 case AsmToken::Exclaim:
784 Lex(); // Eat the operator.
785 if (parsePrimaryExpr(Res, EndLoc))
787 Res = MCUnaryExpr::CreateLNot(Res, getContext());
789 case AsmToken::Dollar:
791 case AsmToken::String:
792 case AsmToken::Identifier: {
793 StringRef Identifier;
794 if (parseIdentifier(Identifier)) {
795 if (FirstTokenKind == AsmToken::Dollar) {
796 if (Lexer.getMAI().getDollarIsPC()) {
797 // This is a '$' reference, which references the current PC. Emit a
798 // temporary label to the streamer and refer to it.
799 MCSymbol *Sym = Ctx.CreateTempSymbol();
801 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
803 EndLoc = FirstTokenLoc;
806 return Error(FirstTokenLoc, "invalid token in expression");
810 // Parse symbol variant
811 std::pair<StringRef, StringRef> Split;
812 if (!MAI.useParensForSymbolVariant()) {
813 Split = Identifier.split('@');
814 } else if (Lexer.is(AsmToken::LParen)) {
815 Lexer.Lex(); // eat (
817 parseIdentifier(VName);
818 if (Lexer.isNot(AsmToken::RParen)) {
819 return Error(Lexer.getTok().getLoc(),
820 "unexpected token in variant, expected ')'");
822 Lexer.Lex(); // eat )
823 Split = std::make_pair(Identifier, VName);
826 EndLoc = SMLoc::getFromPointer(Identifier.end());
828 // This is a symbol reference.
829 StringRef SymbolName = Identifier;
830 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
832 // Lookup the symbol variant if used.
833 if (Split.second.size()) {
834 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
835 if (Variant != MCSymbolRefExpr::VK_Invalid) {
836 SymbolName = Split.first;
837 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
838 Variant = MCSymbolRefExpr::VK_None;
840 return Error(SMLoc::getFromPointer(Split.second.begin()),
841 "invalid variant '" + Split.second + "'");
845 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
847 // If this is an absolute variable reference, substitute it now to preserve
848 // semantics in the face of reassignment.
849 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
851 return Error(EndLoc, "unexpected modifier on variable reference");
853 Res = Sym->getVariableValue();
857 // Otherwise create a symbol ref.
858 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
861 case AsmToken::BigNum:
862 return TokError("literal value out of range for directive");
863 case AsmToken::Integer: {
864 SMLoc Loc = getTok().getLoc();
865 int64_t IntVal = getTok().getIntVal();
866 Res = MCConstantExpr::Create(IntVal, getContext());
867 EndLoc = Lexer.getTok().getEndLoc();
869 // Look for 'b' or 'f' following an Integer as a directional label
870 if (Lexer.getKind() == AsmToken::Identifier) {
871 StringRef IDVal = getTok().getString();
872 // Lookup the symbol variant if used.
873 std::pair<StringRef, StringRef> Split = IDVal.split('@');
874 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
875 if (Split.first.size() != IDVal.size()) {
876 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
877 if (Variant == MCSymbolRefExpr::VK_Invalid) {
878 Variant = MCSymbolRefExpr::VK_None;
879 return TokError("invalid variant '" + Split.second + "'");
883 if (IDVal == "f" || IDVal == "b") {
885 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
886 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
887 if (IDVal == "b" && Sym->isUndefined())
888 return Error(Loc, "invalid reference to undefined symbol");
889 EndLoc = Lexer.getTok().getEndLoc();
890 Lex(); // Eat identifier.
895 case AsmToken::Real: {
896 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
897 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
898 Res = MCConstantExpr::Create(IntVal, getContext());
899 EndLoc = Lexer.getTok().getEndLoc();
903 case AsmToken::Dot: {
904 // This is a '.' reference, which references the current PC. Emit a
905 // temporary label to the streamer and refer to it.
906 MCSymbol *Sym = Ctx.CreateTempSymbol();
908 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
909 EndLoc = Lexer.getTok().getEndLoc();
910 Lex(); // Eat identifier.
913 case AsmToken::LParen:
914 Lex(); // Eat the '('.
915 return parseParenExpr(Res, EndLoc);
916 case AsmToken::LBrac:
917 if (!PlatformParser->HasBracketExpressions())
918 return TokError("brackets expression not supported on this target");
919 Lex(); // Eat the '['.
920 return parseBracketExpr(Res, EndLoc);
921 case AsmToken::Minus:
922 Lex(); // Eat the operator.
923 if (parsePrimaryExpr(Res, EndLoc))
925 Res = MCUnaryExpr::CreateMinus(Res, getContext());
928 Lex(); // Eat the operator.
929 if (parsePrimaryExpr(Res, EndLoc))
931 Res = MCUnaryExpr::CreatePlus(Res, getContext());
933 case AsmToken::Tilde:
934 Lex(); // Eat the operator.
935 if (parsePrimaryExpr(Res, EndLoc))
937 Res = MCUnaryExpr::CreateNot(Res, getContext());
942 bool AsmParser::parseExpression(const MCExpr *&Res) {
944 return parseExpression(Res, EndLoc);
948 AsmParser::applyModifierToExpr(const MCExpr *E,
949 MCSymbolRefExpr::VariantKind Variant) {
950 // Ask the target implementation about this expression first.
951 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
954 // Recurse over the given expression, rebuilding it to apply the given variant
955 // if there is exactly one symbol.
956 switch (E->getKind()) {
958 case MCExpr::Constant:
961 case MCExpr::SymbolRef: {
962 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
964 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
965 TokError("invalid variant on expression '" + getTok().getIdentifier() +
966 "' (already modified)");
970 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
973 case MCExpr::Unary: {
974 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
975 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
978 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
981 case MCExpr::Binary: {
982 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
983 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
984 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
994 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
998 llvm_unreachable("Invalid expression kind!");
1001 /// \brief Parse an expression and return it.
1003 /// expr ::= expr &&,|| expr -> lowest.
1004 /// expr ::= expr |,^,&,! expr
1005 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1006 /// expr ::= expr <<,>> expr
1007 /// expr ::= expr +,- expr
1008 /// expr ::= expr *,/,% expr -> highest.
1009 /// expr ::= primaryexpr
1011 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1012 // Parse the expression.
1014 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1017 // As a special case, we support 'a op b @ modifier' by rewriting the
1018 // expression to include the modifier. This is inefficient, but in general we
1019 // expect users to use 'a@modifier op b'.
1020 if (Lexer.getKind() == AsmToken::At) {
1023 if (Lexer.isNot(AsmToken::Identifier))
1024 return TokError("unexpected symbol modifier following '@'");
1026 MCSymbolRefExpr::VariantKind Variant =
1027 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1028 if (Variant == MCSymbolRefExpr::VK_Invalid)
1029 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1031 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1033 return TokError("invalid modifier '" + getTok().getIdentifier() +
1034 "' (no symbols present)");
1041 // Try to constant fold it up front, if possible.
1043 if (Res->EvaluateAsAbsolute(Value))
1044 Res = MCConstantExpr::Create(Value, getContext());
1049 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1051 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1054 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1057 SMLoc StartLoc = Lexer.getLoc();
1058 if (parseExpression(Expr))
1061 if (!Expr->EvaluateAsAbsolute(Res))
1062 return Error(StartLoc, "expected absolute expression");
1067 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1068 MCBinaryExpr::Opcode &Kind) {
1071 return 0; // not a binop.
1073 // Lowest Precedence: &&, ||
1074 case AsmToken::AmpAmp:
1075 Kind = MCBinaryExpr::LAnd;
1077 case AsmToken::PipePipe:
1078 Kind = MCBinaryExpr::LOr;
1081 // Low Precedence: |, &, ^
1083 // FIXME: gas seems to support '!' as an infix operator?
1084 case AsmToken::Pipe:
1085 Kind = MCBinaryExpr::Or;
1087 case AsmToken::Caret:
1088 Kind = MCBinaryExpr::Xor;
1091 Kind = MCBinaryExpr::And;
1094 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1095 case AsmToken::EqualEqual:
1096 Kind = MCBinaryExpr::EQ;
1098 case AsmToken::ExclaimEqual:
1099 case AsmToken::LessGreater:
1100 Kind = MCBinaryExpr::NE;
1102 case AsmToken::Less:
1103 Kind = MCBinaryExpr::LT;
1105 case AsmToken::LessEqual:
1106 Kind = MCBinaryExpr::LTE;
1108 case AsmToken::Greater:
1109 Kind = MCBinaryExpr::GT;
1111 case AsmToken::GreaterEqual:
1112 Kind = MCBinaryExpr::GTE;
1115 // Intermediate Precedence: <<, >>
1116 case AsmToken::LessLess:
1117 Kind = MCBinaryExpr::Shl;
1119 case AsmToken::GreaterGreater:
1120 Kind = MCBinaryExpr::Shr;
1123 // High Intermediate Precedence: +, -
1124 case AsmToken::Plus:
1125 Kind = MCBinaryExpr::Add;
1127 case AsmToken::Minus:
1128 Kind = MCBinaryExpr::Sub;
1131 // Highest Precedence: *, /, %
1132 case AsmToken::Star:
1133 Kind = MCBinaryExpr::Mul;
1135 case AsmToken::Slash:
1136 Kind = MCBinaryExpr::Div;
1138 case AsmToken::Percent:
1139 Kind = MCBinaryExpr::Mod;
1144 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1145 /// Res contains the LHS of the expression on input.
1146 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1149 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1150 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1152 // If the next token is lower precedence than we are allowed to eat, return
1153 // successfully with what we ate already.
1154 if (TokPrec < Precedence)
1159 // Eat the next primary expression.
1161 if (parsePrimaryExpr(RHS, EndLoc))
1164 // If BinOp binds less tightly with RHS than the operator after RHS, let
1165 // the pending operator take RHS as its LHS.
1166 MCBinaryExpr::Opcode Dummy;
1167 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1168 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1171 // Merge LHS and RHS according to operator.
1172 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1177 /// ::= EndOfStatement
1178 /// ::= Label* Directive ...Operands... EndOfStatement
1179 /// ::= Label* Identifier OperandList* EndOfStatement
1180 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1181 if (Lexer.is(AsmToken::EndOfStatement)) {
1187 // Statements always start with an identifier or are a full line comment.
1188 AsmToken ID = getTok();
1189 SMLoc IDLoc = ID.getLoc();
1191 int64_t LocalLabelVal = -1;
1192 // A full line comment is a '#' as the first token.
1193 if (Lexer.is(AsmToken::Hash))
1194 return parseCppHashLineFilenameComment(IDLoc);
1196 // Allow an integer followed by a ':' as a directional local label.
1197 if (Lexer.is(AsmToken::Integer)) {
1198 LocalLabelVal = getTok().getIntVal();
1199 if (LocalLabelVal < 0) {
1200 if (!TheCondState.Ignore)
1201 return TokError("unexpected token at start of statement");
1204 IDVal = getTok().getString();
1205 Lex(); // Consume the integer token to be used as an identifier token.
1206 if (Lexer.getKind() != AsmToken::Colon) {
1207 if (!TheCondState.Ignore)
1208 return TokError("unexpected token at start of statement");
1211 } else if (Lexer.is(AsmToken::Dot)) {
1212 // Treat '.' as a valid identifier in this context.
1215 } else if (parseIdentifier(IDVal)) {
1216 if (!TheCondState.Ignore)
1217 return TokError("unexpected token at start of statement");
1221 // Handle conditional assembly here before checking for skipping. We
1222 // have to do this so that .endif isn't skipped in a ".if 0" block for
1224 StringMap<DirectiveKind>::const_iterator DirKindIt =
1225 DirectiveKindMap.find(IDVal);
1226 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1228 : DirKindIt->getValue();
1233 return parseDirectiveIf(IDLoc);
1235 return parseDirectiveIfb(IDLoc, true);
1237 return parseDirectiveIfb(IDLoc, false);
1239 return parseDirectiveIfc(IDLoc, true);
1241 return parseDirectiveIfc(IDLoc, false);
1243 return parseDirectiveIfdef(IDLoc, true);
1246 return parseDirectiveIfdef(IDLoc, false);
1248 return parseDirectiveElseIf(IDLoc);
1250 return parseDirectiveElse(IDLoc);
1252 return parseDirectiveEndIf(IDLoc);
1255 // Ignore the statement if in the middle of inactive conditional
1257 if (TheCondState.Ignore) {
1258 eatToEndOfStatement();
1262 // FIXME: Recurse on local labels?
1264 // See what kind of statement we have.
1265 switch (Lexer.getKind()) {
1266 case AsmToken::Colon: {
1267 checkForValidSection();
1269 // identifier ':' -> Label.
1272 // Diagnose attempt to use '.' as a label.
1274 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1276 // Diagnose attempt to use a variable as a label.
1278 // FIXME: Diagnostics. Note the location of the definition as a label.
1279 // FIXME: This doesn't diagnose assignment to a symbol which has been
1280 // implicitly marked as external.
1282 if (LocalLabelVal == -1)
1283 Sym = getContext().GetOrCreateSymbol(IDVal);
1285 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1286 if (!Sym->isUndefined() || Sym->isVariable())
1287 return Error(IDLoc, "invalid symbol redefinition");
1290 if (!ParsingInlineAsm)
1293 // If we are generating dwarf for assembly source files then gather the
1294 // info to make a dwarf label entry for this label if needed.
1295 if (getContext().getGenDwarfForAssembly())
1296 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1299 getTargetParser().onLabelParsed(Sym);
1301 // Consume any end of statement token, if present, to avoid spurious
1302 // AddBlankLine calls().
1303 if (Lexer.is(AsmToken::EndOfStatement)) {
1305 if (Lexer.is(AsmToken::Eof))
1312 case AsmToken::Equal:
1313 // identifier '=' ... -> assignment statement
1316 return parseAssignment(IDVal, true);
1318 default: // Normal instruction or directive.
1322 // If macros are enabled, check to see if this is a macro instantiation.
1323 if (areMacrosEnabled())
1324 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1325 return handleMacroEntry(M, IDLoc);
1328 // Otherwise, we have a normal instruction or directive.
1330 // Directives start with "."
1331 if (IDVal[0] == '.' && IDVal != ".") {
1332 // There are several entities interested in parsing directives:
1334 // 1. The target-specific assembly parser. Some directives are target
1335 // specific or may potentially behave differently on certain targets.
1336 // 2. Asm parser extensions. For example, platform-specific parsers
1337 // (like the ELF parser) register themselves as extensions.
1338 // 3. The generic directive parser implemented by this class. These are
1339 // all the directives that behave in a target and platform independent
1340 // manner, or at least have a default behavior that's shared between
1341 // all targets and platforms.
1343 // First query the target-specific parser. It will return 'true' if it
1344 // isn't interested in this directive.
1345 if (!getTargetParser().ParseDirective(ID))
1348 // Next, check the extension directive map to see if any extension has
1349 // registered itself to parse this directive.
1350 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1351 ExtensionDirectiveMap.lookup(IDVal);
1353 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1355 // Finally, if no one else is interested in this directive, it must be
1356 // generic and familiar to this class.
1362 return parseDirectiveSet(IDVal, true);
1364 return parseDirectiveSet(IDVal, false);
1366 return parseDirectiveAscii(IDVal, false);
1369 return parseDirectiveAscii(IDVal, true);
1371 return parseDirectiveValue(1);
1375 return parseDirectiveValue(2);
1379 return parseDirectiveValue(4);
1382 return parseDirectiveValue(8);
1384 return parseDirectiveOctaValue();
1387 return parseDirectiveRealValue(APFloat::IEEEsingle);
1389 return parseDirectiveRealValue(APFloat::IEEEdouble);
1391 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1392 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1395 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1396 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1399 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1401 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1403 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1405 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1407 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1409 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1411 return parseDirectiveOrg();
1413 return parseDirectiveFill();
1415 return parseDirectiveZero();
1417 eatToEndOfStatement(); // .extern is the default, ignore it.
1421 return parseDirectiveSymbolAttribute(MCSA_Global);
1422 case DK_LAZY_REFERENCE:
1423 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1424 case DK_NO_DEAD_STRIP:
1425 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1426 case DK_SYMBOL_RESOLVER:
1427 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1428 case DK_PRIVATE_EXTERN:
1429 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1431 return parseDirectiveSymbolAttribute(MCSA_Reference);
1432 case DK_WEAK_DEFINITION:
1433 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1434 case DK_WEAK_REFERENCE:
1435 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1436 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1437 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1440 return parseDirectiveComm(/*IsLocal=*/false);
1442 return parseDirectiveComm(/*IsLocal=*/true);
1444 return parseDirectiveAbort();
1446 return parseDirectiveInclude();
1448 return parseDirectiveIncbin();
1451 return TokError(Twine(IDVal) + " not supported yet");
1453 return parseDirectiveRept(IDLoc, IDVal);
1455 return parseDirectiveIrp(IDLoc);
1457 return parseDirectiveIrpc(IDLoc);
1459 return parseDirectiveEndr(IDLoc);
1460 case DK_BUNDLE_ALIGN_MODE:
1461 return parseDirectiveBundleAlignMode();
1462 case DK_BUNDLE_LOCK:
1463 return parseDirectiveBundleLock();
1464 case DK_BUNDLE_UNLOCK:
1465 return parseDirectiveBundleUnlock();
1467 return parseDirectiveLEB128(true);
1469 return parseDirectiveLEB128(false);
1472 return parseDirectiveSpace(IDVal);
1474 return parseDirectiveFile(IDLoc);
1476 return parseDirectiveLine();
1478 return parseDirectiveLoc();
1480 return parseDirectiveStabs();
1481 case DK_CFI_SECTIONS:
1482 return parseDirectiveCFISections();
1483 case DK_CFI_STARTPROC:
1484 return parseDirectiveCFIStartProc();
1485 case DK_CFI_ENDPROC:
1486 return parseDirectiveCFIEndProc();
1487 case DK_CFI_DEF_CFA:
1488 return parseDirectiveCFIDefCfa(IDLoc);
1489 case DK_CFI_DEF_CFA_OFFSET:
1490 return parseDirectiveCFIDefCfaOffset();
1491 case DK_CFI_ADJUST_CFA_OFFSET:
1492 return parseDirectiveCFIAdjustCfaOffset();
1493 case DK_CFI_DEF_CFA_REGISTER:
1494 return parseDirectiveCFIDefCfaRegister(IDLoc);
1496 return parseDirectiveCFIOffset(IDLoc);
1497 case DK_CFI_REL_OFFSET:
1498 return parseDirectiveCFIRelOffset(IDLoc);
1499 case DK_CFI_PERSONALITY:
1500 return parseDirectiveCFIPersonalityOrLsda(true);
1502 return parseDirectiveCFIPersonalityOrLsda(false);
1503 case DK_CFI_REMEMBER_STATE:
1504 return parseDirectiveCFIRememberState();
1505 case DK_CFI_RESTORE_STATE:
1506 return parseDirectiveCFIRestoreState();
1507 case DK_CFI_SAME_VALUE:
1508 return parseDirectiveCFISameValue(IDLoc);
1509 case DK_CFI_RESTORE:
1510 return parseDirectiveCFIRestore(IDLoc);
1512 return parseDirectiveCFIEscape();
1513 case DK_CFI_SIGNAL_FRAME:
1514 return parseDirectiveCFISignalFrame();
1515 case DK_CFI_UNDEFINED:
1516 return parseDirectiveCFIUndefined(IDLoc);
1517 case DK_CFI_REGISTER:
1518 return parseDirectiveCFIRegister(IDLoc);
1519 case DK_CFI_WINDOW_SAVE:
1520 return parseDirectiveCFIWindowSave();
1523 return parseDirectiveMacrosOnOff(IDVal);
1525 return parseDirectiveMacro(IDLoc);
1528 return parseDirectiveEndMacro(IDVal);
1530 return parseDirectivePurgeMacro(IDLoc);
1532 return parseDirectiveEnd(IDLoc);
1534 return parseDirectiveErr(IDLoc);
1537 return Error(IDLoc, "unknown directive");
1540 // __asm _emit or __asm __emit
1541 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1542 IDVal == "_EMIT" || IDVal == "__EMIT"))
1543 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1546 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1547 return parseDirectiveMSAlign(IDLoc, Info);
1549 checkForValidSection();
1551 // Canonicalize the opcode to lower case.
1552 std::string OpcodeStr = IDVal.lower();
1553 ParseInstructionInfo IInfo(Info.AsmRewrites);
1554 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1555 Info.ParsedOperands);
1556 Info.ParseError = HadError;
1558 // Dump the parsed representation, if requested.
1559 if (getShowParsedOperands()) {
1560 SmallString<256> Str;
1561 raw_svector_ostream OS(Str);
1562 OS << "parsed instruction: [";
1563 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1566 Info.ParsedOperands[i]->print(OS);
1570 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1573 // If we are generating dwarf for assembly source files and the current
1574 // section is the initial text section then generate a .loc directive for
1576 if (!HadError && getContext().getGenDwarfForAssembly() &&
1577 getContext().getGenDwarfSection() ==
1578 getStreamer().getCurrentSection().first) {
1580 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1582 // If we previously parsed a cpp hash file line comment then make sure the
1583 // current Dwarf File is for the CppHashFilename if not then emit the
1584 // Dwarf File table for it and adjust the line number for the .loc.
1585 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1586 getContext().getMCDwarfFiles();
1587 if (CppHashFilename.size() != 0) {
1588 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1590 getStreamer().EmitDwarfFileDirective(
1591 getContext().nextGenDwarfFileNumber(), StringRef(),
1594 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1595 // cache with the different Loc from the call above we save the last
1596 // info we queried here with SrcMgr.FindLineNumber().
1597 unsigned CppHashLocLineNo;
1598 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1599 CppHashLocLineNo = LastQueryLine;
1601 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1602 LastQueryLine = CppHashLocLineNo;
1603 LastQueryIDLoc = CppHashLoc;
1604 LastQueryBuffer = CppHashBuf;
1606 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1609 getStreamer().EmitDwarfLocDirective(
1610 getContext().getGenDwarfFileNumber(), Line, 0,
1611 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1615 // If parsing succeeded, match the instruction.
1618 HadError = getTargetParser().MatchAndEmitInstruction(
1619 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1623 // Don't skip the rest of the line, the instruction parser is responsible for
1628 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1629 /// since they may not be able to be tokenized to get to the end of line token.
1630 void AsmParser::eatToEndOfLine() {
1631 if (!Lexer.is(AsmToken::EndOfStatement))
1632 Lexer.LexUntilEndOfLine();
1637 /// parseCppHashLineFilenameComment as this:
1638 /// ::= # number "filename"
1639 /// or just as a full line comment if it doesn't have a number and a string.
1640 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1641 Lex(); // Eat the hash token.
1643 if (getLexer().isNot(AsmToken::Integer)) {
1644 // Consume the line since in cases it is not a well-formed line directive,
1645 // as if were simply a full line comment.
1650 int64_t LineNumber = getTok().getIntVal();
1653 if (getLexer().isNot(AsmToken::String)) {
1658 StringRef Filename = getTok().getString();
1659 // Get rid of the enclosing quotes.
1660 Filename = Filename.substr(1, Filename.size() - 2);
1662 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1664 CppHashFilename = Filename;
1665 CppHashLineNumber = LineNumber;
1666 CppHashBuf = CurBuffer;
1668 // Ignore any trailing characters, they're just comment.
1673 /// \brief will use the last parsed cpp hash line filename comment
1674 /// for the Filename and LineNo if any in the diagnostic.
1675 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1676 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1677 raw_ostream &OS = errs();
1679 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1680 const SMLoc &DiagLoc = Diag.getLoc();
1681 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1682 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1684 // Like SourceMgr::printMessage() we need to print the include stack if any
1685 // before printing the message.
1686 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1687 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1688 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1689 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1692 // If we have not parsed a cpp hash line filename comment or the source
1693 // manager changed or buffer changed (like in a nested include) then just
1694 // print the normal diagnostic using its Filename and LineNo.
1695 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1696 DiagBuf != CppHashBuf) {
1697 if (Parser->SavedDiagHandler)
1698 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1704 // Use the CppHashFilename and calculate a line number based on the
1705 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1707 const std::string &Filename = Parser->CppHashFilename;
1709 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1710 int CppHashLocLineNo =
1711 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1713 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1715 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1716 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1717 Diag.getLineContents(), Diag.getRanges());
1719 if (Parser->SavedDiagHandler)
1720 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1722 NewDiag.print(0, OS);
1725 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1726 // difference being that that function accepts '@' as part of identifiers and
1727 // we can't do that. AsmLexer.cpp should probably be changed to handle
1728 // '@' as a special case when needed.
1729 static bool isIdentifierChar(char c) {
1730 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1734 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1735 ArrayRef<MCAsmMacroParameter> Parameters,
1736 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1737 unsigned NParameters = Parameters.size();
1738 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1739 return Error(L, "Wrong number of arguments");
1741 // A macro without parameters is handled differently on Darwin:
1742 // gas accepts no arguments and does no substitutions
1743 while (!Body.empty()) {
1744 // Scan for the next substitution.
1745 std::size_t End = Body.size(), Pos = 0;
1746 for (; Pos != End; ++Pos) {
1747 // Check for a substitution or escape.
1748 if (IsDarwin && !NParameters) {
1749 // This macro has no parameters, look for $0, $1, etc.
1750 if (Body[Pos] != '$' || Pos + 1 == End)
1753 char Next = Body[Pos + 1];
1754 if (Next == '$' || Next == 'n' ||
1755 isdigit(static_cast<unsigned char>(Next)))
1758 // This macro has parameters, look for \foo, \bar, etc.
1759 if (Body[Pos] == '\\' && Pos + 1 != End)
1765 OS << Body.slice(0, Pos);
1767 // Check if we reached the end.
1771 if (IsDarwin && !NParameters) {
1772 switch (Body[Pos + 1]) {
1778 // $n => number of arguments
1783 // $[0-9] => argument
1785 // Missing arguments are ignored.
1786 unsigned Index = Body[Pos + 1] - '0';
1787 if (Index >= A.size())
1790 // Otherwise substitute with the token values, with spaces eliminated.
1791 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1792 ie = A[Index].end();
1794 OS << it->getString();
1800 unsigned I = Pos + 1;
1801 while (isIdentifierChar(Body[I]) && I + 1 != End)
1804 const char *Begin = Body.data() + Pos + 1;
1805 StringRef Argument(Begin, I - (Pos + 1));
1807 for (; Index < NParameters; ++Index)
1808 if (Parameters[Index].Name == Argument)
1811 if (Index == NParameters) {
1812 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1815 OS << '\\' << Argument;
1819 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1820 ie = A[Index].end();
1822 if (it->getKind() == AsmToken::String)
1823 OS << it->getStringContents();
1825 OS << it->getString();
1827 Pos += 1 + Argument.size();
1830 // Update the scan point.
1831 Body = Body.substr(Pos);
1837 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1838 SMLoc EL, MemoryBuffer *I)
1839 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1842 static bool isOperator(AsmToken::TokenKind kind) {
1846 case AsmToken::Plus:
1847 case AsmToken::Minus:
1848 case AsmToken::Tilde:
1849 case AsmToken::Slash:
1850 case AsmToken::Star:
1852 case AsmToken::Equal:
1853 case AsmToken::EqualEqual:
1854 case AsmToken::Pipe:
1855 case AsmToken::PipePipe:
1856 case AsmToken::Caret:
1858 case AsmToken::AmpAmp:
1859 case AsmToken::Exclaim:
1860 case AsmToken::ExclaimEqual:
1861 case AsmToken::Percent:
1862 case AsmToken::Less:
1863 case AsmToken::LessEqual:
1864 case AsmToken::LessLess:
1865 case AsmToken::LessGreater:
1866 case AsmToken::Greater:
1867 case AsmToken::GreaterEqual:
1868 case AsmToken::GreaterGreater:
1874 class AsmLexerSkipSpaceRAII {
1876 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1877 Lexer.setSkipSpace(SkipSpace);
1880 ~AsmLexerSkipSpaceRAII() {
1881 Lexer.setSkipSpace(true);
1889 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA) {
1890 unsigned ParenLevel = 0;
1891 unsigned AddTokens = 0;
1893 // Darwin doesn't use spaces to delmit arguments.
1894 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1897 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1898 return TokError("unexpected token in macro instantiation");
1900 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1903 if (Lexer.is(AsmToken::Space)) {
1904 Lex(); // Eat spaces
1906 // Spaces can delimit parameters, but could also be part an expression.
1907 // If the token after a space is an operator, add the token and the next
1908 // one into this argument
1910 if (isOperator(Lexer.getKind())) {
1911 // Check to see whether the token is used as an operator,
1912 // or part of an identifier
1913 const char *NextChar = getTok().getEndLoc().getPointer();
1914 if (*NextChar == ' ')
1918 if (!AddTokens && ParenLevel == 0) {
1924 // handleMacroEntry relies on not advancing the lexer here
1925 // to be able to fill in the remaining default parameter values
1926 if (Lexer.is(AsmToken::EndOfStatement))
1929 // Adjust the current parentheses level.
1930 if (Lexer.is(AsmToken::LParen))
1932 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1935 // Append the token to the current argument list.
1936 MA.push_back(getTok());
1942 if (ParenLevel != 0)
1943 return TokError("unbalanced parentheses in macro argument");
1947 // Parse the macro instantiation arguments.
1948 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1949 MCAsmMacroArguments &A) {
1950 const unsigned NParameters = M ? M->Parameters.size() : 0;
1951 bool NamedParametersFound = false;
1952 SmallVector<SMLoc, 4> FALocs;
1954 A.resize(NParameters);
1955 FALocs.resize(NParameters);
1957 // Parse two kinds of macro invocations:
1958 // - macros defined without any parameters accept an arbitrary number of them
1959 // - macros defined with parameters accept at most that many of them
1960 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1962 SMLoc IDLoc = Lexer.getLoc();
1963 MCAsmMacroParameter FA;
1965 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1966 if (parseIdentifier(FA.Name)) {
1967 Error(IDLoc, "invalid argument identifier for formal argument");
1968 eatToEndOfStatement();
1972 if (!Lexer.is(AsmToken::Equal)) {
1973 TokError("expected '=' after formal parameter identifier");
1974 eatToEndOfStatement();
1979 NamedParametersFound = true;
1982 if (NamedParametersFound && FA.Name.empty()) {
1983 Error(IDLoc, "cannot mix positional and keyword arguments");
1984 eatToEndOfStatement();
1988 if (parseMacroArgument(FA.Value))
1991 unsigned PI = Parameter;
1992 if (!FA.Name.empty()) {
1994 for (FAI = 0; FAI < NParameters; ++FAI)
1995 if (M->Parameters[FAI].Name == FA.Name)
1998 if (FAI >= NParameters) {
2000 "parameter named '" + FA.Name + "' does not exist for macro '" +
2007 if (!FA.Value.empty()) {
2012 if (FALocs.size() <= PI)
2013 FALocs.resize(PI + 1);
2015 FALocs[PI] = Lexer.getLoc();
2018 // At the end of the statement, fill in remaining arguments that have
2019 // default values. If there aren't any, then the next argument is
2020 // required but missing
2021 if (Lexer.is(AsmToken::EndOfStatement)) {
2022 bool Failure = false;
2023 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2024 if (A[FAI].empty()) {
2025 if (M->Parameters[FAI].Required) {
2026 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2027 "missing value for required parameter "
2028 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2032 if (!M->Parameters[FAI].Value.empty())
2033 A[FAI] = M->Parameters[FAI].Value;
2039 if (Lexer.is(AsmToken::Comma))
2043 return TokError("too many positional arguments");
2046 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2047 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2048 return (I == MacroMap.end()) ? NULL : I->getValue();
2051 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2052 MacroMap[Name] = new MCAsmMacro(Macro);
2055 void AsmParser::undefineMacro(StringRef Name) {
2056 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2057 if (I != MacroMap.end()) {
2058 delete I->getValue();
2063 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2064 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2065 // this, although we should protect against infinite loops.
2066 if (ActiveMacros.size() == 20)
2067 return TokError("macros cannot be nested more than 20 levels deep");
2069 MCAsmMacroArguments A;
2070 if (parseMacroArguments(M, A))
2073 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2074 // to hold the macro body with substitutions.
2075 SmallString<256> Buf;
2076 StringRef Body = M->Body;
2077 raw_svector_ostream OS(Buf);
2079 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2082 // We include the .endmacro in the buffer as our cue to exit the macro
2084 OS << ".endmacro\n";
2086 MemoryBuffer *Instantiation =
2087 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2089 // Create the macro instantiation object and add to the current macro
2090 // instantiation stack.
2091 MacroInstantiation *MI = new MacroInstantiation(
2092 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2093 ActiveMacros.push_back(MI);
2095 // Jump to the macro instantiation and prime the lexer.
2096 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2097 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2103 void AsmParser::handleMacroExit() {
2104 // Jump to the EndOfStatement we should return to, and consume it.
2105 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2108 // Pop the instantiation entry.
2109 delete ActiveMacros.back();
2110 ActiveMacros.pop_back();
2113 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2114 switch (Value->getKind()) {
2115 case MCExpr::Binary: {
2116 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2117 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2119 case MCExpr::Target:
2120 case MCExpr::Constant:
2122 case MCExpr::SymbolRef: {
2124 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2126 return isUsedIn(Sym, S.getVariableValue());
2130 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2133 llvm_unreachable("Unknown expr kind!");
2136 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2138 // FIXME: Use better location, we should use proper tokens.
2139 SMLoc EqualLoc = Lexer.getLoc();
2141 const MCExpr *Value;
2142 if (parseExpression(Value))
2145 // Note: we don't count b as used in "a = b". This is to allow
2149 if (Lexer.isNot(AsmToken::EndOfStatement))
2150 return TokError("unexpected token in assignment");
2152 // Eat the end of statement marker.
2155 // Validate that the LHS is allowed to be a variable (either it has not been
2156 // used as a symbol, or it is an absolute symbol).
2157 MCSymbol *Sym = getContext().LookupSymbol(Name);
2159 // Diagnose assignment to a label.
2161 // FIXME: Diagnostics. Note the location of the definition as a label.
2162 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2163 if (isUsedIn(Sym, Value))
2164 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2165 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2166 ; // Allow redefinitions of undefined symbols only used in directives.
2167 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2168 ; // Allow redefinitions of variables that haven't yet been used.
2169 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2170 return Error(EqualLoc, "redefinition of '" + Name + "'");
2171 else if (!Sym->isVariable())
2172 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2173 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2174 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2177 // Don't count these checks as uses.
2178 Sym->setUsed(false);
2179 } else if (Name == ".") {
2180 if (Out.EmitValueToOffset(Value, 0)) {
2181 Error(EqualLoc, "expected absolute expression");
2182 eatToEndOfStatement();
2186 Sym = getContext().GetOrCreateSymbol(Name);
2188 // Do the assignment.
2189 Out.EmitAssignment(Sym, Value);
2191 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2196 /// parseIdentifier:
2199 bool AsmParser::parseIdentifier(StringRef &Res) {
2200 // The assembler has relaxed rules for accepting identifiers, in particular we
2201 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2202 // separate tokens. At this level, we have already lexed so we cannot (currently)
2203 // handle this as a context dependent token, instead we detect adjacent tokens
2204 // and return the combined identifier.
2205 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2206 SMLoc PrefixLoc = getLexer().getLoc();
2208 // Consume the prefix character, and check for a following identifier.
2210 if (Lexer.isNot(AsmToken::Identifier))
2213 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2214 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2217 // Construct the joined identifier and consume the token.
2219 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2224 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2227 Res = getTok().getIdentifier();
2229 Lex(); // Consume the identifier token.
2234 /// parseDirectiveSet:
2235 /// ::= .equ identifier ',' expression
2236 /// ::= .equiv identifier ',' expression
2237 /// ::= .set identifier ',' expression
2238 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2241 if (parseIdentifier(Name))
2242 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2244 if (getLexer().isNot(AsmToken::Comma))
2245 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2248 return parseAssignment(Name, allow_redef, true);
2251 bool AsmParser::parseEscapedString(std::string &Data) {
2252 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2255 StringRef Str = getTok().getStringContents();
2256 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2257 if (Str[i] != '\\') {
2262 // Recognize escaped characters. Note that this escape semantics currently
2263 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2266 return TokError("unexpected backslash at end of string");
2268 // Recognize octal sequences.
2269 if ((unsigned)(Str[i] - '0') <= 7) {
2270 // Consume up to three octal characters.
2271 unsigned Value = Str[i] - '0';
2273 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2275 Value = Value * 8 + (Str[i] - '0');
2277 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2279 Value = Value * 8 + (Str[i] - '0');
2284 return TokError("invalid octal escape sequence (out of range)");
2286 Data += (unsigned char)Value;
2290 // Otherwise recognize individual escapes.
2293 // Just reject invalid escape sequences for now.
2294 return TokError("invalid escape sequence (unrecognized character)");
2296 case 'b': Data += '\b'; break;
2297 case 'f': Data += '\f'; break;
2298 case 'n': Data += '\n'; break;
2299 case 'r': Data += '\r'; break;
2300 case 't': Data += '\t'; break;
2301 case '"': Data += '"'; break;
2302 case '\\': Data += '\\'; break;
2309 /// parseDirectiveAscii:
2310 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2311 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2312 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2313 checkForValidSection();
2316 if (getLexer().isNot(AsmToken::String))
2317 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2320 if (parseEscapedString(Data))
2323 getStreamer().EmitBytes(Data);
2325 getStreamer().EmitBytes(StringRef("\0", 1));
2329 if (getLexer().is(AsmToken::EndOfStatement))
2332 if (getLexer().isNot(AsmToken::Comma))
2333 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2342 /// parseDirectiveValue
2343 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2344 bool AsmParser::parseDirectiveValue(unsigned Size) {
2345 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2346 checkForValidSection();
2349 const MCExpr *Value;
2350 SMLoc ExprLoc = getLexer().getLoc();
2351 if (parseExpression(Value))
2354 // Special case constant expressions to match code generator.
2355 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2356 assert(Size <= 8 && "Invalid size");
2357 uint64_t IntValue = MCE->getValue();
2358 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2359 return Error(ExprLoc, "literal value out of range for directive");
2360 getStreamer().EmitIntValue(IntValue, Size);
2362 getStreamer().EmitValue(Value, Size);
2364 if (getLexer().is(AsmToken::EndOfStatement))
2367 // FIXME: Improve diagnostic.
2368 if (getLexer().isNot(AsmToken::Comma))
2369 return TokError("unexpected token in directive");
2378 /// ParseDirectiveOctaValue
2379 /// ::= .octa [ hexconstant (, hexconstant)* ]
2380 bool AsmParser::parseDirectiveOctaValue() {
2381 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2382 checkForValidSection();
2385 if (Lexer.getKind() == AsmToken::Error)
2387 if (Lexer.getKind() != AsmToken::Integer &&
2388 Lexer.getKind() != AsmToken::BigNum)
2389 return TokError("unknown token in expression");
2391 SMLoc ExprLoc = getLexer().getLoc();
2392 APInt IntValue = getTok().getAPIntVal();
2396 if (IntValue.isIntN(64)) {
2398 lo = IntValue.getZExtValue();
2399 } else if (IntValue.isIntN(128)) {
2400 // It might actually have more than 128 bits, but the top ones are zero.
2401 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2402 lo = IntValue.getLoBits(64).getZExtValue();
2404 return Error(ExprLoc, "literal value out of range for directive");
2406 if (MAI.isLittleEndian()) {
2407 getStreamer().EmitIntValue(lo, 8);
2408 getStreamer().EmitIntValue(hi, 8);
2410 getStreamer().EmitIntValue(hi, 8);
2411 getStreamer().EmitIntValue(lo, 8);
2414 if (getLexer().is(AsmToken::EndOfStatement))
2417 // FIXME: Improve diagnostic.
2418 if (getLexer().isNot(AsmToken::Comma))
2419 return TokError("unexpected token in directive");
2428 /// parseDirectiveRealValue
2429 /// ::= (.single | .double) [ expression (, expression)* ]
2430 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2431 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2432 checkForValidSection();
2435 // We don't truly support arithmetic on floating point expressions, so we
2436 // have to manually parse unary prefixes.
2438 if (getLexer().is(AsmToken::Minus)) {
2441 } else if (getLexer().is(AsmToken::Plus))
2444 if (getLexer().isNot(AsmToken::Integer) &&
2445 getLexer().isNot(AsmToken::Real) &&
2446 getLexer().isNot(AsmToken::Identifier))
2447 return TokError("unexpected token in directive");
2449 // Convert to an APFloat.
2450 APFloat Value(Semantics);
2451 StringRef IDVal = getTok().getString();
2452 if (getLexer().is(AsmToken::Identifier)) {
2453 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2454 Value = APFloat::getInf(Semantics);
2455 else if (!IDVal.compare_lower("nan"))
2456 Value = APFloat::getNaN(Semantics, false, ~0);
2458 return TokError("invalid floating point literal");
2459 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2460 APFloat::opInvalidOp)
2461 return TokError("invalid floating point literal");
2465 // Consume the numeric token.
2468 // Emit the value as an integer.
2469 APInt AsInt = Value.bitcastToAPInt();
2470 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2471 AsInt.getBitWidth() / 8);
2473 if (getLexer().is(AsmToken::EndOfStatement))
2476 if (getLexer().isNot(AsmToken::Comma))
2477 return TokError("unexpected token in directive");
2486 /// parseDirectiveZero
2487 /// ::= .zero expression
2488 bool AsmParser::parseDirectiveZero() {
2489 checkForValidSection();
2492 if (parseAbsoluteExpression(NumBytes))
2496 if (getLexer().is(AsmToken::Comma)) {
2498 if (parseAbsoluteExpression(Val))
2502 if (getLexer().isNot(AsmToken::EndOfStatement))
2503 return TokError("unexpected token in '.zero' directive");
2507 getStreamer().EmitFill(NumBytes, Val);
2512 /// parseDirectiveFill
2513 /// ::= .fill expression [ , expression [ , expression ] ]
2514 bool AsmParser::parseDirectiveFill() {
2515 checkForValidSection();
2517 SMLoc RepeatLoc = getLexer().getLoc();
2519 if (parseAbsoluteExpression(NumValues))
2522 if (NumValues < 0) {
2524 "'.fill' directive with negative repeat count has no effect");
2528 int64_t FillSize = 1;
2529 int64_t FillExpr = 0;
2531 SMLoc SizeLoc, ExprLoc;
2532 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2533 if (getLexer().isNot(AsmToken::Comma))
2534 return TokError("unexpected token in '.fill' directive");
2537 SizeLoc = getLexer().getLoc();
2538 if (parseAbsoluteExpression(FillSize))
2541 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2542 if (getLexer().isNot(AsmToken::Comma))
2543 return TokError("unexpected token in '.fill' directive");
2546 ExprLoc = getLexer().getLoc();
2547 if (parseAbsoluteExpression(FillExpr))
2550 if (getLexer().isNot(AsmToken::EndOfStatement))
2551 return TokError("unexpected token in '.fill' directive");
2558 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2562 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2566 if (!isUInt<32>(FillExpr) && FillSize > 4)
2567 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2569 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2570 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2572 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2573 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2574 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2580 /// parseDirectiveOrg
2581 /// ::= .org expression [ , expression ]
2582 bool AsmParser::parseDirectiveOrg() {
2583 checkForValidSection();
2585 const MCExpr *Offset;
2586 SMLoc Loc = getTok().getLoc();
2587 if (parseExpression(Offset))
2590 // Parse optional fill expression.
2591 int64_t FillExpr = 0;
2592 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2593 if (getLexer().isNot(AsmToken::Comma))
2594 return TokError("unexpected token in '.org' directive");
2597 if (parseAbsoluteExpression(FillExpr))
2600 if (getLexer().isNot(AsmToken::EndOfStatement))
2601 return TokError("unexpected token in '.org' directive");
2606 // Only limited forms of relocatable expressions are accepted here, it
2607 // has to be relative to the current section. The streamer will return
2608 // 'true' if the expression wasn't evaluatable.
2609 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2610 return Error(Loc, "expected assembly-time absolute expression");
2615 /// parseDirectiveAlign
2616 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2617 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2618 checkForValidSection();
2620 SMLoc AlignmentLoc = getLexer().getLoc();
2622 if (parseAbsoluteExpression(Alignment))
2626 bool HasFillExpr = false;
2627 int64_t FillExpr = 0;
2628 int64_t MaxBytesToFill = 0;
2629 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2630 if (getLexer().isNot(AsmToken::Comma))
2631 return TokError("unexpected token in directive");
2634 // The fill expression can be omitted while specifying a maximum number of
2635 // alignment bytes, e.g:
2637 if (getLexer().isNot(AsmToken::Comma)) {
2639 if (parseAbsoluteExpression(FillExpr))
2643 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2644 if (getLexer().isNot(AsmToken::Comma))
2645 return TokError("unexpected token in directive");
2648 MaxBytesLoc = getLexer().getLoc();
2649 if (parseAbsoluteExpression(MaxBytesToFill))
2652 if (getLexer().isNot(AsmToken::EndOfStatement))
2653 return TokError("unexpected token in directive");
2662 // Compute alignment in bytes.
2664 // FIXME: Diagnose overflow.
2665 if (Alignment >= 32) {
2666 Error(AlignmentLoc, "invalid alignment value");
2670 Alignment = 1ULL << Alignment;
2672 // Reject alignments that aren't a power of two, for gas compatibility.
2673 if (!isPowerOf2_64(Alignment))
2674 Error(AlignmentLoc, "alignment must be a power of 2");
2677 // Diagnose non-sensical max bytes to align.
2678 if (MaxBytesLoc.isValid()) {
2679 if (MaxBytesToFill < 1) {
2680 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2681 "many bytes, ignoring maximum bytes expression");
2685 if (MaxBytesToFill >= Alignment) {
2686 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2692 // Check whether we should use optimal code alignment for this .align
2694 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2695 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2696 ValueSize == 1 && UseCodeAlign) {
2697 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2699 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2700 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2707 /// parseDirectiveFile
2708 /// ::= .file [number] filename
2709 /// ::= .file number directory filename
2710 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2711 // FIXME: I'm not sure what this is.
2712 int64_t FileNumber = -1;
2713 SMLoc FileNumberLoc = getLexer().getLoc();
2714 if (getLexer().is(AsmToken::Integer)) {
2715 FileNumber = getTok().getIntVal();
2719 return TokError("file number less than one");
2722 if (getLexer().isNot(AsmToken::String))
2723 return TokError("unexpected token in '.file' directive");
2725 // Usually the directory and filename together, otherwise just the directory.
2726 // Allow the strings to have escaped octal character sequence.
2727 std::string Path = getTok().getString();
2728 if (parseEscapedString(Path))
2732 StringRef Directory;
2734 std::string FilenameData;
2735 if (getLexer().is(AsmToken::String)) {
2736 if (FileNumber == -1)
2737 return TokError("explicit path specified, but no file number");
2738 if (parseEscapedString(FilenameData))
2740 Filename = FilenameData;
2747 if (getLexer().isNot(AsmToken::EndOfStatement))
2748 return TokError("unexpected token in '.file' directive");
2750 if (FileNumber == -1)
2751 getStreamer().EmitFileDirective(Filename);
2753 if (getContext().getGenDwarfForAssembly() == true)
2755 "input can't have .file dwarf directives when -g is "
2756 "used to generate dwarf debug info for assembly code");
2758 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2759 Error(FileNumberLoc, "file number already allocated");
2765 /// parseDirectiveLine
2766 /// ::= .line [number]
2767 bool AsmParser::parseDirectiveLine() {
2768 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2769 if (getLexer().isNot(AsmToken::Integer))
2770 return TokError("unexpected token in '.line' directive");
2772 int64_t LineNumber = getTok().getIntVal();
2776 // FIXME: Do something with the .line.
2779 if (getLexer().isNot(AsmToken::EndOfStatement))
2780 return TokError("unexpected token in '.line' directive");
2785 /// parseDirectiveLoc
2786 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2787 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2788 /// The first number is a file number, must have been previously assigned with
2789 /// a .file directive, the second number is the line number and optionally the
2790 /// third number is a column position (zero if not specified). The remaining
2791 /// optional items are .loc sub-directives.
2792 bool AsmParser::parseDirectiveLoc() {
2793 if (getLexer().isNot(AsmToken::Integer))
2794 return TokError("unexpected token in '.loc' directive");
2795 int64_t FileNumber = getTok().getIntVal();
2797 return TokError("file number less than one in '.loc' directive");
2798 if (!getContext().isValidDwarfFileNumber(FileNumber))
2799 return TokError("unassigned file number in '.loc' directive");
2802 int64_t LineNumber = 0;
2803 if (getLexer().is(AsmToken::Integer)) {
2804 LineNumber = getTok().getIntVal();
2806 return TokError("line number less than zero in '.loc' directive");
2810 int64_t ColumnPos = 0;
2811 if (getLexer().is(AsmToken::Integer)) {
2812 ColumnPos = getTok().getIntVal();
2814 return TokError("column position less than zero in '.loc' directive");
2818 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2820 int64_t Discriminator = 0;
2821 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2823 if (getLexer().is(AsmToken::EndOfStatement))
2827 SMLoc Loc = getTok().getLoc();
2828 if (parseIdentifier(Name))
2829 return TokError("unexpected token in '.loc' directive");
2831 if (Name == "basic_block")
2832 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2833 else if (Name == "prologue_end")
2834 Flags |= DWARF2_FLAG_PROLOGUE_END;
2835 else if (Name == "epilogue_begin")
2836 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2837 else if (Name == "is_stmt") {
2838 Loc = getTok().getLoc();
2839 const MCExpr *Value;
2840 if (parseExpression(Value))
2842 // The expression must be the constant 0 or 1.
2843 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2844 int Value = MCE->getValue();
2846 Flags &= ~DWARF2_FLAG_IS_STMT;
2847 else if (Value == 1)
2848 Flags |= DWARF2_FLAG_IS_STMT;
2850 return Error(Loc, "is_stmt value not 0 or 1");
2852 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2854 } else if (Name == "isa") {
2855 Loc = getTok().getLoc();
2856 const MCExpr *Value;
2857 if (parseExpression(Value))
2859 // The expression must be a constant greater or equal to 0.
2860 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2861 int Value = MCE->getValue();
2863 return Error(Loc, "isa number less than zero");
2866 return Error(Loc, "isa number not a constant value");
2868 } else if (Name == "discriminator") {
2869 if (parseAbsoluteExpression(Discriminator))
2872 return Error(Loc, "unknown sub-directive in '.loc' directive");
2875 if (getLexer().is(AsmToken::EndOfStatement))
2880 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2881 Isa, Discriminator, StringRef());
2886 /// parseDirectiveStabs
2887 /// ::= .stabs string, number, number, number
2888 bool AsmParser::parseDirectiveStabs() {
2889 return TokError("unsupported directive '.stabs'");
2892 /// parseDirectiveCFISections
2893 /// ::= .cfi_sections section [, section]
2894 bool AsmParser::parseDirectiveCFISections() {
2899 if (parseIdentifier(Name))
2900 return TokError("Expected an identifier");
2902 if (Name == ".eh_frame")
2904 else if (Name == ".debug_frame")
2907 if (getLexer().is(AsmToken::Comma)) {
2910 if (parseIdentifier(Name))
2911 return TokError("Expected an identifier");
2913 if (Name == ".eh_frame")
2915 else if (Name == ".debug_frame")
2919 getStreamer().EmitCFISections(EH, Debug);
2923 /// parseDirectiveCFIStartProc
2924 /// ::= .cfi_startproc [simple]
2925 bool AsmParser::parseDirectiveCFIStartProc() {
2927 if (getLexer().isNot(AsmToken::EndOfStatement))
2928 if (parseIdentifier(Simple) || Simple != "simple")
2929 return TokError("unexpected token in .cfi_startproc directive");
2931 getStreamer().EmitCFIStartProc(!Simple.empty());
2935 /// parseDirectiveCFIEndProc
2936 /// ::= .cfi_endproc
2937 bool AsmParser::parseDirectiveCFIEndProc() {
2938 getStreamer().EmitCFIEndProc();
2942 /// \brief parse register name or number.
2943 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2944 SMLoc DirectiveLoc) {
2947 if (getLexer().isNot(AsmToken::Integer)) {
2948 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2950 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2952 return parseAbsoluteExpression(Register);
2957 /// parseDirectiveCFIDefCfa
2958 /// ::= .cfi_def_cfa register, offset
2959 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2960 int64_t Register = 0;
2961 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2964 if (getLexer().isNot(AsmToken::Comma))
2965 return TokError("unexpected token in directive");
2969 if (parseAbsoluteExpression(Offset))
2972 getStreamer().EmitCFIDefCfa(Register, Offset);
2976 /// parseDirectiveCFIDefCfaOffset
2977 /// ::= .cfi_def_cfa_offset offset
2978 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2980 if (parseAbsoluteExpression(Offset))
2983 getStreamer().EmitCFIDefCfaOffset(Offset);
2987 /// parseDirectiveCFIRegister
2988 /// ::= .cfi_register register, register
2989 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2990 int64_t Register1 = 0;
2991 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2994 if (getLexer().isNot(AsmToken::Comma))
2995 return TokError("unexpected token in directive");
2998 int64_t Register2 = 0;
2999 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3002 getStreamer().EmitCFIRegister(Register1, Register2);
3006 /// parseDirectiveCFIWindowSave
3007 /// ::= .cfi_window_save
3008 bool AsmParser::parseDirectiveCFIWindowSave() {
3009 getStreamer().EmitCFIWindowSave();
3013 /// parseDirectiveCFIAdjustCfaOffset
3014 /// ::= .cfi_adjust_cfa_offset adjustment
3015 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3016 int64_t Adjustment = 0;
3017 if (parseAbsoluteExpression(Adjustment))
3020 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3024 /// parseDirectiveCFIDefCfaRegister
3025 /// ::= .cfi_def_cfa_register register
3026 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3027 int64_t Register = 0;
3028 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3031 getStreamer().EmitCFIDefCfaRegister(Register);
3035 /// parseDirectiveCFIOffset
3036 /// ::= .cfi_offset register, offset
3037 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3038 int64_t Register = 0;
3041 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3044 if (getLexer().isNot(AsmToken::Comma))
3045 return TokError("unexpected token in directive");
3048 if (parseAbsoluteExpression(Offset))
3051 getStreamer().EmitCFIOffset(Register, Offset);
3055 /// parseDirectiveCFIRelOffset
3056 /// ::= .cfi_rel_offset register, offset
3057 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3058 int64_t Register = 0;
3060 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3063 if (getLexer().isNot(AsmToken::Comma))
3064 return TokError("unexpected token in directive");
3068 if (parseAbsoluteExpression(Offset))
3071 getStreamer().EmitCFIRelOffset(Register, Offset);
3075 static bool isValidEncoding(int64_t Encoding) {
3076 if (Encoding & ~0xff)
3079 if (Encoding == dwarf::DW_EH_PE_omit)
3082 const unsigned Format = Encoding & 0xf;
3083 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3084 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3085 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3086 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3089 const unsigned Application = Encoding & 0x70;
3090 if (Application != dwarf::DW_EH_PE_absptr &&
3091 Application != dwarf::DW_EH_PE_pcrel)
3097 /// parseDirectiveCFIPersonalityOrLsda
3098 /// IsPersonality true for cfi_personality, false for cfi_lsda
3099 /// ::= .cfi_personality encoding, [symbol_name]
3100 /// ::= .cfi_lsda encoding, [symbol_name]
3101 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3102 int64_t Encoding = 0;
3103 if (parseAbsoluteExpression(Encoding))
3105 if (Encoding == dwarf::DW_EH_PE_omit)
3108 if (!isValidEncoding(Encoding))
3109 return TokError("unsupported encoding.");
3111 if (getLexer().isNot(AsmToken::Comma))
3112 return TokError("unexpected token in directive");
3116 if (parseIdentifier(Name))
3117 return TokError("expected identifier in directive");
3119 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3122 getStreamer().EmitCFIPersonality(Sym, Encoding);
3124 getStreamer().EmitCFILsda(Sym, Encoding);
3128 /// parseDirectiveCFIRememberState
3129 /// ::= .cfi_remember_state
3130 bool AsmParser::parseDirectiveCFIRememberState() {
3131 getStreamer().EmitCFIRememberState();
3135 /// parseDirectiveCFIRestoreState
3136 /// ::= .cfi_remember_state
3137 bool AsmParser::parseDirectiveCFIRestoreState() {
3138 getStreamer().EmitCFIRestoreState();
3142 /// parseDirectiveCFISameValue
3143 /// ::= .cfi_same_value register
3144 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3145 int64_t Register = 0;
3147 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3150 getStreamer().EmitCFISameValue(Register);
3154 /// parseDirectiveCFIRestore
3155 /// ::= .cfi_restore register
3156 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3157 int64_t Register = 0;
3158 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3161 getStreamer().EmitCFIRestore(Register);
3165 /// parseDirectiveCFIEscape
3166 /// ::= .cfi_escape expression[,...]
3167 bool AsmParser::parseDirectiveCFIEscape() {
3170 if (parseAbsoluteExpression(CurrValue))
3173 Values.push_back((uint8_t)CurrValue);
3175 while (getLexer().is(AsmToken::Comma)) {
3178 if (parseAbsoluteExpression(CurrValue))
3181 Values.push_back((uint8_t)CurrValue);
3184 getStreamer().EmitCFIEscape(Values);
3188 /// parseDirectiveCFISignalFrame
3189 /// ::= .cfi_signal_frame
3190 bool AsmParser::parseDirectiveCFISignalFrame() {
3191 if (getLexer().isNot(AsmToken::EndOfStatement))
3192 return Error(getLexer().getLoc(),
3193 "unexpected token in '.cfi_signal_frame'");
3195 getStreamer().EmitCFISignalFrame();
3199 /// parseDirectiveCFIUndefined
3200 /// ::= .cfi_undefined register
3201 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3202 int64_t Register = 0;
3204 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3207 getStreamer().EmitCFIUndefined(Register);
3211 /// parseDirectiveMacrosOnOff
3214 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3215 if (getLexer().isNot(AsmToken::EndOfStatement))
3216 return Error(getLexer().getLoc(),
3217 "unexpected token in '" + Directive + "' directive");
3219 setMacrosEnabled(Directive == ".macros_on");
3223 /// parseDirectiveMacro
3224 /// ::= .macro name[,] [parameters]
3225 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3227 if (parseIdentifier(Name))
3228 return TokError("expected identifier in '.macro' directive");
3230 if (getLexer().is(AsmToken::Comma))
3233 MCAsmMacroParameters Parameters;
3234 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3235 MCAsmMacroParameter Parameter;
3236 if (parseIdentifier(Parameter.Name))
3237 return TokError("expected identifier in '.macro' directive");
3239 if (Lexer.is(AsmToken::Colon)) {
3240 Lex(); // consume ':'
3243 StringRef Qualifier;
3245 QualLoc = Lexer.getLoc();
3246 if (parseIdentifier(Qualifier))
3247 return Error(QualLoc, "missing parameter qualifier for "
3248 "'" + Parameter.Name + "' in macro '" + Name + "'");
3250 if (Qualifier == "req")
3251 Parameter.Required = true;
3253 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3254 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3257 if (getLexer().is(AsmToken::Equal)) {
3262 ParamLoc = Lexer.getLoc();
3263 if (parseMacroArgument(Parameter.Value))
3266 if (Parameter.Required)
3267 Warning(ParamLoc, "pointless default value for required parameter "
3268 "'" + Parameter.Name + "' in macro '" + Name + "'");
3271 Parameters.push_back(Parameter);
3273 if (getLexer().is(AsmToken::Comma))
3277 // Eat the end of statement.
3280 AsmToken EndToken, StartToken = getTok();
3281 unsigned MacroDepth = 0;
3283 // Lex the macro definition.
3285 // Check whether we have reached the end of the file.
3286 if (getLexer().is(AsmToken::Eof))
3287 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3289 // Otherwise, check whether we have reach the .endmacro.
3290 if (getLexer().is(AsmToken::Identifier)) {
3291 if (getTok().getIdentifier() == ".endm" ||
3292 getTok().getIdentifier() == ".endmacro") {
3293 if (MacroDepth == 0) { // Outermost macro.
3294 EndToken = getTok();
3296 if (getLexer().isNot(AsmToken::EndOfStatement))
3297 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3301 // Otherwise we just found the end of an inner macro.
3304 } else if (getTok().getIdentifier() == ".macro") {
3305 // We allow nested macros. Those aren't instantiated until the outermost
3306 // macro is expanded so just ignore them for now.
3311 // Otherwise, scan til the end of the statement.
3312 eatToEndOfStatement();
3315 if (lookupMacro(Name)) {
3316 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3319 const char *BodyStart = StartToken.getLoc().getPointer();
3320 const char *BodyEnd = EndToken.getLoc().getPointer();
3321 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3322 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3323 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3327 /// checkForBadMacro
3329 /// With the support added for named parameters there may be code out there that
3330 /// is transitioning from positional parameters. In versions of gas that did
3331 /// not support named parameters they would be ignored on the macro definition.
3332 /// But to support both styles of parameters this is not possible so if a macro
3333 /// definition has named parameters but does not use them and has what appears
3334 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3335 /// warning that the positional parameter found in body which have no effect.
3336 /// Hoping the developer will either remove the named parameters from the macro
3337 /// definition so the positional parameters get used if that was what was
3338 /// intended or change the macro to use the named parameters. It is possible
3339 /// this warning will trigger when the none of the named parameters are used
3340 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3341 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3343 ArrayRef<MCAsmMacroParameter> Parameters) {
3344 // If this macro is not defined with named parameters the warning we are
3345 // checking for here doesn't apply.
3346 unsigned NParameters = Parameters.size();
3347 if (NParameters == 0)
3350 bool NamedParametersFound = false;
3351 bool PositionalParametersFound = false;
3353 // Look at the body of the macro for use of both the named parameters and what
3354 // are likely to be positional parameters. This is what expandMacro() is
3355 // doing when it finds the parameters in the body.
3356 while (!Body.empty()) {
3357 // Scan for the next possible parameter.
3358 std::size_t End = Body.size(), Pos = 0;
3359 for (; Pos != End; ++Pos) {
3360 // Check for a substitution or escape.
3361 // This macro is defined with parameters, look for \foo, \bar, etc.
3362 if (Body[Pos] == '\\' && Pos + 1 != End)
3365 // This macro should have parameters, but look for $0, $1, ..., $n too.
3366 if (Body[Pos] != '$' || Pos + 1 == End)
3368 char Next = Body[Pos + 1];
3369 if (Next == '$' || Next == 'n' ||
3370 isdigit(static_cast<unsigned char>(Next)))
3374 // Check if we reached the end.
3378 if (Body[Pos] == '$') {
3379 switch (Body[Pos + 1]) {
3384 // $n => number of arguments
3386 PositionalParametersFound = true;
3389 // $[0-9] => argument
3391 PositionalParametersFound = true;
3397 unsigned I = Pos + 1;
3398 while (isIdentifierChar(Body[I]) && I + 1 != End)
3401 const char *Begin = Body.data() + Pos + 1;
3402 StringRef Argument(Begin, I - (Pos + 1));
3404 for (; Index < NParameters; ++Index)
3405 if (Parameters[Index].Name == Argument)
3408 if (Index == NParameters) {
3409 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3415 NamedParametersFound = true;
3416 Pos += 1 + Argument.size();
3419 // Update the scan point.
3420 Body = Body.substr(Pos);
3423 if (!NamedParametersFound && PositionalParametersFound)
3424 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3425 "used in macro body, possible positional parameter "
3426 "found in body which will have no effect");
3429 /// parseDirectiveEndMacro
3432 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3433 if (getLexer().isNot(AsmToken::EndOfStatement))
3434 return TokError("unexpected token in '" + Directive + "' directive");
3436 // If we are inside a macro instantiation, terminate the current
3438 if (isInsideMacroInstantiation()) {
3443 // Otherwise, this .endmacro is a stray entry in the file; well formed
3444 // .endmacro directives are handled during the macro definition parsing.
3445 return TokError("unexpected '" + Directive + "' in file, "
3446 "no current macro definition");
3449 /// parseDirectivePurgeMacro
3451 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3453 if (parseIdentifier(Name))
3454 return TokError("expected identifier in '.purgem' directive");
3456 if (getLexer().isNot(AsmToken::EndOfStatement))
3457 return TokError("unexpected token in '.purgem' directive");
3459 if (!lookupMacro(Name))
3460 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3462 undefineMacro(Name);
3466 /// parseDirectiveBundleAlignMode
3467 /// ::= {.bundle_align_mode} expression
3468 bool AsmParser::parseDirectiveBundleAlignMode() {
3469 checkForValidSection();
3471 // Expect a single argument: an expression that evaluates to a constant
3472 // in the inclusive range 0-30.
3473 SMLoc ExprLoc = getLexer().getLoc();
3474 int64_t AlignSizePow2;
3475 if (parseAbsoluteExpression(AlignSizePow2))
3477 else if (getLexer().isNot(AsmToken::EndOfStatement))
3478 return TokError("unexpected token after expression in"
3479 " '.bundle_align_mode' directive");
3480 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3481 return Error(ExprLoc,
3482 "invalid bundle alignment size (expected between 0 and 30)");
3486 // Because of AlignSizePow2's verified range we can safely truncate it to
3488 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3492 /// parseDirectiveBundleLock
3493 /// ::= {.bundle_lock} [align_to_end]
3494 bool AsmParser::parseDirectiveBundleLock() {
3495 checkForValidSection();
3496 bool AlignToEnd = false;
3498 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3500 SMLoc Loc = getTok().getLoc();
3501 const char *kInvalidOptionError =
3502 "invalid option for '.bundle_lock' directive";
3504 if (parseIdentifier(Option))
3505 return Error(Loc, kInvalidOptionError);
3507 if (Option != "align_to_end")
3508 return Error(Loc, kInvalidOptionError);
3509 else if (getLexer().isNot(AsmToken::EndOfStatement))
3511 "unexpected token after '.bundle_lock' directive option");
3517 getStreamer().EmitBundleLock(AlignToEnd);
3521 /// parseDirectiveBundleLock
3522 /// ::= {.bundle_lock}
3523 bool AsmParser::parseDirectiveBundleUnlock() {
3524 checkForValidSection();
3526 if (getLexer().isNot(AsmToken::EndOfStatement))
3527 return TokError("unexpected token in '.bundle_unlock' directive");
3530 getStreamer().EmitBundleUnlock();
3534 /// parseDirectiveSpace
3535 /// ::= (.skip | .space) expression [ , expression ]
3536 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3537 checkForValidSection();
3540 if (parseAbsoluteExpression(NumBytes))
3543 int64_t FillExpr = 0;
3544 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3545 if (getLexer().isNot(AsmToken::Comma))
3546 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3549 if (parseAbsoluteExpression(FillExpr))
3552 if (getLexer().isNot(AsmToken::EndOfStatement))
3553 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3559 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3562 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3563 getStreamer().EmitFill(NumBytes, FillExpr);
3568 /// parseDirectiveLEB128
3569 /// ::= (.sleb128 | .uleb128) expression
3570 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3571 checkForValidSection();
3572 const MCExpr *Value;
3574 if (parseExpression(Value))
3577 if (getLexer().isNot(AsmToken::EndOfStatement))
3578 return TokError("unexpected token in directive");
3581 getStreamer().EmitSLEB128Value(Value);
3583 getStreamer().EmitULEB128Value(Value);
3588 /// parseDirectiveSymbolAttribute
3589 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3590 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3591 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3594 SMLoc Loc = getTok().getLoc();
3596 if (parseIdentifier(Name))
3597 return Error(Loc, "expected identifier in directive");
3599 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3601 // Assembler local symbols don't make any sense here. Complain loudly.
3602 if (Sym->isTemporary())
3603 return Error(Loc, "non-local symbol required in directive");
3605 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3606 return Error(Loc, "unable to emit symbol attribute");
3608 if (getLexer().is(AsmToken::EndOfStatement))
3611 if (getLexer().isNot(AsmToken::Comma))
3612 return TokError("unexpected token in directive");
3621 /// parseDirectiveComm
3622 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3623 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3624 checkForValidSection();
3626 SMLoc IDLoc = getLexer().getLoc();
3628 if (parseIdentifier(Name))
3629 return TokError("expected identifier in directive");
3631 // Handle the identifier as the key symbol.
3632 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3634 if (getLexer().isNot(AsmToken::Comma))
3635 return TokError("unexpected token in directive");
3639 SMLoc SizeLoc = getLexer().getLoc();
3640 if (parseAbsoluteExpression(Size))
3643 int64_t Pow2Alignment = 0;
3644 SMLoc Pow2AlignmentLoc;
3645 if (getLexer().is(AsmToken::Comma)) {
3647 Pow2AlignmentLoc = getLexer().getLoc();
3648 if (parseAbsoluteExpression(Pow2Alignment))
3651 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3652 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3653 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3655 // If this target takes alignments in bytes (not log) validate and convert.
3656 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3657 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3658 if (!isPowerOf2_64(Pow2Alignment))
3659 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3660 Pow2Alignment = Log2_64(Pow2Alignment);
3664 if (getLexer().isNot(AsmToken::EndOfStatement))
3665 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3669 // NOTE: a size of zero for a .comm should create a undefined symbol
3670 // but a size of .lcomm creates a bss symbol of size zero.
3672 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3673 "be less than zero");
3675 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3676 // may internally end up wanting an alignment in bytes.
3677 // FIXME: Diagnose overflow.
3678 if (Pow2Alignment < 0)
3679 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3680 "alignment, can't be less than zero");
3682 if (!Sym->isUndefined())
3683 return Error(IDLoc, "invalid symbol redefinition");
3685 // Create the Symbol as a common or local common with Size and Pow2Alignment
3687 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3691 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3695 /// parseDirectiveAbort
3696 /// ::= .abort [... message ...]
3697 bool AsmParser::parseDirectiveAbort() {
3698 // FIXME: Use loc from directive.
3699 SMLoc Loc = getLexer().getLoc();
3701 StringRef Str = parseStringToEndOfStatement();
3702 if (getLexer().isNot(AsmToken::EndOfStatement))
3703 return TokError("unexpected token in '.abort' directive");
3708 Error(Loc, ".abort detected. Assembly stopping.");
3710 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3711 // FIXME: Actually abort assembly here.
3716 /// parseDirectiveInclude
3717 /// ::= .include "filename"
3718 bool AsmParser::parseDirectiveInclude() {
3719 if (getLexer().isNot(AsmToken::String))
3720 return TokError("expected string in '.include' directive");
3722 // Allow the strings to have escaped octal character sequence.
3723 std::string Filename;
3724 if (parseEscapedString(Filename))
3726 SMLoc IncludeLoc = getLexer().getLoc();
3729 if (getLexer().isNot(AsmToken::EndOfStatement))
3730 return TokError("unexpected token in '.include' directive");
3732 // Attempt to switch the lexer to the included file before consuming the end
3733 // of statement to avoid losing it when we switch.
3734 if (enterIncludeFile(Filename)) {
3735 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3742 /// parseDirectiveIncbin
3743 /// ::= .incbin "filename"
3744 bool AsmParser::parseDirectiveIncbin() {
3745 if (getLexer().isNot(AsmToken::String))
3746 return TokError("expected string in '.incbin' directive");
3748 // Allow the strings to have escaped octal character sequence.
3749 std::string Filename;
3750 if (parseEscapedString(Filename))
3752 SMLoc IncbinLoc = getLexer().getLoc();
3755 if (getLexer().isNot(AsmToken::EndOfStatement))
3756 return TokError("unexpected token in '.incbin' directive");
3758 // Attempt to process the included file.
3759 if (processIncbinFile(Filename)) {
3760 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3767 /// parseDirectiveIf
3768 /// ::= .if expression
3769 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3770 TheCondStack.push_back(TheCondState);
3771 TheCondState.TheCond = AsmCond::IfCond;
3772 if (TheCondState.Ignore) {
3773 eatToEndOfStatement();
3776 if (parseAbsoluteExpression(ExprValue))
3779 if (getLexer().isNot(AsmToken::EndOfStatement))
3780 return TokError("unexpected token in '.if' directive");
3784 TheCondState.CondMet = ExprValue;
3785 TheCondState.Ignore = !TheCondState.CondMet;
3791 /// parseDirectiveIfb
3793 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3794 TheCondStack.push_back(TheCondState);
3795 TheCondState.TheCond = AsmCond::IfCond;
3797 if (TheCondState.Ignore) {
3798 eatToEndOfStatement();
3800 StringRef Str = parseStringToEndOfStatement();
3802 if (getLexer().isNot(AsmToken::EndOfStatement))
3803 return TokError("unexpected token in '.ifb' directive");
3807 TheCondState.CondMet = ExpectBlank == Str.empty();
3808 TheCondState.Ignore = !TheCondState.CondMet;
3814 /// parseDirectiveIfc
3815 /// ::= .ifc string1, string2
3816 /// ::= .ifnc string1, string2
3817 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3818 TheCondStack.push_back(TheCondState);
3819 TheCondState.TheCond = AsmCond::IfCond;
3821 if (TheCondState.Ignore) {
3822 eatToEndOfStatement();
3824 StringRef Str1 = parseStringToComma();
3826 if (getLexer().isNot(AsmToken::Comma))
3827 return TokError("unexpected token in '.ifc' directive");
3831 StringRef Str2 = parseStringToEndOfStatement();
3833 if (getLexer().isNot(AsmToken::EndOfStatement))
3834 return TokError("unexpected token in '.ifc' directive");
3838 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3839 TheCondState.Ignore = !TheCondState.CondMet;
3845 /// parseDirectiveIfdef
3846 /// ::= .ifdef symbol
3847 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3849 TheCondStack.push_back(TheCondState);
3850 TheCondState.TheCond = AsmCond::IfCond;
3852 if (TheCondState.Ignore) {
3853 eatToEndOfStatement();
3855 if (parseIdentifier(Name))
3856 return TokError("expected identifier after '.ifdef'");
3860 MCSymbol *Sym = getContext().LookupSymbol(Name);
3863 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3865 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3866 TheCondState.Ignore = !TheCondState.CondMet;
3872 /// parseDirectiveElseIf
3873 /// ::= .elseif expression
3874 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3875 if (TheCondState.TheCond != AsmCond::IfCond &&
3876 TheCondState.TheCond != AsmCond::ElseIfCond)
3877 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3879 TheCondState.TheCond = AsmCond::ElseIfCond;
3881 bool LastIgnoreState = false;
3882 if (!TheCondStack.empty())
3883 LastIgnoreState = TheCondStack.back().Ignore;
3884 if (LastIgnoreState || TheCondState.CondMet) {
3885 TheCondState.Ignore = true;
3886 eatToEndOfStatement();
3889 if (parseAbsoluteExpression(ExprValue))
3892 if (getLexer().isNot(AsmToken::EndOfStatement))
3893 return TokError("unexpected token in '.elseif' directive");
3896 TheCondState.CondMet = ExprValue;
3897 TheCondState.Ignore = !TheCondState.CondMet;
3903 /// parseDirectiveElse
3905 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3906 if (getLexer().isNot(AsmToken::EndOfStatement))
3907 return TokError("unexpected token in '.else' directive");
3911 if (TheCondState.TheCond != AsmCond::IfCond &&
3912 TheCondState.TheCond != AsmCond::ElseIfCond)
3913 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3915 TheCondState.TheCond = AsmCond::ElseCond;
3916 bool LastIgnoreState = false;
3917 if (!TheCondStack.empty())
3918 LastIgnoreState = TheCondStack.back().Ignore;
3919 if (LastIgnoreState || TheCondState.CondMet)
3920 TheCondState.Ignore = true;
3922 TheCondState.Ignore = false;
3927 /// parseDirectiveEnd
3929 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3930 if (getLexer().isNot(AsmToken::EndOfStatement))
3931 return TokError("unexpected token in '.end' directive");
3935 while (Lexer.isNot(AsmToken::Eof))
3941 /// parseDirectiveErr
3943 bool AsmParser::parseDirectiveErr(SMLoc Loc) {
3944 if (!TheCondStack.empty())
3945 if (TheCondStack.back().Ignore)
3947 return Error(Loc, ".err encountered");
3950 /// parseDirectiveEndIf
3952 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3953 if (getLexer().isNot(AsmToken::EndOfStatement))
3954 return TokError("unexpected token in '.endif' directive");
3958 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3959 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3961 if (!TheCondStack.empty()) {
3962 TheCondState = TheCondStack.back();
3963 TheCondStack.pop_back();
3969 void AsmParser::initializeDirectiveKindMap() {
3970 DirectiveKindMap[".set"] = DK_SET;
3971 DirectiveKindMap[".equ"] = DK_EQU;
3972 DirectiveKindMap[".equiv"] = DK_EQUIV;
3973 DirectiveKindMap[".ascii"] = DK_ASCII;
3974 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3975 DirectiveKindMap[".string"] = DK_STRING;
3976 DirectiveKindMap[".byte"] = DK_BYTE;
3977 DirectiveKindMap[".short"] = DK_SHORT;
3978 DirectiveKindMap[".value"] = DK_VALUE;
3979 DirectiveKindMap[".2byte"] = DK_2BYTE;
3980 DirectiveKindMap[".long"] = DK_LONG;
3981 DirectiveKindMap[".int"] = DK_INT;
3982 DirectiveKindMap[".4byte"] = DK_4BYTE;
3983 DirectiveKindMap[".quad"] = DK_QUAD;
3984 DirectiveKindMap[".8byte"] = DK_8BYTE;
3985 DirectiveKindMap[".octa"] = DK_OCTA;
3986 DirectiveKindMap[".single"] = DK_SINGLE;
3987 DirectiveKindMap[".float"] = DK_FLOAT;
3988 DirectiveKindMap[".double"] = DK_DOUBLE;
3989 DirectiveKindMap[".align"] = DK_ALIGN;
3990 DirectiveKindMap[".align32"] = DK_ALIGN32;
3991 DirectiveKindMap[".balign"] = DK_BALIGN;
3992 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3993 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3994 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3995 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3996 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3997 DirectiveKindMap[".org"] = DK_ORG;
3998 DirectiveKindMap[".fill"] = DK_FILL;
3999 DirectiveKindMap[".zero"] = DK_ZERO;
4000 DirectiveKindMap[".extern"] = DK_EXTERN;
4001 DirectiveKindMap[".globl"] = DK_GLOBL;
4002 DirectiveKindMap[".global"] = DK_GLOBAL;
4003 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4004 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4005 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4006 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4007 DirectiveKindMap[".reference"] = DK_REFERENCE;
4008 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4009 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4010 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4011 DirectiveKindMap[".comm"] = DK_COMM;
4012 DirectiveKindMap[".common"] = DK_COMMON;
4013 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4014 DirectiveKindMap[".abort"] = DK_ABORT;
4015 DirectiveKindMap[".include"] = DK_INCLUDE;
4016 DirectiveKindMap[".incbin"] = DK_INCBIN;
4017 DirectiveKindMap[".code16"] = DK_CODE16;
4018 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4019 DirectiveKindMap[".rept"] = DK_REPT;
4020 DirectiveKindMap[".rep"] = DK_REPT;
4021 DirectiveKindMap[".irp"] = DK_IRP;
4022 DirectiveKindMap[".irpc"] = DK_IRPC;
4023 DirectiveKindMap[".endr"] = DK_ENDR;
4024 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4025 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4026 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4027 DirectiveKindMap[".if"] = DK_IF;
4028 DirectiveKindMap[".ifb"] = DK_IFB;
4029 DirectiveKindMap[".ifnb"] = DK_IFNB;
4030 DirectiveKindMap[".ifc"] = DK_IFC;
4031 DirectiveKindMap[".ifnc"] = DK_IFNC;
4032 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4033 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4034 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4035 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4036 DirectiveKindMap[".else"] = DK_ELSE;
4037 DirectiveKindMap[".end"] = DK_END;
4038 DirectiveKindMap[".endif"] = DK_ENDIF;
4039 DirectiveKindMap[".skip"] = DK_SKIP;
4040 DirectiveKindMap[".space"] = DK_SPACE;
4041 DirectiveKindMap[".file"] = DK_FILE;
4042 DirectiveKindMap[".line"] = DK_LINE;
4043 DirectiveKindMap[".loc"] = DK_LOC;
4044 DirectiveKindMap[".stabs"] = DK_STABS;
4045 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4046 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4047 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4048 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4049 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4050 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4051 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4052 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4053 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4054 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4055 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4056 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4057 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4058 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4059 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4060 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4061 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4062 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4063 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4064 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4065 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4066 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4067 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4068 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4069 DirectiveKindMap[".macro"] = DK_MACRO;
4070 DirectiveKindMap[".endm"] = DK_ENDM;
4071 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4072 DirectiveKindMap[".purgem"] = DK_PURGEM;
4073 DirectiveKindMap[".err"] = DK_ERR;
4076 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4077 AsmToken EndToken, StartToken = getTok();
4079 unsigned NestLevel = 0;
4081 // Check whether we have reached the end of the file.
4082 if (getLexer().is(AsmToken::Eof)) {
4083 Error(DirectiveLoc, "no matching '.endr' in definition");
4087 if (Lexer.is(AsmToken::Identifier) &&
4088 (getTok().getIdentifier() == ".rept")) {
4092 // Otherwise, check whether we have reached the .endr.
4093 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4094 if (NestLevel == 0) {
4095 EndToken = getTok();
4097 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4098 TokError("unexpected token in '.endr' directive");
4106 // Otherwise, scan till the end of the statement.
4107 eatToEndOfStatement();
4110 const char *BodyStart = StartToken.getLoc().getPointer();
4111 const char *BodyEnd = EndToken.getLoc().getPointer();
4112 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4114 // We Are Anonymous.
4115 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4116 return &MacroLikeBodies.back();
4119 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4120 raw_svector_ostream &OS) {
4123 MemoryBuffer *Instantiation =
4124 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4126 // Create the macro instantiation object and add to the current macro
4127 // instantiation stack.
4128 MacroInstantiation *MI = new MacroInstantiation(
4129 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4130 ActiveMacros.push_back(MI);
4132 // Jump to the macro instantiation and prime the lexer.
4133 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4134 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4138 /// parseDirectiveRept
4139 /// ::= .rep | .rept count
4140 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4141 const MCExpr *CountExpr;
4142 SMLoc CountLoc = getTok().getLoc();
4143 if (parseExpression(CountExpr))
4147 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4148 eatToEndOfStatement();
4149 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4153 return Error(CountLoc, "Count is negative");
4155 if (Lexer.isNot(AsmToken::EndOfStatement))
4156 return TokError("unexpected token in '" + Dir + "' directive");
4158 // Eat the end of statement.
4161 // Lex the rept definition.
4162 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4166 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4167 // to hold the macro body with substitutions.
4168 SmallString<256> Buf;
4169 raw_svector_ostream OS(Buf);
4171 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4174 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4179 /// parseDirectiveIrp
4180 /// ::= .irp symbol,values
4181 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4182 MCAsmMacroParameter Parameter;
4184 if (parseIdentifier(Parameter.Name))
4185 return TokError("expected identifier in '.irp' directive");
4187 if (Lexer.isNot(AsmToken::Comma))
4188 return TokError("expected comma in '.irp' directive");
4192 MCAsmMacroArguments A;
4193 if (parseMacroArguments(0, A))
4196 // Eat the end of statement.
4199 // Lex the irp definition.
4200 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4204 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4205 // to hold the macro body with substitutions.
4206 SmallString<256> Buf;
4207 raw_svector_ostream OS(Buf);
4209 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4210 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4214 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4219 /// parseDirectiveIrpc
4220 /// ::= .irpc symbol,values
4221 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4222 MCAsmMacroParameter Parameter;
4224 if (parseIdentifier(Parameter.Name))
4225 return TokError("expected identifier in '.irpc' directive");
4227 if (Lexer.isNot(AsmToken::Comma))
4228 return TokError("expected comma in '.irpc' directive");
4232 MCAsmMacroArguments A;
4233 if (parseMacroArguments(0, A))
4236 if (A.size() != 1 || A.front().size() != 1)
4237 return TokError("unexpected token in '.irpc' directive");
4239 // Eat the end of statement.
4242 // Lex the irpc definition.
4243 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4247 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4248 // to hold the macro body with substitutions.
4249 SmallString<256> Buf;
4250 raw_svector_ostream OS(Buf);
4252 StringRef Values = A.front().front().getString();
4253 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4254 MCAsmMacroArgument Arg;
4255 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4257 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4261 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4266 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4267 if (ActiveMacros.empty())
4268 return TokError("unmatched '.endr' directive");
4270 // The only .repl that should get here are the ones created by
4271 // instantiateMacroLikeBody.
4272 assert(getLexer().is(AsmToken::EndOfStatement));
4278 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4280 const MCExpr *Value;
4281 SMLoc ExprLoc = getLexer().getLoc();
4282 if (parseExpression(Value))
4284 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4286 return Error(ExprLoc, "unexpected expression in _emit");
4287 uint64_t IntValue = MCE->getValue();
4288 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4289 return Error(ExprLoc, "literal value out of range for directive");
4291 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4295 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4296 const MCExpr *Value;
4297 SMLoc ExprLoc = getLexer().getLoc();
4298 if (parseExpression(Value))
4300 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4302 return Error(ExprLoc, "unexpected expression in align");
4303 uint64_t IntValue = MCE->getValue();
4304 if (!isPowerOf2_64(IntValue))
4305 return Error(ExprLoc, "literal value not a power of two greater then zero");
4307 Info.AsmRewrites->push_back(
4308 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4312 // We are comparing pointers, but the pointers are relative to a single string.
4313 // Thus, this should always be deterministic.
4314 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4315 const AsmRewrite *AsmRewriteB) {
4316 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4318 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4321 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4322 // rewrite to the same location. Make sure the SizeDirective rewrite is
4323 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4324 // ensures the sort algorithm is stable.
4325 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4326 AsmRewritePrecedence[AsmRewriteB->Kind])
4329 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4330 AsmRewritePrecedence[AsmRewriteB->Kind])
4332 llvm_unreachable("Unstable rewrite sort.");
4335 bool AsmParser::parseMSInlineAsm(
4336 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4337 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4338 SmallVectorImpl<std::string> &Constraints,
4339 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4340 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4341 SmallVector<void *, 4> InputDecls;
4342 SmallVector<void *, 4> OutputDecls;
4343 SmallVector<bool, 4> InputDeclsAddressOf;
4344 SmallVector<bool, 4> OutputDeclsAddressOf;
4345 SmallVector<std::string, 4> InputConstraints;
4346 SmallVector<std::string, 4> OutputConstraints;
4347 SmallVector<unsigned, 4> ClobberRegs;
4349 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4354 // While we have input, parse each statement.
4355 unsigned InputIdx = 0;
4356 unsigned OutputIdx = 0;
4357 while (getLexer().isNot(AsmToken::Eof)) {
4358 ParseStatementInfo Info(&AsmStrRewrites);
4359 if (parseStatement(Info))
4362 if (Info.ParseError)
4365 if (Info.Opcode == ~0U)
4368 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4370 // Build the list of clobbers, outputs and inputs.
4371 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4372 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4375 if (Operand->isImm())
4378 // Register operand.
4379 if (Operand->isReg() && !Operand->needAddressOf()) {
4380 unsigned NumDefs = Desc.getNumDefs();
4382 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4383 ClobberRegs.push_back(Operand->getReg());
4387 // Expr/Input or Output.
4388 StringRef SymName = Operand->getSymName();
4389 if (SymName.empty())
4392 void *OpDecl = Operand->getOpDecl();
4396 bool isOutput = (i == 1) && Desc.mayStore();
4397 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4400 OutputDecls.push_back(OpDecl);
4401 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4402 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4403 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4405 InputDecls.push_back(OpDecl);
4406 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4407 InputConstraints.push_back(Operand->getConstraint().str());
4408 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4412 // Consider implicit defs to be clobbers. Think of cpuid and push.
4413 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4414 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4415 ClobberRegs.push_back(ImpDefs[I]);
4418 // Set the number of Outputs and Inputs.
4419 NumOutputs = OutputDecls.size();
4420 NumInputs = InputDecls.size();
4422 // Set the unique clobbers.
4423 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4424 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4426 Clobbers.assign(ClobberRegs.size(), std::string());
4427 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4428 raw_string_ostream OS(Clobbers[I]);
4429 IP->printRegName(OS, ClobberRegs[I]);
4432 // Merge the various outputs and inputs. Output are expected first.
4433 if (NumOutputs || NumInputs) {
4434 unsigned NumExprs = NumOutputs + NumInputs;
4435 OpDecls.resize(NumExprs);
4436 Constraints.resize(NumExprs);
4437 for (unsigned i = 0; i < NumOutputs; ++i) {
4438 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4439 Constraints[i] = OutputConstraints[i];
4441 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4442 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4443 Constraints[j] = InputConstraints[i];
4447 // Build the IR assembly string.
4448 std::string AsmStringIR;
4449 raw_string_ostream OS(AsmStringIR);
4450 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4451 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4452 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4453 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4454 E = AsmStrRewrites.end();
4456 AsmRewriteKind Kind = (*I).Kind;
4457 if (Kind == AOK_Delete)
4460 const char *Loc = (*I).Loc.getPointer();
4461 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4463 // Emit everything up to the immediate/expression.
4464 unsigned Len = Loc - AsmStart;
4466 OS << StringRef(AsmStart, Len);
4468 // Skip the original expression.
4469 if (Kind == AOK_Skip) {
4470 AsmStart = Loc + (*I).Len;
4474 unsigned AdditionalSkip = 0;
4475 // Rewrite expressions in $N notation.
4480 OS << "$$" << (*I).Val;
4486 OS << '$' << InputIdx++;
4489 OS << '$' << OutputIdx++;
4491 case AOK_SizeDirective:
4494 case 8: OS << "byte ptr "; break;
4495 case 16: OS << "word ptr "; break;
4496 case 32: OS << "dword ptr "; break;
4497 case 64: OS << "qword ptr "; break;
4498 case 80: OS << "xword ptr "; break;
4499 case 128: OS << "xmmword ptr "; break;
4500 case 256: OS << "ymmword ptr "; break;
4507 unsigned Val = (*I).Val;
4508 OS << ".align " << Val;
4510 // Skip the original immediate.
4511 assert(Val < 10 && "Expected alignment less then 2^10.");
4512 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4515 case AOK_DotOperator:
4520 // Skip the original expression.
4521 AsmStart = Loc + (*I).Len + AdditionalSkip;
4524 // Emit the remainder of the asm string.
4525 if (AsmStart != AsmEnd)
4526 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4528 AsmString = OS.str();
4532 /// \brief Create an MCAsmParser instance.
4533 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4534 MCStreamer &Out, const MCAsmInfo &MAI) {
4535 return new AsmParser(SM, C, Out, MAI);