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_IFNE, DK_IFB, DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF,
354 DK_IFNDEF, DK_IFNOTDEF, 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"
442 bool parseDirectiveIf(SMLoc DirectiveLoc);
443 // ".ifb" or ".ifnb", depending on ExpectBlank.
444 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
445 // ".ifc" or ".ifnc", depending on ExpectEqual.
446 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
448 bool parseDirectiveIfeqs(SMLoc DirectiveLoc);
449 // ".ifdef" or ".ifndef", depending on expect_defined
450 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
451 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
452 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
453 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
454 virtual bool parseEscapedString(std::string &Data);
456 const MCExpr *applyModifierToExpr(const MCExpr *E,
457 MCSymbolRefExpr::VariantKind Variant);
459 // Macro-like directives
460 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
461 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
462 raw_svector_ostream &OS);
463 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
464 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
465 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
466 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
468 // "_emit" or "__emit"
469 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
473 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
476 bool parseDirectiveEnd(SMLoc DirectiveLoc);
478 // ".err" or ".error"
479 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
481 void initializeDirectiveKindMap();
487 extern MCAsmParserExtension *createDarwinAsmParser();
488 extern MCAsmParserExtension *createELFAsmParser();
489 extern MCAsmParserExtension *createCOFFAsmParser();
493 enum { DEFAULT_ADDRSPACE = 0 };
495 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
496 const MCAsmInfo &_MAI)
497 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
498 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
499 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
500 ParsingInlineAsm(false) {
501 // Save the old handler.
502 SavedDiagHandler = SrcMgr.getDiagHandler();
503 SavedDiagContext = SrcMgr.getDiagContext();
504 // Set our own handler which calls the saved handler.
505 SrcMgr.setDiagHandler(DiagHandler, this);
506 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
508 // Initialize the platform / file format parser.
509 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
510 case MCObjectFileInfo::IsCOFF:
511 PlatformParser = createCOFFAsmParser();
512 PlatformParser->Initialize(*this);
514 case MCObjectFileInfo::IsMachO:
515 PlatformParser = createDarwinAsmParser();
516 PlatformParser->Initialize(*this);
519 case MCObjectFileInfo::IsELF:
520 PlatformParser = createELFAsmParser();
521 PlatformParser->Initialize(*this);
525 initializeDirectiveKindMap();
528 AsmParser::~AsmParser() {
529 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
531 // Destroy any macros.
532 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
535 delete it->getValue();
537 delete PlatformParser;
540 void AsmParser::printMacroInstantiations() {
541 // Print the active macro instantiation stack.
542 for (std::vector<MacroInstantiation *>::const_reverse_iterator
543 it = ActiveMacros.rbegin(),
544 ie = ActiveMacros.rend();
546 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
547 "while in macro instantiation");
550 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
551 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
552 printMacroInstantiations();
555 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
556 if (FatalAssemblerWarnings)
557 return Error(L, Msg, Ranges);
558 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
559 printMacroInstantiations();
563 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
565 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
566 printMacroInstantiations();
570 bool AsmParser::enterIncludeFile(const std::string &Filename) {
571 std::string IncludedFile;
572 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
578 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
583 /// Process the specified .incbin file by searching for it in the include paths
584 /// then just emitting the byte contents of the file to the streamer. This
585 /// returns true on failure.
586 bool AsmParser::processIncbinFile(const std::string &Filename) {
587 std::string IncludedFile;
588 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
592 // Pick up the bytes from the file and emit them.
593 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
597 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
598 if (InBuffer != -1) {
599 CurBuffer = InBuffer;
601 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
603 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
606 const AsmToken &AsmParser::Lex() {
607 const AsmToken *tok = &Lexer.Lex();
609 if (tok->is(AsmToken::Eof)) {
610 // If this is the end of an included file, pop the parent file off the
612 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
613 if (ParentIncludeLoc != SMLoc()) {
614 jumpToLoc(ParentIncludeLoc);
619 if (tok->is(AsmToken::Error))
620 Error(Lexer.getErrLoc(), Lexer.getErr());
625 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
626 // Create the initial section, if requested.
627 if (!NoInitialTextSection)
634 AsmCond StartingCondState = TheCondState;
636 // If we are generating dwarf for assembly source files save the initial text
637 // section and generate a .file directive.
638 if (getContext().getGenDwarfForAssembly()) {
639 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
640 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
641 getStreamer().EmitLabel(SectionStartSym);
642 getContext().setGenDwarfSectionStartSym(SectionStartSym);
643 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
645 getContext().getMainFileName());
648 // While we have input, parse each statement.
649 while (Lexer.isNot(AsmToken::Eof)) {
650 ParseStatementInfo Info;
651 if (!parseStatement(Info))
654 // We had an error, validate that one was emitted and recover by skipping to
656 assert(HadError && "Parse statement returned an error, but none emitted!");
657 eatToEndOfStatement();
660 if (TheCondState.TheCond != StartingCondState.TheCond ||
661 TheCondState.Ignore != StartingCondState.Ignore)
662 return TokError("unmatched .ifs or .elses");
664 // Check to see there are no empty DwarfFile slots.
665 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
666 getContext().getMCDwarfFiles();
667 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
668 if (!MCDwarfFiles[i])
669 TokError("unassigned file number: " + Twine(i) + " for .file directives");
672 // Check to see that all assembler local symbols were actually defined.
673 // Targets that don't do subsections via symbols may not want this, though,
674 // so conservatively exclude them. Only do this if we're finalizing, though,
675 // as otherwise we won't necessarilly have seen everything yet.
676 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
677 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
678 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
681 MCSymbol *Sym = i->getValue();
682 // Variable symbols may not be marked as defined, so check those
683 // explicitly. If we know it's a variable, we have a definition for
684 // the purposes of this check.
685 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
686 // FIXME: We would really like to refer back to where the symbol was
687 // first referenced for a source location. We need to add something
688 // to track that. Currently, we just point to the end of the file.
690 getLexer().getLoc(), SourceMgr::DK_Error,
691 "assembler local symbol '" + Sym->getName() + "' not defined");
695 // Finalize the output stream if there are no errors and if the client wants
697 if (!HadError && !NoFinalize)
703 void AsmParser::checkForValidSection() {
704 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
705 TokError("expected section directive before assembly directive");
710 /// \brief Throw away the rest of the line for testing purposes.
711 void AsmParser::eatToEndOfStatement() {
712 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
716 if (Lexer.is(AsmToken::EndOfStatement))
720 StringRef AsmParser::parseStringToEndOfStatement() {
721 const char *Start = getTok().getLoc().getPointer();
723 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
726 const char *End = getTok().getLoc().getPointer();
727 return StringRef(Start, End - Start);
730 StringRef AsmParser::parseStringToComma() {
731 const char *Start = getTok().getLoc().getPointer();
733 while (Lexer.isNot(AsmToken::EndOfStatement) &&
734 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
737 const char *End = getTok().getLoc().getPointer();
738 return StringRef(Start, End - Start);
741 /// \brief Parse a paren expression and return it.
742 /// NOTE: This assumes the leading '(' has already been consumed.
744 /// parenexpr ::= expr)
746 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
747 if (parseExpression(Res))
749 if (Lexer.isNot(AsmToken::RParen))
750 return TokError("expected ')' in parentheses expression");
751 EndLoc = Lexer.getTok().getEndLoc();
756 /// \brief Parse a bracket expression and return it.
757 /// NOTE: This assumes the leading '[' has already been consumed.
759 /// bracketexpr ::= expr]
761 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
762 if (parseExpression(Res))
764 if (Lexer.isNot(AsmToken::RBrac))
765 return TokError("expected ']' in brackets expression");
766 EndLoc = Lexer.getTok().getEndLoc();
771 /// \brief Parse a primary expression and return it.
772 /// primaryexpr ::= (parenexpr
773 /// primaryexpr ::= symbol
774 /// primaryexpr ::= number
775 /// primaryexpr ::= '.'
776 /// primaryexpr ::= ~,+,- primaryexpr
777 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
778 SMLoc FirstTokenLoc = getLexer().getLoc();
779 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
780 switch (FirstTokenKind) {
782 return TokError("unknown token in expression");
783 // If we have an error assume that we've already handled it.
784 case AsmToken::Error:
786 case AsmToken::Exclaim:
787 Lex(); // Eat the operator.
788 if (parsePrimaryExpr(Res, EndLoc))
790 Res = MCUnaryExpr::CreateLNot(Res, getContext());
792 case AsmToken::Dollar:
794 case AsmToken::String:
795 case AsmToken::Identifier: {
796 StringRef Identifier;
797 if (parseIdentifier(Identifier)) {
798 if (FirstTokenKind == AsmToken::Dollar) {
799 if (Lexer.getMAI().getDollarIsPC()) {
800 // This is a '$' reference, which references the current PC. Emit a
801 // temporary label to the streamer and refer to it.
802 MCSymbol *Sym = Ctx.CreateTempSymbol();
804 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
806 EndLoc = FirstTokenLoc;
809 return Error(FirstTokenLoc, "invalid token in expression");
813 // Parse symbol variant
814 std::pair<StringRef, StringRef> Split;
815 if (!MAI.useParensForSymbolVariant()) {
816 Split = Identifier.split('@');
817 } else if (Lexer.is(AsmToken::LParen)) {
818 Lexer.Lex(); // eat (
820 parseIdentifier(VName);
821 if (Lexer.isNot(AsmToken::RParen)) {
822 return Error(Lexer.getTok().getLoc(),
823 "unexpected token in variant, expected ')'");
825 Lexer.Lex(); // eat )
826 Split = std::make_pair(Identifier, VName);
829 EndLoc = SMLoc::getFromPointer(Identifier.end());
831 // This is a symbol reference.
832 StringRef SymbolName = Identifier;
833 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
835 // Lookup the symbol variant if used.
836 if (Split.second.size()) {
837 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
838 if (Variant != MCSymbolRefExpr::VK_Invalid) {
839 SymbolName = Split.first;
840 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
841 Variant = MCSymbolRefExpr::VK_None;
843 return Error(SMLoc::getFromPointer(Split.second.begin()),
844 "invalid variant '" + Split.second + "'");
848 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
850 // If this is an absolute variable reference, substitute it now to preserve
851 // semantics in the face of reassignment.
852 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
854 return Error(EndLoc, "unexpected modifier on variable reference");
856 Res = Sym->getVariableValue();
860 // Otherwise create a symbol ref.
861 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
864 case AsmToken::BigNum:
865 return TokError("literal value out of range for directive");
866 case AsmToken::Integer: {
867 SMLoc Loc = getTok().getLoc();
868 int64_t IntVal = getTok().getIntVal();
869 Res = MCConstantExpr::Create(IntVal, getContext());
870 EndLoc = Lexer.getTok().getEndLoc();
872 // Look for 'b' or 'f' following an Integer as a directional label
873 if (Lexer.getKind() == AsmToken::Identifier) {
874 StringRef IDVal = getTok().getString();
875 // Lookup the symbol variant if used.
876 std::pair<StringRef, StringRef> Split = IDVal.split('@');
877 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
878 if (Split.first.size() != IDVal.size()) {
879 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
880 if (Variant == MCSymbolRefExpr::VK_Invalid) {
881 Variant = MCSymbolRefExpr::VK_None;
882 return TokError("invalid variant '" + Split.second + "'");
886 if (IDVal == "f" || IDVal == "b") {
888 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
889 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
890 if (IDVal == "b" && Sym->isUndefined())
891 return Error(Loc, "invalid reference to undefined symbol");
892 EndLoc = Lexer.getTok().getEndLoc();
893 Lex(); // Eat identifier.
898 case AsmToken::Real: {
899 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
900 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
901 Res = MCConstantExpr::Create(IntVal, getContext());
902 EndLoc = Lexer.getTok().getEndLoc();
906 case AsmToken::Dot: {
907 // This is a '.' reference, which references the current PC. Emit a
908 // temporary label to the streamer and refer to it.
909 MCSymbol *Sym = Ctx.CreateTempSymbol();
911 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
912 EndLoc = Lexer.getTok().getEndLoc();
913 Lex(); // Eat identifier.
916 case AsmToken::LParen:
917 Lex(); // Eat the '('.
918 return parseParenExpr(Res, EndLoc);
919 case AsmToken::LBrac:
920 if (!PlatformParser->HasBracketExpressions())
921 return TokError("brackets expression not supported on this target");
922 Lex(); // Eat the '['.
923 return parseBracketExpr(Res, EndLoc);
924 case AsmToken::Minus:
925 Lex(); // Eat the operator.
926 if (parsePrimaryExpr(Res, EndLoc))
928 Res = MCUnaryExpr::CreateMinus(Res, getContext());
931 Lex(); // Eat the operator.
932 if (parsePrimaryExpr(Res, EndLoc))
934 Res = MCUnaryExpr::CreatePlus(Res, getContext());
936 case AsmToken::Tilde:
937 Lex(); // Eat the operator.
938 if (parsePrimaryExpr(Res, EndLoc))
940 Res = MCUnaryExpr::CreateNot(Res, getContext());
945 bool AsmParser::parseExpression(const MCExpr *&Res) {
947 return parseExpression(Res, EndLoc);
951 AsmParser::applyModifierToExpr(const MCExpr *E,
952 MCSymbolRefExpr::VariantKind Variant) {
953 // Ask the target implementation about this expression first.
954 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
957 // Recurse over the given expression, rebuilding it to apply the given variant
958 // if there is exactly one symbol.
959 switch (E->getKind()) {
961 case MCExpr::Constant:
964 case MCExpr::SymbolRef: {
965 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
967 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
968 TokError("invalid variant on expression '" + getTok().getIdentifier() +
969 "' (already modified)");
973 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
976 case MCExpr::Unary: {
977 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
978 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
981 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
984 case MCExpr::Binary: {
985 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
986 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
987 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
997 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1001 llvm_unreachable("Invalid expression kind!");
1004 /// \brief Parse an expression and return it.
1006 /// expr ::= expr &&,|| expr -> lowest.
1007 /// expr ::= expr |,^,&,! expr
1008 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1009 /// expr ::= expr <<,>> expr
1010 /// expr ::= expr +,- expr
1011 /// expr ::= expr *,/,% expr -> highest.
1012 /// expr ::= primaryexpr
1014 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1015 // Parse the expression.
1017 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1020 // As a special case, we support 'a op b @ modifier' by rewriting the
1021 // expression to include the modifier. This is inefficient, but in general we
1022 // expect users to use 'a@modifier op b'.
1023 if (Lexer.getKind() == AsmToken::At) {
1026 if (Lexer.isNot(AsmToken::Identifier))
1027 return TokError("unexpected symbol modifier following '@'");
1029 MCSymbolRefExpr::VariantKind Variant =
1030 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1031 if (Variant == MCSymbolRefExpr::VK_Invalid)
1032 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1034 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1036 return TokError("invalid modifier '" + getTok().getIdentifier() +
1037 "' (no symbols present)");
1044 // Try to constant fold it up front, if possible.
1046 if (Res->EvaluateAsAbsolute(Value))
1047 Res = MCConstantExpr::Create(Value, getContext());
1052 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1054 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1057 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1060 SMLoc StartLoc = Lexer.getLoc();
1061 if (parseExpression(Expr))
1064 if (!Expr->EvaluateAsAbsolute(Res))
1065 return Error(StartLoc, "expected absolute expression");
1070 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1071 MCBinaryExpr::Opcode &Kind) {
1074 return 0; // not a binop.
1076 // Lowest Precedence: &&, ||
1077 case AsmToken::AmpAmp:
1078 Kind = MCBinaryExpr::LAnd;
1080 case AsmToken::PipePipe:
1081 Kind = MCBinaryExpr::LOr;
1084 // Low Precedence: |, &, ^
1086 // FIXME: gas seems to support '!' as an infix operator?
1087 case AsmToken::Pipe:
1088 Kind = MCBinaryExpr::Or;
1090 case AsmToken::Caret:
1091 Kind = MCBinaryExpr::Xor;
1094 Kind = MCBinaryExpr::And;
1097 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1098 case AsmToken::EqualEqual:
1099 Kind = MCBinaryExpr::EQ;
1101 case AsmToken::ExclaimEqual:
1102 case AsmToken::LessGreater:
1103 Kind = MCBinaryExpr::NE;
1105 case AsmToken::Less:
1106 Kind = MCBinaryExpr::LT;
1108 case AsmToken::LessEqual:
1109 Kind = MCBinaryExpr::LTE;
1111 case AsmToken::Greater:
1112 Kind = MCBinaryExpr::GT;
1114 case AsmToken::GreaterEqual:
1115 Kind = MCBinaryExpr::GTE;
1118 // Intermediate Precedence: <<, >>
1119 case AsmToken::LessLess:
1120 Kind = MCBinaryExpr::Shl;
1122 case AsmToken::GreaterGreater:
1123 Kind = MCBinaryExpr::Shr;
1126 // High Intermediate Precedence: +, -
1127 case AsmToken::Plus:
1128 Kind = MCBinaryExpr::Add;
1130 case AsmToken::Minus:
1131 Kind = MCBinaryExpr::Sub;
1134 // Highest Precedence: *, /, %
1135 case AsmToken::Star:
1136 Kind = MCBinaryExpr::Mul;
1138 case AsmToken::Slash:
1139 Kind = MCBinaryExpr::Div;
1141 case AsmToken::Percent:
1142 Kind = MCBinaryExpr::Mod;
1147 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1148 /// Res contains the LHS of the expression on input.
1149 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1152 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1153 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1155 // If the next token is lower precedence than we are allowed to eat, return
1156 // successfully with what we ate already.
1157 if (TokPrec < Precedence)
1162 // Eat the next primary expression.
1164 if (parsePrimaryExpr(RHS, EndLoc))
1167 // If BinOp binds less tightly with RHS than the operator after RHS, let
1168 // the pending operator take RHS as its LHS.
1169 MCBinaryExpr::Opcode Dummy;
1170 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1171 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1174 // Merge LHS and RHS according to operator.
1175 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1180 /// ::= EndOfStatement
1181 /// ::= Label* Directive ...Operands... EndOfStatement
1182 /// ::= Label* Identifier OperandList* EndOfStatement
1183 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1184 if (Lexer.is(AsmToken::EndOfStatement)) {
1190 // Statements always start with an identifier or are a full line comment.
1191 AsmToken ID = getTok();
1192 SMLoc IDLoc = ID.getLoc();
1194 int64_t LocalLabelVal = -1;
1195 // A full line comment is a '#' as the first token.
1196 if (Lexer.is(AsmToken::Hash))
1197 return parseCppHashLineFilenameComment(IDLoc);
1199 // Allow an integer followed by a ':' as a directional local label.
1200 if (Lexer.is(AsmToken::Integer)) {
1201 LocalLabelVal = getTok().getIntVal();
1202 if (LocalLabelVal < 0) {
1203 if (!TheCondState.Ignore)
1204 return TokError("unexpected token at start of statement");
1207 IDVal = getTok().getString();
1208 Lex(); // Consume the integer token to be used as an identifier token.
1209 if (Lexer.getKind() != AsmToken::Colon) {
1210 if (!TheCondState.Ignore)
1211 return TokError("unexpected token at start of statement");
1214 } else if (Lexer.is(AsmToken::Dot)) {
1215 // Treat '.' as a valid identifier in this context.
1218 } else if (parseIdentifier(IDVal)) {
1219 if (!TheCondState.Ignore)
1220 return TokError("unexpected token at start of statement");
1224 // Handle conditional assembly here before checking for skipping. We
1225 // have to do this so that .endif isn't skipped in a ".if 0" block for
1227 StringMap<DirectiveKind>::const_iterator DirKindIt =
1228 DirectiveKindMap.find(IDVal);
1229 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1231 : DirKindIt->getValue();
1237 return parseDirectiveIf(IDLoc);
1239 return parseDirectiveIfb(IDLoc, true);
1241 return parseDirectiveIfb(IDLoc, false);
1243 return parseDirectiveIfc(IDLoc, true);
1245 return parseDirectiveIfeqs(IDLoc);
1247 return parseDirectiveIfc(IDLoc, false);
1249 return parseDirectiveIfdef(IDLoc, true);
1252 return parseDirectiveIfdef(IDLoc, false);
1254 return parseDirectiveElseIf(IDLoc);
1256 return parseDirectiveElse(IDLoc);
1258 return parseDirectiveEndIf(IDLoc);
1261 // Ignore the statement if in the middle of inactive conditional
1263 if (TheCondState.Ignore) {
1264 eatToEndOfStatement();
1268 // FIXME: Recurse on local labels?
1270 // See what kind of statement we have.
1271 switch (Lexer.getKind()) {
1272 case AsmToken::Colon: {
1273 checkForValidSection();
1275 // identifier ':' -> Label.
1278 // Diagnose attempt to use '.' as a label.
1280 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1282 // Diagnose attempt to use a variable as a label.
1284 // FIXME: Diagnostics. Note the location of the definition as a label.
1285 // FIXME: This doesn't diagnose assignment to a symbol which has been
1286 // implicitly marked as external.
1288 if (LocalLabelVal == -1)
1289 Sym = getContext().GetOrCreateSymbol(IDVal);
1291 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1292 if (!Sym->isUndefined() || Sym->isVariable())
1293 return Error(IDLoc, "invalid symbol redefinition");
1296 if (!ParsingInlineAsm)
1299 // If we are generating dwarf for assembly source files then gather the
1300 // info to make a dwarf label entry for this label if needed.
1301 if (getContext().getGenDwarfForAssembly())
1302 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1305 getTargetParser().onLabelParsed(Sym);
1307 // Consume any end of statement token, if present, to avoid spurious
1308 // AddBlankLine calls().
1309 if (Lexer.is(AsmToken::EndOfStatement)) {
1311 if (Lexer.is(AsmToken::Eof))
1318 case AsmToken::Equal:
1319 // identifier '=' ... -> assignment statement
1322 return parseAssignment(IDVal, true);
1324 default: // Normal instruction or directive.
1328 // If macros are enabled, check to see if this is a macro instantiation.
1329 if (areMacrosEnabled())
1330 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1331 return handleMacroEntry(M, IDLoc);
1334 // Otherwise, we have a normal instruction or directive.
1336 // Directives start with "."
1337 if (IDVal[0] == '.' && IDVal != ".") {
1338 // There are several entities interested in parsing directives:
1340 // 1. The target-specific assembly parser. Some directives are target
1341 // specific or may potentially behave differently on certain targets.
1342 // 2. Asm parser extensions. For example, platform-specific parsers
1343 // (like the ELF parser) register themselves as extensions.
1344 // 3. The generic directive parser implemented by this class. These are
1345 // all the directives that behave in a target and platform independent
1346 // manner, or at least have a default behavior that's shared between
1347 // all targets and platforms.
1349 // First query the target-specific parser. It will return 'true' if it
1350 // isn't interested in this directive.
1351 if (!getTargetParser().ParseDirective(ID))
1354 // Next, check the extension directive map to see if any extension has
1355 // registered itself to parse this directive.
1356 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1357 ExtensionDirectiveMap.lookup(IDVal);
1359 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1361 // Finally, if no one else is interested in this directive, it must be
1362 // generic and familiar to this class.
1368 return parseDirectiveSet(IDVal, true);
1370 return parseDirectiveSet(IDVal, false);
1372 return parseDirectiveAscii(IDVal, false);
1375 return parseDirectiveAscii(IDVal, true);
1377 return parseDirectiveValue(1);
1381 return parseDirectiveValue(2);
1385 return parseDirectiveValue(4);
1388 return parseDirectiveValue(8);
1390 return parseDirectiveOctaValue();
1393 return parseDirectiveRealValue(APFloat::IEEEsingle);
1395 return parseDirectiveRealValue(APFloat::IEEEdouble);
1397 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1398 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1401 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1402 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1405 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1407 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1409 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1411 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1413 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1415 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1417 return parseDirectiveOrg();
1419 return parseDirectiveFill();
1421 return parseDirectiveZero();
1423 eatToEndOfStatement(); // .extern is the default, ignore it.
1427 return parseDirectiveSymbolAttribute(MCSA_Global);
1428 case DK_LAZY_REFERENCE:
1429 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1430 case DK_NO_DEAD_STRIP:
1431 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1432 case DK_SYMBOL_RESOLVER:
1433 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1434 case DK_PRIVATE_EXTERN:
1435 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1437 return parseDirectiveSymbolAttribute(MCSA_Reference);
1438 case DK_WEAK_DEFINITION:
1439 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1440 case DK_WEAK_REFERENCE:
1441 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1442 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1443 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1446 return parseDirectiveComm(/*IsLocal=*/false);
1448 return parseDirectiveComm(/*IsLocal=*/true);
1450 return parseDirectiveAbort();
1452 return parseDirectiveInclude();
1454 return parseDirectiveIncbin();
1457 return TokError(Twine(IDVal) + " not supported yet");
1459 return parseDirectiveRept(IDLoc, IDVal);
1461 return parseDirectiveIrp(IDLoc);
1463 return parseDirectiveIrpc(IDLoc);
1465 return parseDirectiveEndr(IDLoc);
1466 case DK_BUNDLE_ALIGN_MODE:
1467 return parseDirectiveBundleAlignMode();
1468 case DK_BUNDLE_LOCK:
1469 return parseDirectiveBundleLock();
1470 case DK_BUNDLE_UNLOCK:
1471 return parseDirectiveBundleUnlock();
1473 return parseDirectiveLEB128(true);
1475 return parseDirectiveLEB128(false);
1478 return parseDirectiveSpace(IDVal);
1480 return parseDirectiveFile(IDLoc);
1482 return parseDirectiveLine();
1484 return parseDirectiveLoc();
1486 return parseDirectiveStabs();
1487 case DK_CFI_SECTIONS:
1488 return parseDirectiveCFISections();
1489 case DK_CFI_STARTPROC:
1490 return parseDirectiveCFIStartProc();
1491 case DK_CFI_ENDPROC:
1492 return parseDirectiveCFIEndProc();
1493 case DK_CFI_DEF_CFA:
1494 return parseDirectiveCFIDefCfa(IDLoc);
1495 case DK_CFI_DEF_CFA_OFFSET:
1496 return parseDirectiveCFIDefCfaOffset();
1497 case DK_CFI_ADJUST_CFA_OFFSET:
1498 return parseDirectiveCFIAdjustCfaOffset();
1499 case DK_CFI_DEF_CFA_REGISTER:
1500 return parseDirectiveCFIDefCfaRegister(IDLoc);
1502 return parseDirectiveCFIOffset(IDLoc);
1503 case DK_CFI_REL_OFFSET:
1504 return parseDirectiveCFIRelOffset(IDLoc);
1505 case DK_CFI_PERSONALITY:
1506 return parseDirectiveCFIPersonalityOrLsda(true);
1508 return parseDirectiveCFIPersonalityOrLsda(false);
1509 case DK_CFI_REMEMBER_STATE:
1510 return parseDirectiveCFIRememberState();
1511 case DK_CFI_RESTORE_STATE:
1512 return parseDirectiveCFIRestoreState();
1513 case DK_CFI_SAME_VALUE:
1514 return parseDirectiveCFISameValue(IDLoc);
1515 case DK_CFI_RESTORE:
1516 return parseDirectiveCFIRestore(IDLoc);
1518 return parseDirectiveCFIEscape();
1519 case DK_CFI_SIGNAL_FRAME:
1520 return parseDirectiveCFISignalFrame();
1521 case DK_CFI_UNDEFINED:
1522 return parseDirectiveCFIUndefined(IDLoc);
1523 case DK_CFI_REGISTER:
1524 return parseDirectiveCFIRegister(IDLoc);
1525 case DK_CFI_WINDOW_SAVE:
1526 return parseDirectiveCFIWindowSave();
1529 return parseDirectiveMacrosOnOff(IDVal);
1531 return parseDirectiveMacro(IDLoc);
1534 return parseDirectiveEndMacro(IDVal);
1536 return parseDirectivePurgeMacro(IDLoc);
1538 return parseDirectiveEnd(IDLoc);
1540 return parseDirectiveError(IDLoc, false);
1542 return parseDirectiveError(IDLoc, true);
1545 return Error(IDLoc, "unknown directive");
1548 // __asm _emit or __asm __emit
1549 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1550 IDVal == "_EMIT" || IDVal == "__EMIT"))
1551 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1554 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1555 return parseDirectiveMSAlign(IDLoc, Info);
1557 checkForValidSection();
1559 // Canonicalize the opcode to lower case.
1560 std::string OpcodeStr = IDVal.lower();
1561 ParseInstructionInfo IInfo(Info.AsmRewrites);
1562 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1563 Info.ParsedOperands);
1564 Info.ParseError = HadError;
1566 // Dump the parsed representation, if requested.
1567 if (getShowParsedOperands()) {
1568 SmallString<256> Str;
1569 raw_svector_ostream OS(Str);
1570 OS << "parsed instruction: [";
1571 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1574 Info.ParsedOperands[i]->print(OS);
1578 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1581 // If we are generating dwarf for assembly source files and the current
1582 // section is the initial text section then generate a .loc directive for
1584 if (!HadError && getContext().getGenDwarfForAssembly() &&
1585 getContext().getGenDwarfSection() ==
1586 getStreamer().getCurrentSection().first) {
1588 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1590 // If we previously parsed a cpp hash file line comment then make sure the
1591 // current Dwarf File is for the CppHashFilename if not then emit the
1592 // Dwarf File table for it and adjust the line number for the .loc.
1593 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1594 getContext().getMCDwarfFiles();
1595 if (CppHashFilename.size() != 0) {
1596 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1598 getStreamer().EmitDwarfFileDirective(
1599 getContext().nextGenDwarfFileNumber(), StringRef(),
1602 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1603 // cache with the different Loc from the call above we save the last
1604 // info we queried here with SrcMgr.FindLineNumber().
1605 unsigned CppHashLocLineNo;
1606 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1607 CppHashLocLineNo = LastQueryLine;
1609 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1610 LastQueryLine = CppHashLocLineNo;
1611 LastQueryIDLoc = CppHashLoc;
1612 LastQueryBuffer = CppHashBuf;
1614 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1617 getStreamer().EmitDwarfLocDirective(
1618 getContext().getGenDwarfFileNumber(), Line, 0,
1619 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1623 // If parsing succeeded, match the instruction.
1626 HadError = getTargetParser().MatchAndEmitInstruction(
1627 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1631 // Don't skip the rest of the line, the instruction parser is responsible for
1636 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1637 /// since they may not be able to be tokenized to get to the end of line token.
1638 void AsmParser::eatToEndOfLine() {
1639 if (!Lexer.is(AsmToken::EndOfStatement))
1640 Lexer.LexUntilEndOfLine();
1645 /// parseCppHashLineFilenameComment as this:
1646 /// ::= # number "filename"
1647 /// or just as a full line comment if it doesn't have a number and a string.
1648 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1649 Lex(); // Eat the hash token.
1651 if (getLexer().isNot(AsmToken::Integer)) {
1652 // Consume the line since in cases it is not a well-formed line directive,
1653 // as if were simply a full line comment.
1658 int64_t LineNumber = getTok().getIntVal();
1661 if (getLexer().isNot(AsmToken::String)) {
1666 StringRef Filename = getTok().getString();
1667 // Get rid of the enclosing quotes.
1668 Filename = Filename.substr(1, Filename.size() - 2);
1670 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1672 CppHashFilename = Filename;
1673 CppHashLineNumber = LineNumber;
1674 CppHashBuf = CurBuffer;
1676 // Ignore any trailing characters, they're just comment.
1681 /// \brief will use the last parsed cpp hash line filename comment
1682 /// for the Filename and LineNo if any in the diagnostic.
1683 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1684 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1685 raw_ostream &OS = errs();
1687 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1688 const SMLoc &DiagLoc = Diag.getLoc();
1689 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1690 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1692 // Like SourceMgr::printMessage() we need to print the include stack if any
1693 // before printing the message.
1694 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1695 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1696 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1697 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1700 // If we have not parsed a cpp hash line filename comment or the source
1701 // manager changed or buffer changed (like in a nested include) then just
1702 // print the normal diagnostic using its Filename and LineNo.
1703 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1704 DiagBuf != CppHashBuf) {
1705 if (Parser->SavedDiagHandler)
1706 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1712 // Use the CppHashFilename and calculate a line number based on the
1713 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1715 const std::string &Filename = Parser->CppHashFilename;
1717 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1718 int CppHashLocLineNo =
1719 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1721 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1723 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1724 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1725 Diag.getLineContents(), Diag.getRanges());
1727 if (Parser->SavedDiagHandler)
1728 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1730 NewDiag.print(0, OS);
1733 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1734 // difference being that that function accepts '@' as part of identifiers and
1735 // we can't do that. AsmLexer.cpp should probably be changed to handle
1736 // '@' as a special case when needed.
1737 static bool isIdentifierChar(char c) {
1738 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1742 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1743 ArrayRef<MCAsmMacroParameter> Parameters,
1744 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1745 unsigned NParameters = Parameters.size();
1746 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1747 return Error(L, "Wrong number of arguments");
1749 // A macro without parameters is handled differently on Darwin:
1750 // gas accepts no arguments and does no substitutions
1751 while (!Body.empty()) {
1752 // Scan for the next substitution.
1753 std::size_t End = Body.size(), Pos = 0;
1754 for (; Pos != End; ++Pos) {
1755 // Check for a substitution or escape.
1756 if (IsDarwin && !NParameters) {
1757 // This macro has no parameters, look for $0, $1, etc.
1758 if (Body[Pos] != '$' || Pos + 1 == End)
1761 char Next = Body[Pos + 1];
1762 if (Next == '$' || Next == 'n' ||
1763 isdigit(static_cast<unsigned char>(Next)))
1766 // This macro has parameters, look for \foo, \bar, etc.
1767 if (Body[Pos] == '\\' && Pos + 1 != End)
1773 OS << Body.slice(0, Pos);
1775 // Check if we reached the end.
1779 if (IsDarwin && !NParameters) {
1780 switch (Body[Pos + 1]) {
1786 // $n => number of arguments
1791 // $[0-9] => argument
1793 // Missing arguments are ignored.
1794 unsigned Index = Body[Pos + 1] - '0';
1795 if (Index >= A.size())
1798 // Otherwise substitute with the token values, with spaces eliminated.
1799 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1800 ie = A[Index].end();
1802 OS << it->getString();
1808 unsigned I = Pos + 1;
1809 while (isIdentifierChar(Body[I]) && I + 1 != End)
1812 const char *Begin = Body.data() + Pos + 1;
1813 StringRef Argument(Begin, I - (Pos + 1));
1815 for (; Index < NParameters; ++Index)
1816 if (Parameters[Index].Name == Argument)
1819 if (Index == NParameters) {
1820 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1823 OS << '\\' << Argument;
1827 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1828 ie = A[Index].end();
1830 if (it->getKind() == AsmToken::String)
1831 OS << it->getStringContents();
1833 OS << it->getString();
1835 Pos += 1 + Argument.size();
1838 // Update the scan point.
1839 Body = Body.substr(Pos);
1845 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1846 SMLoc EL, MemoryBuffer *I)
1847 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1850 static bool isOperator(AsmToken::TokenKind kind) {
1854 case AsmToken::Plus:
1855 case AsmToken::Minus:
1856 case AsmToken::Tilde:
1857 case AsmToken::Slash:
1858 case AsmToken::Star:
1860 case AsmToken::Equal:
1861 case AsmToken::EqualEqual:
1862 case AsmToken::Pipe:
1863 case AsmToken::PipePipe:
1864 case AsmToken::Caret:
1866 case AsmToken::AmpAmp:
1867 case AsmToken::Exclaim:
1868 case AsmToken::ExclaimEqual:
1869 case AsmToken::Percent:
1870 case AsmToken::Less:
1871 case AsmToken::LessEqual:
1872 case AsmToken::LessLess:
1873 case AsmToken::LessGreater:
1874 case AsmToken::Greater:
1875 case AsmToken::GreaterEqual:
1876 case AsmToken::GreaterGreater:
1882 class AsmLexerSkipSpaceRAII {
1884 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1885 Lexer.setSkipSpace(SkipSpace);
1888 ~AsmLexerSkipSpaceRAII() {
1889 Lexer.setSkipSpace(true);
1897 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA) {
1898 unsigned ParenLevel = 0;
1899 unsigned AddTokens = 0;
1901 // Darwin doesn't use spaces to delmit arguments.
1902 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1905 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1906 return TokError("unexpected token in macro instantiation");
1908 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1911 if (Lexer.is(AsmToken::Space)) {
1912 Lex(); // Eat spaces
1914 // Spaces can delimit parameters, but could also be part an expression.
1915 // If the token after a space is an operator, add the token and the next
1916 // one into this argument
1918 if (isOperator(Lexer.getKind())) {
1919 // Check to see whether the token is used as an operator,
1920 // or part of an identifier
1921 const char *NextChar = getTok().getEndLoc().getPointer();
1922 if (*NextChar == ' ')
1926 if (!AddTokens && ParenLevel == 0) {
1932 // handleMacroEntry relies on not advancing the lexer here
1933 // to be able to fill in the remaining default parameter values
1934 if (Lexer.is(AsmToken::EndOfStatement))
1937 // Adjust the current parentheses level.
1938 if (Lexer.is(AsmToken::LParen))
1940 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1943 // Append the token to the current argument list.
1944 MA.push_back(getTok());
1950 if (ParenLevel != 0)
1951 return TokError("unbalanced parentheses in macro argument");
1955 // Parse the macro instantiation arguments.
1956 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1957 MCAsmMacroArguments &A) {
1958 const unsigned NParameters = M ? M->Parameters.size() : 0;
1959 bool NamedParametersFound = false;
1960 SmallVector<SMLoc, 4> FALocs;
1962 A.resize(NParameters);
1963 FALocs.resize(NParameters);
1965 // Parse two kinds of macro invocations:
1966 // - macros defined without any parameters accept an arbitrary number of them
1967 // - macros defined with parameters accept at most that many of them
1968 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1970 SMLoc IDLoc = Lexer.getLoc();
1971 MCAsmMacroParameter FA;
1973 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1974 if (parseIdentifier(FA.Name)) {
1975 Error(IDLoc, "invalid argument identifier for formal argument");
1976 eatToEndOfStatement();
1980 if (!Lexer.is(AsmToken::Equal)) {
1981 TokError("expected '=' after formal parameter identifier");
1982 eatToEndOfStatement();
1987 NamedParametersFound = true;
1990 if (NamedParametersFound && FA.Name.empty()) {
1991 Error(IDLoc, "cannot mix positional and keyword arguments");
1992 eatToEndOfStatement();
1996 if (parseMacroArgument(FA.Value))
1999 unsigned PI = Parameter;
2000 if (!FA.Name.empty()) {
2002 for (FAI = 0; FAI < NParameters; ++FAI)
2003 if (M->Parameters[FAI].Name == FA.Name)
2006 if (FAI >= NParameters) {
2008 "parameter named '" + FA.Name + "' does not exist for macro '" +
2015 if (!FA.Value.empty()) {
2020 if (FALocs.size() <= PI)
2021 FALocs.resize(PI + 1);
2023 FALocs[PI] = Lexer.getLoc();
2026 // At the end of the statement, fill in remaining arguments that have
2027 // default values. If there aren't any, then the next argument is
2028 // required but missing
2029 if (Lexer.is(AsmToken::EndOfStatement)) {
2030 bool Failure = false;
2031 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2032 if (A[FAI].empty()) {
2033 if (M->Parameters[FAI].Required) {
2034 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2035 "missing value for required parameter "
2036 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2040 if (!M->Parameters[FAI].Value.empty())
2041 A[FAI] = M->Parameters[FAI].Value;
2047 if (Lexer.is(AsmToken::Comma))
2051 return TokError("too many positional arguments");
2054 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2055 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2056 return (I == MacroMap.end()) ? NULL : I->getValue();
2059 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2060 MacroMap[Name] = new MCAsmMacro(Macro);
2063 void AsmParser::undefineMacro(StringRef Name) {
2064 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2065 if (I != MacroMap.end()) {
2066 delete I->getValue();
2071 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2072 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2073 // this, although we should protect against infinite loops.
2074 if (ActiveMacros.size() == 20)
2075 return TokError("macros cannot be nested more than 20 levels deep");
2077 MCAsmMacroArguments A;
2078 if (parseMacroArguments(M, A))
2081 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2082 // to hold the macro body with substitutions.
2083 SmallString<256> Buf;
2084 StringRef Body = M->Body;
2085 raw_svector_ostream OS(Buf);
2087 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2090 // We include the .endmacro in the buffer as our cue to exit the macro
2092 OS << ".endmacro\n";
2094 MemoryBuffer *Instantiation =
2095 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2097 // Create the macro instantiation object and add to the current macro
2098 // instantiation stack.
2099 MacroInstantiation *MI = new MacroInstantiation(
2100 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2101 ActiveMacros.push_back(MI);
2103 // Jump to the macro instantiation and prime the lexer.
2104 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2105 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2111 void AsmParser::handleMacroExit() {
2112 // Jump to the EndOfStatement we should return to, and consume it.
2113 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2116 // Pop the instantiation entry.
2117 delete ActiveMacros.back();
2118 ActiveMacros.pop_back();
2121 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2122 switch (Value->getKind()) {
2123 case MCExpr::Binary: {
2124 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2125 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2127 case MCExpr::Target:
2128 case MCExpr::Constant:
2130 case MCExpr::SymbolRef: {
2132 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2134 return isUsedIn(Sym, S.getVariableValue());
2138 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2141 llvm_unreachable("Unknown expr kind!");
2144 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2146 // FIXME: Use better location, we should use proper tokens.
2147 SMLoc EqualLoc = Lexer.getLoc();
2149 const MCExpr *Value;
2150 if (parseExpression(Value))
2153 // Note: we don't count b as used in "a = b". This is to allow
2157 if (Lexer.isNot(AsmToken::EndOfStatement))
2158 return TokError("unexpected token in assignment");
2160 // Eat the end of statement marker.
2163 // Validate that the LHS is allowed to be a variable (either it has not been
2164 // used as a symbol, or it is an absolute symbol).
2165 MCSymbol *Sym = getContext().LookupSymbol(Name);
2167 // Diagnose assignment to a label.
2169 // FIXME: Diagnostics. Note the location of the definition as a label.
2170 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2171 if (isUsedIn(Sym, Value))
2172 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2173 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2174 ; // Allow redefinitions of undefined symbols only used in directives.
2175 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2176 ; // Allow redefinitions of variables that haven't yet been used.
2177 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2178 return Error(EqualLoc, "redefinition of '" + Name + "'");
2179 else if (!Sym->isVariable())
2180 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2181 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2182 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2185 // Don't count these checks as uses.
2186 Sym->setUsed(false);
2187 } else if (Name == ".") {
2188 if (Out.EmitValueToOffset(Value, 0)) {
2189 Error(EqualLoc, "expected absolute expression");
2190 eatToEndOfStatement();
2194 Sym = getContext().GetOrCreateSymbol(Name);
2196 // Do the assignment.
2197 Out.EmitAssignment(Sym, Value);
2199 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2204 /// parseIdentifier:
2207 bool AsmParser::parseIdentifier(StringRef &Res) {
2208 // The assembler has relaxed rules for accepting identifiers, in particular we
2209 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2210 // separate tokens. At this level, we have already lexed so we cannot (currently)
2211 // handle this as a context dependent token, instead we detect adjacent tokens
2212 // and return the combined identifier.
2213 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2214 SMLoc PrefixLoc = getLexer().getLoc();
2216 // Consume the prefix character, and check for a following identifier.
2218 if (Lexer.isNot(AsmToken::Identifier))
2221 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2222 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2225 // Construct the joined identifier and consume the token.
2227 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2232 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2235 Res = getTok().getIdentifier();
2237 Lex(); // Consume the identifier token.
2242 /// parseDirectiveSet:
2243 /// ::= .equ identifier ',' expression
2244 /// ::= .equiv identifier ',' expression
2245 /// ::= .set identifier ',' expression
2246 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2249 if (parseIdentifier(Name))
2250 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2252 if (getLexer().isNot(AsmToken::Comma))
2253 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2256 return parseAssignment(Name, allow_redef, true);
2259 bool AsmParser::parseEscapedString(std::string &Data) {
2260 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2263 StringRef Str = getTok().getStringContents();
2264 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2265 if (Str[i] != '\\') {
2270 // Recognize escaped characters. Note that this escape semantics currently
2271 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2274 return TokError("unexpected backslash at end of string");
2276 // Recognize octal sequences.
2277 if ((unsigned)(Str[i] - '0') <= 7) {
2278 // Consume up to three octal characters.
2279 unsigned Value = Str[i] - '0';
2281 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2283 Value = Value * 8 + (Str[i] - '0');
2285 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2287 Value = Value * 8 + (Str[i] - '0');
2292 return TokError("invalid octal escape sequence (out of range)");
2294 Data += (unsigned char)Value;
2298 // Otherwise recognize individual escapes.
2301 // Just reject invalid escape sequences for now.
2302 return TokError("invalid escape sequence (unrecognized character)");
2304 case 'b': Data += '\b'; break;
2305 case 'f': Data += '\f'; break;
2306 case 'n': Data += '\n'; break;
2307 case 'r': Data += '\r'; break;
2308 case 't': Data += '\t'; break;
2309 case '"': Data += '"'; break;
2310 case '\\': Data += '\\'; break;
2317 /// parseDirectiveAscii:
2318 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2319 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2320 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2321 checkForValidSection();
2324 if (getLexer().isNot(AsmToken::String))
2325 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2328 if (parseEscapedString(Data))
2331 getStreamer().EmitBytes(Data);
2333 getStreamer().EmitBytes(StringRef("\0", 1));
2337 if (getLexer().is(AsmToken::EndOfStatement))
2340 if (getLexer().isNot(AsmToken::Comma))
2341 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2350 /// parseDirectiveValue
2351 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2352 bool AsmParser::parseDirectiveValue(unsigned Size) {
2353 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2354 checkForValidSection();
2357 const MCExpr *Value;
2358 SMLoc ExprLoc = getLexer().getLoc();
2359 if (parseExpression(Value))
2362 // Special case constant expressions to match code generator.
2363 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2364 assert(Size <= 8 && "Invalid size");
2365 uint64_t IntValue = MCE->getValue();
2366 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2367 return Error(ExprLoc, "literal value out of range for directive");
2368 getStreamer().EmitIntValue(IntValue, Size);
2370 getStreamer().EmitValue(Value, Size);
2372 if (getLexer().is(AsmToken::EndOfStatement))
2375 // FIXME: Improve diagnostic.
2376 if (getLexer().isNot(AsmToken::Comma))
2377 return TokError("unexpected token in directive");
2386 /// ParseDirectiveOctaValue
2387 /// ::= .octa [ hexconstant (, hexconstant)* ]
2388 bool AsmParser::parseDirectiveOctaValue() {
2389 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2390 checkForValidSection();
2393 if (Lexer.getKind() == AsmToken::Error)
2395 if (Lexer.getKind() != AsmToken::Integer &&
2396 Lexer.getKind() != AsmToken::BigNum)
2397 return TokError("unknown token in expression");
2399 SMLoc ExprLoc = getLexer().getLoc();
2400 APInt IntValue = getTok().getAPIntVal();
2404 if (IntValue.isIntN(64)) {
2406 lo = IntValue.getZExtValue();
2407 } else if (IntValue.isIntN(128)) {
2408 // It might actually have more than 128 bits, but the top ones are zero.
2409 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2410 lo = IntValue.getLoBits(64).getZExtValue();
2412 return Error(ExprLoc, "literal value out of range for directive");
2414 if (MAI.isLittleEndian()) {
2415 getStreamer().EmitIntValue(lo, 8);
2416 getStreamer().EmitIntValue(hi, 8);
2418 getStreamer().EmitIntValue(hi, 8);
2419 getStreamer().EmitIntValue(lo, 8);
2422 if (getLexer().is(AsmToken::EndOfStatement))
2425 // FIXME: Improve diagnostic.
2426 if (getLexer().isNot(AsmToken::Comma))
2427 return TokError("unexpected token in directive");
2436 /// parseDirectiveRealValue
2437 /// ::= (.single | .double) [ expression (, expression)* ]
2438 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2439 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2440 checkForValidSection();
2443 // We don't truly support arithmetic on floating point expressions, so we
2444 // have to manually parse unary prefixes.
2446 if (getLexer().is(AsmToken::Minus)) {
2449 } else if (getLexer().is(AsmToken::Plus))
2452 if (getLexer().isNot(AsmToken::Integer) &&
2453 getLexer().isNot(AsmToken::Real) &&
2454 getLexer().isNot(AsmToken::Identifier))
2455 return TokError("unexpected token in directive");
2457 // Convert to an APFloat.
2458 APFloat Value(Semantics);
2459 StringRef IDVal = getTok().getString();
2460 if (getLexer().is(AsmToken::Identifier)) {
2461 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2462 Value = APFloat::getInf(Semantics);
2463 else if (!IDVal.compare_lower("nan"))
2464 Value = APFloat::getNaN(Semantics, false, ~0);
2466 return TokError("invalid floating point literal");
2467 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2468 APFloat::opInvalidOp)
2469 return TokError("invalid floating point literal");
2473 // Consume the numeric token.
2476 // Emit the value as an integer.
2477 APInt AsInt = Value.bitcastToAPInt();
2478 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2479 AsInt.getBitWidth() / 8);
2481 if (getLexer().is(AsmToken::EndOfStatement))
2484 if (getLexer().isNot(AsmToken::Comma))
2485 return TokError("unexpected token in directive");
2494 /// parseDirectiveZero
2495 /// ::= .zero expression
2496 bool AsmParser::parseDirectiveZero() {
2497 checkForValidSection();
2500 if (parseAbsoluteExpression(NumBytes))
2504 if (getLexer().is(AsmToken::Comma)) {
2506 if (parseAbsoluteExpression(Val))
2510 if (getLexer().isNot(AsmToken::EndOfStatement))
2511 return TokError("unexpected token in '.zero' directive");
2515 getStreamer().EmitFill(NumBytes, Val);
2520 /// parseDirectiveFill
2521 /// ::= .fill expression [ , expression [ , expression ] ]
2522 bool AsmParser::parseDirectiveFill() {
2523 checkForValidSection();
2525 SMLoc RepeatLoc = getLexer().getLoc();
2527 if (parseAbsoluteExpression(NumValues))
2530 if (NumValues < 0) {
2532 "'.fill' directive with negative repeat count has no effect");
2536 int64_t FillSize = 1;
2537 int64_t FillExpr = 0;
2539 SMLoc SizeLoc, ExprLoc;
2540 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2541 if (getLexer().isNot(AsmToken::Comma))
2542 return TokError("unexpected token in '.fill' directive");
2545 SizeLoc = getLexer().getLoc();
2546 if (parseAbsoluteExpression(FillSize))
2549 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2550 if (getLexer().isNot(AsmToken::Comma))
2551 return TokError("unexpected token in '.fill' directive");
2554 ExprLoc = getLexer().getLoc();
2555 if (parseAbsoluteExpression(FillExpr))
2558 if (getLexer().isNot(AsmToken::EndOfStatement))
2559 return TokError("unexpected token in '.fill' directive");
2566 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2570 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2574 if (!isUInt<32>(FillExpr) && FillSize > 4)
2575 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2577 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2578 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2580 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2581 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2582 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2588 /// parseDirectiveOrg
2589 /// ::= .org expression [ , expression ]
2590 bool AsmParser::parseDirectiveOrg() {
2591 checkForValidSection();
2593 const MCExpr *Offset;
2594 SMLoc Loc = getTok().getLoc();
2595 if (parseExpression(Offset))
2598 // Parse optional fill expression.
2599 int64_t FillExpr = 0;
2600 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2601 if (getLexer().isNot(AsmToken::Comma))
2602 return TokError("unexpected token in '.org' directive");
2605 if (parseAbsoluteExpression(FillExpr))
2608 if (getLexer().isNot(AsmToken::EndOfStatement))
2609 return TokError("unexpected token in '.org' directive");
2614 // Only limited forms of relocatable expressions are accepted here, it
2615 // has to be relative to the current section. The streamer will return
2616 // 'true' if the expression wasn't evaluatable.
2617 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2618 return Error(Loc, "expected assembly-time absolute expression");
2623 /// parseDirectiveAlign
2624 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2625 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2626 checkForValidSection();
2628 SMLoc AlignmentLoc = getLexer().getLoc();
2630 if (parseAbsoluteExpression(Alignment))
2634 bool HasFillExpr = false;
2635 int64_t FillExpr = 0;
2636 int64_t MaxBytesToFill = 0;
2637 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2638 if (getLexer().isNot(AsmToken::Comma))
2639 return TokError("unexpected token in directive");
2642 // The fill expression can be omitted while specifying a maximum number of
2643 // alignment bytes, e.g:
2645 if (getLexer().isNot(AsmToken::Comma)) {
2647 if (parseAbsoluteExpression(FillExpr))
2651 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2652 if (getLexer().isNot(AsmToken::Comma))
2653 return TokError("unexpected token in directive");
2656 MaxBytesLoc = getLexer().getLoc();
2657 if (parseAbsoluteExpression(MaxBytesToFill))
2660 if (getLexer().isNot(AsmToken::EndOfStatement))
2661 return TokError("unexpected token in directive");
2670 // Compute alignment in bytes.
2672 // FIXME: Diagnose overflow.
2673 if (Alignment >= 32) {
2674 Error(AlignmentLoc, "invalid alignment value");
2678 Alignment = 1ULL << Alignment;
2680 // Reject alignments that aren't a power of two, for gas compatibility.
2681 if (!isPowerOf2_64(Alignment))
2682 Error(AlignmentLoc, "alignment must be a power of 2");
2685 // Diagnose non-sensical max bytes to align.
2686 if (MaxBytesLoc.isValid()) {
2687 if (MaxBytesToFill < 1) {
2688 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2689 "many bytes, ignoring maximum bytes expression");
2693 if (MaxBytesToFill >= Alignment) {
2694 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2700 // Check whether we should use optimal code alignment for this .align
2702 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2703 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2704 ValueSize == 1 && UseCodeAlign) {
2705 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2707 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2708 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2715 /// parseDirectiveFile
2716 /// ::= .file [number] filename
2717 /// ::= .file number directory filename
2718 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2719 // FIXME: I'm not sure what this is.
2720 int64_t FileNumber = -1;
2721 SMLoc FileNumberLoc = getLexer().getLoc();
2722 if (getLexer().is(AsmToken::Integer)) {
2723 FileNumber = getTok().getIntVal();
2727 return TokError("file number less than one");
2730 if (getLexer().isNot(AsmToken::String))
2731 return TokError("unexpected token in '.file' directive");
2733 // Usually the directory and filename together, otherwise just the directory.
2734 // Allow the strings to have escaped octal character sequence.
2735 std::string Path = getTok().getString();
2736 if (parseEscapedString(Path))
2740 StringRef Directory;
2742 std::string FilenameData;
2743 if (getLexer().is(AsmToken::String)) {
2744 if (FileNumber == -1)
2745 return TokError("explicit path specified, but no file number");
2746 if (parseEscapedString(FilenameData))
2748 Filename = FilenameData;
2755 if (getLexer().isNot(AsmToken::EndOfStatement))
2756 return TokError("unexpected token in '.file' directive");
2758 if (FileNumber == -1)
2759 getStreamer().EmitFileDirective(Filename);
2761 if (getContext().getGenDwarfForAssembly() == true)
2763 "input can't have .file dwarf directives when -g is "
2764 "used to generate dwarf debug info for assembly code");
2766 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2767 Error(FileNumberLoc, "file number already allocated");
2773 /// parseDirectiveLine
2774 /// ::= .line [number]
2775 bool AsmParser::parseDirectiveLine() {
2776 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2777 if (getLexer().isNot(AsmToken::Integer))
2778 return TokError("unexpected token in '.line' directive");
2780 int64_t LineNumber = getTok().getIntVal();
2784 // FIXME: Do something with the .line.
2787 if (getLexer().isNot(AsmToken::EndOfStatement))
2788 return TokError("unexpected token in '.line' directive");
2793 /// parseDirectiveLoc
2794 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2795 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2796 /// The first number is a file number, must have been previously assigned with
2797 /// a .file directive, the second number is the line number and optionally the
2798 /// third number is a column position (zero if not specified). The remaining
2799 /// optional items are .loc sub-directives.
2800 bool AsmParser::parseDirectiveLoc() {
2801 if (getLexer().isNot(AsmToken::Integer))
2802 return TokError("unexpected token in '.loc' directive");
2803 int64_t FileNumber = getTok().getIntVal();
2805 return TokError("file number less than one in '.loc' directive");
2806 if (!getContext().isValidDwarfFileNumber(FileNumber))
2807 return TokError("unassigned file number in '.loc' directive");
2810 int64_t LineNumber = 0;
2811 if (getLexer().is(AsmToken::Integer)) {
2812 LineNumber = getTok().getIntVal();
2814 return TokError("line number less than zero in '.loc' directive");
2818 int64_t ColumnPos = 0;
2819 if (getLexer().is(AsmToken::Integer)) {
2820 ColumnPos = getTok().getIntVal();
2822 return TokError("column position less than zero in '.loc' directive");
2826 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2828 int64_t Discriminator = 0;
2829 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2831 if (getLexer().is(AsmToken::EndOfStatement))
2835 SMLoc Loc = getTok().getLoc();
2836 if (parseIdentifier(Name))
2837 return TokError("unexpected token in '.loc' directive");
2839 if (Name == "basic_block")
2840 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2841 else if (Name == "prologue_end")
2842 Flags |= DWARF2_FLAG_PROLOGUE_END;
2843 else if (Name == "epilogue_begin")
2844 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2845 else if (Name == "is_stmt") {
2846 Loc = getTok().getLoc();
2847 const MCExpr *Value;
2848 if (parseExpression(Value))
2850 // The expression must be the constant 0 or 1.
2851 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2852 int Value = MCE->getValue();
2854 Flags &= ~DWARF2_FLAG_IS_STMT;
2855 else if (Value == 1)
2856 Flags |= DWARF2_FLAG_IS_STMT;
2858 return Error(Loc, "is_stmt value not 0 or 1");
2860 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2862 } else if (Name == "isa") {
2863 Loc = getTok().getLoc();
2864 const MCExpr *Value;
2865 if (parseExpression(Value))
2867 // The expression must be a constant greater or equal to 0.
2868 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2869 int Value = MCE->getValue();
2871 return Error(Loc, "isa number less than zero");
2874 return Error(Loc, "isa number not a constant value");
2876 } else if (Name == "discriminator") {
2877 if (parseAbsoluteExpression(Discriminator))
2880 return Error(Loc, "unknown sub-directive in '.loc' directive");
2883 if (getLexer().is(AsmToken::EndOfStatement))
2888 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2889 Isa, Discriminator, StringRef());
2894 /// parseDirectiveStabs
2895 /// ::= .stabs string, number, number, number
2896 bool AsmParser::parseDirectiveStabs() {
2897 return TokError("unsupported directive '.stabs'");
2900 /// parseDirectiveCFISections
2901 /// ::= .cfi_sections section [, section]
2902 bool AsmParser::parseDirectiveCFISections() {
2907 if (parseIdentifier(Name))
2908 return TokError("Expected an identifier");
2910 if (Name == ".eh_frame")
2912 else if (Name == ".debug_frame")
2915 if (getLexer().is(AsmToken::Comma)) {
2918 if (parseIdentifier(Name))
2919 return TokError("Expected an identifier");
2921 if (Name == ".eh_frame")
2923 else if (Name == ".debug_frame")
2927 getStreamer().EmitCFISections(EH, Debug);
2931 /// parseDirectiveCFIStartProc
2932 /// ::= .cfi_startproc [simple]
2933 bool AsmParser::parseDirectiveCFIStartProc() {
2935 if (getLexer().isNot(AsmToken::EndOfStatement))
2936 if (parseIdentifier(Simple) || Simple != "simple")
2937 return TokError("unexpected token in .cfi_startproc directive");
2939 getStreamer().EmitCFIStartProc(!Simple.empty());
2943 /// parseDirectiveCFIEndProc
2944 /// ::= .cfi_endproc
2945 bool AsmParser::parseDirectiveCFIEndProc() {
2946 getStreamer().EmitCFIEndProc();
2950 /// \brief parse register name or number.
2951 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2952 SMLoc DirectiveLoc) {
2955 if (getLexer().isNot(AsmToken::Integer)) {
2956 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2958 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2960 return parseAbsoluteExpression(Register);
2965 /// parseDirectiveCFIDefCfa
2966 /// ::= .cfi_def_cfa register, offset
2967 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2968 int64_t Register = 0;
2969 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2972 if (getLexer().isNot(AsmToken::Comma))
2973 return TokError("unexpected token in directive");
2977 if (parseAbsoluteExpression(Offset))
2980 getStreamer().EmitCFIDefCfa(Register, Offset);
2984 /// parseDirectiveCFIDefCfaOffset
2985 /// ::= .cfi_def_cfa_offset offset
2986 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2988 if (parseAbsoluteExpression(Offset))
2991 getStreamer().EmitCFIDefCfaOffset(Offset);
2995 /// parseDirectiveCFIRegister
2996 /// ::= .cfi_register register, register
2997 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2998 int64_t Register1 = 0;
2999 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3002 if (getLexer().isNot(AsmToken::Comma))
3003 return TokError("unexpected token in directive");
3006 int64_t Register2 = 0;
3007 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3010 getStreamer().EmitCFIRegister(Register1, Register2);
3014 /// parseDirectiveCFIWindowSave
3015 /// ::= .cfi_window_save
3016 bool AsmParser::parseDirectiveCFIWindowSave() {
3017 getStreamer().EmitCFIWindowSave();
3021 /// parseDirectiveCFIAdjustCfaOffset
3022 /// ::= .cfi_adjust_cfa_offset adjustment
3023 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3024 int64_t Adjustment = 0;
3025 if (parseAbsoluteExpression(Adjustment))
3028 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3032 /// parseDirectiveCFIDefCfaRegister
3033 /// ::= .cfi_def_cfa_register register
3034 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3035 int64_t Register = 0;
3036 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3039 getStreamer().EmitCFIDefCfaRegister(Register);
3043 /// parseDirectiveCFIOffset
3044 /// ::= .cfi_offset register, offset
3045 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3046 int64_t Register = 0;
3049 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3052 if (getLexer().isNot(AsmToken::Comma))
3053 return TokError("unexpected token in directive");
3056 if (parseAbsoluteExpression(Offset))
3059 getStreamer().EmitCFIOffset(Register, Offset);
3063 /// parseDirectiveCFIRelOffset
3064 /// ::= .cfi_rel_offset register, offset
3065 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3066 int64_t Register = 0;
3068 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3071 if (getLexer().isNot(AsmToken::Comma))
3072 return TokError("unexpected token in directive");
3076 if (parseAbsoluteExpression(Offset))
3079 getStreamer().EmitCFIRelOffset(Register, Offset);
3083 static bool isValidEncoding(int64_t Encoding) {
3084 if (Encoding & ~0xff)
3087 if (Encoding == dwarf::DW_EH_PE_omit)
3090 const unsigned Format = Encoding & 0xf;
3091 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3092 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3093 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3094 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3097 const unsigned Application = Encoding & 0x70;
3098 if (Application != dwarf::DW_EH_PE_absptr &&
3099 Application != dwarf::DW_EH_PE_pcrel)
3105 /// parseDirectiveCFIPersonalityOrLsda
3106 /// IsPersonality true for cfi_personality, false for cfi_lsda
3107 /// ::= .cfi_personality encoding, [symbol_name]
3108 /// ::= .cfi_lsda encoding, [symbol_name]
3109 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3110 int64_t Encoding = 0;
3111 if (parseAbsoluteExpression(Encoding))
3113 if (Encoding == dwarf::DW_EH_PE_omit)
3116 if (!isValidEncoding(Encoding))
3117 return TokError("unsupported encoding.");
3119 if (getLexer().isNot(AsmToken::Comma))
3120 return TokError("unexpected token in directive");
3124 if (parseIdentifier(Name))
3125 return TokError("expected identifier in directive");
3127 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3130 getStreamer().EmitCFIPersonality(Sym, Encoding);
3132 getStreamer().EmitCFILsda(Sym, Encoding);
3136 /// parseDirectiveCFIRememberState
3137 /// ::= .cfi_remember_state
3138 bool AsmParser::parseDirectiveCFIRememberState() {
3139 getStreamer().EmitCFIRememberState();
3143 /// parseDirectiveCFIRestoreState
3144 /// ::= .cfi_remember_state
3145 bool AsmParser::parseDirectiveCFIRestoreState() {
3146 getStreamer().EmitCFIRestoreState();
3150 /// parseDirectiveCFISameValue
3151 /// ::= .cfi_same_value register
3152 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3153 int64_t Register = 0;
3155 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3158 getStreamer().EmitCFISameValue(Register);
3162 /// parseDirectiveCFIRestore
3163 /// ::= .cfi_restore register
3164 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3165 int64_t Register = 0;
3166 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3169 getStreamer().EmitCFIRestore(Register);
3173 /// parseDirectiveCFIEscape
3174 /// ::= .cfi_escape expression[,...]
3175 bool AsmParser::parseDirectiveCFIEscape() {
3178 if (parseAbsoluteExpression(CurrValue))
3181 Values.push_back((uint8_t)CurrValue);
3183 while (getLexer().is(AsmToken::Comma)) {
3186 if (parseAbsoluteExpression(CurrValue))
3189 Values.push_back((uint8_t)CurrValue);
3192 getStreamer().EmitCFIEscape(Values);
3196 /// parseDirectiveCFISignalFrame
3197 /// ::= .cfi_signal_frame
3198 bool AsmParser::parseDirectiveCFISignalFrame() {
3199 if (getLexer().isNot(AsmToken::EndOfStatement))
3200 return Error(getLexer().getLoc(),
3201 "unexpected token in '.cfi_signal_frame'");
3203 getStreamer().EmitCFISignalFrame();
3207 /// parseDirectiveCFIUndefined
3208 /// ::= .cfi_undefined register
3209 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3210 int64_t Register = 0;
3212 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3215 getStreamer().EmitCFIUndefined(Register);
3219 /// parseDirectiveMacrosOnOff
3222 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3223 if (getLexer().isNot(AsmToken::EndOfStatement))
3224 return Error(getLexer().getLoc(),
3225 "unexpected token in '" + Directive + "' directive");
3227 setMacrosEnabled(Directive == ".macros_on");
3231 /// parseDirectiveMacro
3232 /// ::= .macro name[,] [parameters]
3233 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3235 if (parseIdentifier(Name))
3236 return TokError("expected identifier in '.macro' directive");
3238 if (getLexer().is(AsmToken::Comma))
3241 MCAsmMacroParameters Parameters;
3242 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3243 MCAsmMacroParameter Parameter;
3244 if (parseIdentifier(Parameter.Name))
3245 return TokError("expected identifier in '.macro' directive");
3247 if (Lexer.is(AsmToken::Colon)) {
3248 Lex(); // consume ':'
3251 StringRef Qualifier;
3253 QualLoc = Lexer.getLoc();
3254 if (parseIdentifier(Qualifier))
3255 return Error(QualLoc, "missing parameter qualifier for "
3256 "'" + Parameter.Name + "' in macro '" + Name + "'");
3258 if (Qualifier == "req")
3259 Parameter.Required = true;
3261 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3262 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3265 if (getLexer().is(AsmToken::Equal)) {
3270 ParamLoc = Lexer.getLoc();
3271 if (parseMacroArgument(Parameter.Value))
3274 if (Parameter.Required)
3275 Warning(ParamLoc, "pointless default value for required parameter "
3276 "'" + Parameter.Name + "' in macro '" + Name + "'");
3279 Parameters.push_back(Parameter);
3281 if (getLexer().is(AsmToken::Comma))
3285 // Eat the end of statement.
3288 AsmToken EndToken, StartToken = getTok();
3289 unsigned MacroDepth = 0;
3291 // Lex the macro definition.
3293 // Check whether we have reached the end of the file.
3294 if (getLexer().is(AsmToken::Eof))
3295 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3297 // Otherwise, check whether we have reach the .endmacro.
3298 if (getLexer().is(AsmToken::Identifier)) {
3299 if (getTok().getIdentifier() == ".endm" ||
3300 getTok().getIdentifier() == ".endmacro") {
3301 if (MacroDepth == 0) { // Outermost macro.
3302 EndToken = getTok();
3304 if (getLexer().isNot(AsmToken::EndOfStatement))
3305 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3309 // Otherwise we just found the end of an inner macro.
3312 } else if (getTok().getIdentifier() == ".macro") {
3313 // We allow nested macros. Those aren't instantiated until the outermost
3314 // macro is expanded so just ignore them for now.
3319 // Otherwise, scan til the end of the statement.
3320 eatToEndOfStatement();
3323 if (lookupMacro(Name)) {
3324 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3327 const char *BodyStart = StartToken.getLoc().getPointer();
3328 const char *BodyEnd = EndToken.getLoc().getPointer();
3329 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3330 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3331 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3335 /// checkForBadMacro
3337 /// With the support added for named parameters there may be code out there that
3338 /// is transitioning from positional parameters. In versions of gas that did
3339 /// not support named parameters they would be ignored on the macro definition.
3340 /// But to support both styles of parameters this is not possible so if a macro
3341 /// definition has named parameters but does not use them and has what appears
3342 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3343 /// warning that the positional parameter found in body which have no effect.
3344 /// Hoping the developer will either remove the named parameters from the macro
3345 /// definition so the positional parameters get used if that was what was
3346 /// intended or change the macro to use the named parameters. It is possible
3347 /// this warning will trigger when the none of the named parameters are used
3348 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3349 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3351 ArrayRef<MCAsmMacroParameter> Parameters) {
3352 // If this macro is not defined with named parameters the warning we are
3353 // checking for here doesn't apply.
3354 unsigned NParameters = Parameters.size();
3355 if (NParameters == 0)
3358 bool NamedParametersFound = false;
3359 bool PositionalParametersFound = false;
3361 // Look at the body of the macro for use of both the named parameters and what
3362 // are likely to be positional parameters. This is what expandMacro() is
3363 // doing when it finds the parameters in the body.
3364 while (!Body.empty()) {
3365 // Scan for the next possible parameter.
3366 std::size_t End = Body.size(), Pos = 0;
3367 for (; Pos != End; ++Pos) {
3368 // Check for a substitution or escape.
3369 // This macro is defined with parameters, look for \foo, \bar, etc.
3370 if (Body[Pos] == '\\' && Pos + 1 != End)
3373 // This macro should have parameters, but look for $0, $1, ..., $n too.
3374 if (Body[Pos] != '$' || Pos + 1 == End)
3376 char Next = Body[Pos + 1];
3377 if (Next == '$' || Next == 'n' ||
3378 isdigit(static_cast<unsigned char>(Next)))
3382 // Check if we reached the end.
3386 if (Body[Pos] == '$') {
3387 switch (Body[Pos + 1]) {
3392 // $n => number of arguments
3394 PositionalParametersFound = true;
3397 // $[0-9] => argument
3399 PositionalParametersFound = true;
3405 unsigned I = Pos + 1;
3406 while (isIdentifierChar(Body[I]) && I + 1 != End)
3409 const char *Begin = Body.data() + Pos + 1;
3410 StringRef Argument(Begin, I - (Pos + 1));
3412 for (; Index < NParameters; ++Index)
3413 if (Parameters[Index].Name == Argument)
3416 if (Index == NParameters) {
3417 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3423 NamedParametersFound = true;
3424 Pos += 1 + Argument.size();
3427 // Update the scan point.
3428 Body = Body.substr(Pos);
3431 if (!NamedParametersFound && PositionalParametersFound)
3432 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3433 "used in macro body, possible positional parameter "
3434 "found in body which will have no effect");
3437 /// parseDirectiveEndMacro
3440 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3441 if (getLexer().isNot(AsmToken::EndOfStatement))
3442 return TokError("unexpected token in '" + Directive + "' directive");
3444 // If we are inside a macro instantiation, terminate the current
3446 if (isInsideMacroInstantiation()) {
3451 // Otherwise, this .endmacro is a stray entry in the file; well formed
3452 // .endmacro directives are handled during the macro definition parsing.
3453 return TokError("unexpected '" + Directive + "' in file, "
3454 "no current macro definition");
3457 /// parseDirectivePurgeMacro
3459 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3461 if (parseIdentifier(Name))
3462 return TokError("expected identifier in '.purgem' directive");
3464 if (getLexer().isNot(AsmToken::EndOfStatement))
3465 return TokError("unexpected token in '.purgem' directive");
3467 if (!lookupMacro(Name))
3468 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3470 undefineMacro(Name);
3474 /// parseDirectiveBundleAlignMode
3475 /// ::= {.bundle_align_mode} expression
3476 bool AsmParser::parseDirectiveBundleAlignMode() {
3477 checkForValidSection();
3479 // Expect a single argument: an expression that evaluates to a constant
3480 // in the inclusive range 0-30.
3481 SMLoc ExprLoc = getLexer().getLoc();
3482 int64_t AlignSizePow2;
3483 if (parseAbsoluteExpression(AlignSizePow2))
3485 else if (getLexer().isNot(AsmToken::EndOfStatement))
3486 return TokError("unexpected token after expression in"
3487 " '.bundle_align_mode' directive");
3488 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3489 return Error(ExprLoc,
3490 "invalid bundle alignment size (expected between 0 and 30)");
3494 // Because of AlignSizePow2's verified range we can safely truncate it to
3496 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3500 /// parseDirectiveBundleLock
3501 /// ::= {.bundle_lock} [align_to_end]
3502 bool AsmParser::parseDirectiveBundleLock() {
3503 checkForValidSection();
3504 bool AlignToEnd = false;
3506 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3508 SMLoc Loc = getTok().getLoc();
3509 const char *kInvalidOptionError =
3510 "invalid option for '.bundle_lock' directive";
3512 if (parseIdentifier(Option))
3513 return Error(Loc, kInvalidOptionError);
3515 if (Option != "align_to_end")
3516 return Error(Loc, kInvalidOptionError);
3517 else if (getLexer().isNot(AsmToken::EndOfStatement))
3519 "unexpected token after '.bundle_lock' directive option");
3525 getStreamer().EmitBundleLock(AlignToEnd);
3529 /// parseDirectiveBundleLock
3530 /// ::= {.bundle_lock}
3531 bool AsmParser::parseDirectiveBundleUnlock() {
3532 checkForValidSection();
3534 if (getLexer().isNot(AsmToken::EndOfStatement))
3535 return TokError("unexpected token in '.bundle_unlock' directive");
3538 getStreamer().EmitBundleUnlock();
3542 /// parseDirectiveSpace
3543 /// ::= (.skip | .space) expression [ , expression ]
3544 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3545 checkForValidSection();
3548 if (parseAbsoluteExpression(NumBytes))
3551 int64_t FillExpr = 0;
3552 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3553 if (getLexer().isNot(AsmToken::Comma))
3554 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3557 if (parseAbsoluteExpression(FillExpr))
3560 if (getLexer().isNot(AsmToken::EndOfStatement))
3561 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3567 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3570 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3571 getStreamer().EmitFill(NumBytes, FillExpr);
3576 /// parseDirectiveLEB128
3577 /// ::= (.sleb128 | .uleb128) expression
3578 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3579 checkForValidSection();
3580 const MCExpr *Value;
3582 if (parseExpression(Value))
3585 if (getLexer().isNot(AsmToken::EndOfStatement))
3586 return TokError("unexpected token in directive");
3589 getStreamer().EmitSLEB128Value(Value);
3591 getStreamer().EmitULEB128Value(Value);
3596 /// parseDirectiveSymbolAttribute
3597 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3598 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3599 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3602 SMLoc Loc = getTok().getLoc();
3604 if (parseIdentifier(Name))
3605 return Error(Loc, "expected identifier in directive");
3607 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3609 // Assembler local symbols don't make any sense here. Complain loudly.
3610 if (Sym->isTemporary())
3611 return Error(Loc, "non-local symbol required in directive");
3613 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3614 return Error(Loc, "unable to emit symbol attribute");
3616 if (getLexer().is(AsmToken::EndOfStatement))
3619 if (getLexer().isNot(AsmToken::Comma))
3620 return TokError("unexpected token in directive");
3629 /// parseDirectiveComm
3630 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3631 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3632 checkForValidSection();
3634 SMLoc IDLoc = getLexer().getLoc();
3636 if (parseIdentifier(Name))
3637 return TokError("expected identifier in directive");
3639 // Handle the identifier as the key symbol.
3640 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3642 if (getLexer().isNot(AsmToken::Comma))
3643 return TokError("unexpected token in directive");
3647 SMLoc SizeLoc = getLexer().getLoc();
3648 if (parseAbsoluteExpression(Size))
3651 int64_t Pow2Alignment = 0;
3652 SMLoc Pow2AlignmentLoc;
3653 if (getLexer().is(AsmToken::Comma)) {
3655 Pow2AlignmentLoc = getLexer().getLoc();
3656 if (parseAbsoluteExpression(Pow2Alignment))
3659 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3660 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3661 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3663 // If this target takes alignments in bytes (not log) validate and convert.
3664 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3665 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3666 if (!isPowerOf2_64(Pow2Alignment))
3667 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3668 Pow2Alignment = Log2_64(Pow2Alignment);
3672 if (getLexer().isNot(AsmToken::EndOfStatement))
3673 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3677 // NOTE: a size of zero for a .comm should create a undefined symbol
3678 // but a size of .lcomm creates a bss symbol of size zero.
3680 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3681 "be less than zero");
3683 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3684 // may internally end up wanting an alignment in bytes.
3685 // FIXME: Diagnose overflow.
3686 if (Pow2Alignment < 0)
3687 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3688 "alignment, can't be less than zero");
3690 if (!Sym->isUndefined())
3691 return Error(IDLoc, "invalid symbol redefinition");
3693 // Create the Symbol as a common or local common with Size and Pow2Alignment
3695 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3699 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3703 /// parseDirectiveAbort
3704 /// ::= .abort [... message ...]
3705 bool AsmParser::parseDirectiveAbort() {
3706 // FIXME: Use loc from directive.
3707 SMLoc Loc = getLexer().getLoc();
3709 StringRef Str = parseStringToEndOfStatement();
3710 if (getLexer().isNot(AsmToken::EndOfStatement))
3711 return TokError("unexpected token in '.abort' directive");
3716 Error(Loc, ".abort detected. Assembly stopping.");
3718 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3719 // FIXME: Actually abort assembly here.
3724 /// parseDirectiveInclude
3725 /// ::= .include "filename"
3726 bool AsmParser::parseDirectiveInclude() {
3727 if (getLexer().isNot(AsmToken::String))
3728 return TokError("expected string in '.include' directive");
3730 // Allow the strings to have escaped octal character sequence.
3731 std::string Filename;
3732 if (parseEscapedString(Filename))
3734 SMLoc IncludeLoc = getLexer().getLoc();
3737 if (getLexer().isNot(AsmToken::EndOfStatement))
3738 return TokError("unexpected token in '.include' directive");
3740 // Attempt to switch the lexer to the included file before consuming the end
3741 // of statement to avoid losing it when we switch.
3742 if (enterIncludeFile(Filename)) {
3743 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3750 /// parseDirectiveIncbin
3751 /// ::= .incbin "filename"
3752 bool AsmParser::parseDirectiveIncbin() {
3753 if (getLexer().isNot(AsmToken::String))
3754 return TokError("expected string in '.incbin' directive");
3756 // Allow the strings to have escaped octal character sequence.
3757 std::string Filename;
3758 if (parseEscapedString(Filename))
3760 SMLoc IncbinLoc = getLexer().getLoc();
3763 if (getLexer().isNot(AsmToken::EndOfStatement))
3764 return TokError("unexpected token in '.incbin' directive");
3766 // Attempt to process the included file.
3767 if (processIncbinFile(Filename)) {
3768 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3775 /// parseDirectiveIf
3776 /// ::= .if expression
3777 /// ::= .ifne expression
3778 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3779 TheCondStack.push_back(TheCondState);
3780 TheCondState.TheCond = AsmCond::IfCond;
3781 if (TheCondState.Ignore) {
3782 eatToEndOfStatement();
3785 if (parseAbsoluteExpression(ExprValue))
3788 if (getLexer().isNot(AsmToken::EndOfStatement))
3789 return TokError("unexpected token in '.if' directive");
3793 TheCondState.CondMet = ExprValue;
3794 TheCondState.Ignore = !TheCondState.CondMet;
3800 /// parseDirectiveIfb
3802 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3803 TheCondStack.push_back(TheCondState);
3804 TheCondState.TheCond = AsmCond::IfCond;
3806 if (TheCondState.Ignore) {
3807 eatToEndOfStatement();
3809 StringRef Str = parseStringToEndOfStatement();
3811 if (getLexer().isNot(AsmToken::EndOfStatement))
3812 return TokError("unexpected token in '.ifb' directive");
3816 TheCondState.CondMet = ExpectBlank == Str.empty();
3817 TheCondState.Ignore = !TheCondState.CondMet;
3823 /// parseDirectiveIfc
3824 /// ::= .ifc string1, string2
3825 /// ::= .ifnc string1, string2
3826 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3827 TheCondStack.push_back(TheCondState);
3828 TheCondState.TheCond = AsmCond::IfCond;
3830 if (TheCondState.Ignore) {
3831 eatToEndOfStatement();
3833 StringRef Str1 = parseStringToComma();
3835 if (getLexer().isNot(AsmToken::Comma))
3836 return TokError("unexpected token in '.ifc' directive");
3840 StringRef Str2 = parseStringToEndOfStatement();
3842 if (getLexer().isNot(AsmToken::EndOfStatement))
3843 return TokError("unexpected token in '.ifc' directive");
3847 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3848 TheCondState.Ignore = !TheCondState.CondMet;
3854 /// parseDirectiveIfeqs
3855 /// ::= .ifeqs string1, string2
3856 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3857 if (Lexer.isNot(AsmToken::String)) {
3858 TokError("expected string parameter for '.ifeqs' directive");
3859 eatToEndOfStatement();
3863 StringRef String1 = getTok().getStringContents();
3866 if (Lexer.isNot(AsmToken::Comma)) {
3867 TokError("expected comma after first string for '.ifeqs' directive");
3868 eatToEndOfStatement();
3874 if (Lexer.isNot(AsmToken::String)) {
3875 TokError("expected string parameter for '.ifeqs' directive");
3876 eatToEndOfStatement();
3880 StringRef String2 = getTok().getStringContents();
3883 TheCondStack.push_back(TheCondState);
3884 TheCondState.TheCond = AsmCond::IfCond;
3885 TheCondState.CondMet = String1 == String2;
3886 TheCondState.Ignore = !TheCondState.CondMet;
3891 /// parseDirectiveIfdef
3892 /// ::= .ifdef symbol
3893 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3895 TheCondStack.push_back(TheCondState);
3896 TheCondState.TheCond = AsmCond::IfCond;
3898 if (TheCondState.Ignore) {
3899 eatToEndOfStatement();
3901 if (parseIdentifier(Name))
3902 return TokError("expected identifier after '.ifdef'");
3906 MCSymbol *Sym = getContext().LookupSymbol(Name);
3909 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3911 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3912 TheCondState.Ignore = !TheCondState.CondMet;
3918 /// parseDirectiveElseIf
3919 /// ::= .elseif expression
3920 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3921 if (TheCondState.TheCond != AsmCond::IfCond &&
3922 TheCondState.TheCond != AsmCond::ElseIfCond)
3923 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3925 TheCondState.TheCond = AsmCond::ElseIfCond;
3927 bool LastIgnoreState = false;
3928 if (!TheCondStack.empty())
3929 LastIgnoreState = TheCondStack.back().Ignore;
3930 if (LastIgnoreState || TheCondState.CondMet) {
3931 TheCondState.Ignore = true;
3932 eatToEndOfStatement();
3935 if (parseAbsoluteExpression(ExprValue))
3938 if (getLexer().isNot(AsmToken::EndOfStatement))
3939 return TokError("unexpected token in '.elseif' directive");
3942 TheCondState.CondMet = ExprValue;
3943 TheCondState.Ignore = !TheCondState.CondMet;
3949 /// parseDirectiveElse
3951 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3952 if (getLexer().isNot(AsmToken::EndOfStatement))
3953 return TokError("unexpected token in '.else' directive");
3957 if (TheCondState.TheCond != AsmCond::IfCond &&
3958 TheCondState.TheCond != AsmCond::ElseIfCond)
3959 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3961 TheCondState.TheCond = AsmCond::ElseCond;
3962 bool LastIgnoreState = false;
3963 if (!TheCondStack.empty())
3964 LastIgnoreState = TheCondStack.back().Ignore;
3965 if (LastIgnoreState || TheCondState.CondMet)
3966 TheCondState.Ignore = true;
3968 TheCondState.Ignore = false;
3973 /// parseDirectiveEnd
3975 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3976 if (getLexer().isNot(AsmToken::EndOfStatement))
3977 return TokError("unexpected token in '.end' directive");
3981 while (Lexer.isNot(AsmToken::Eof))
3987 /// parseDirectiveError
3989 /// ::= .error [string]
3990 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
3991 if (!TheCondStack.empty()) {
3992 if (TheCondStack.back().Ignore) {
3993 eatToEndOfStatement();
3999 return Error(L, ".err encountered");
4001 StringRef Message = ".error directive invoked in source file";
4002 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4003 if (Lexer.isNot(AsmToken::String)) {
4004 TokError(".error argument must be a string");
4005 eatToEndOfStatement();
4009 Message = getTok().getStringContents();
4017 /// parseDirectiveEndIf
4019 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4020 if (getLexer().isNot(AsmToken::EndOfStatement))
4021 return TokError("unexpected token in '.endif' directive");
4025 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4026 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4028 if (!TheCondStack.empty()) {
4029 TheCondState = TheCondStack.back();
4030 TheCondStack.pop_back();
4036 void AsmParser::initializeDirectiveKindMap() {
4037 DirectiveKindMap[".set"] = DK_SET;
4038 DirectiveKindMap[".equ"] = DK_EQU;
4039 DirectiveKindMap[".equiv"] = DK_EQUIV;
4040 DirectiveKindMap[".ascii"] = DK_ASCII;
4041 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4042 DirectiveKindMap[".string"] = DK_STRING;
4043 DirectiveKindMap[".byte"] = DK_BYTE;
4044 DirectiveKindMap[".short"] = DK_SHORT;
4045 DirectiveKindMap[".value"] = DK_VALUE;
4046 DirectiveKindMap[".2byte"] = DK_2BYTE;
4047 DirectiveKindMap[".long"] = DK_LONG;
4048 DirectiveKindMap[".int"] = DK_INT;
4049 DirectiveKindMap[".4byte"] = DK_4BYTE;
4050 DirectiveKindMap[".quad"] = DK_QUAD;
4051 DirectiveKindMap[".8byte"] = DK_8BYTE;
4052 DirectiveKindMap[".octa"] = DK_OCTA;
4053 DirectiveKindMap[".single"] = DK_SINGLE;
4054 DirectiveKindMap[".float"] = DK_FLOAT;
4055 DirectiveKindMap[".double"] = DK_DOUBLE;
4056 DirectiveKindMap[".align"] = DK_ALIGN;
4057 DirectiveKindMap[".align32"] = DK_ALIGN32;
4058 DirectiveKindMap[".balign"] = DK_BALIGN;
4059 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4060 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4061 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4062 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4063 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4064 DirectiveKindMap[".org"] = DK_ORG;
4065 DirectiveKindMap[".fill"] = DK_FILL;
4066 DirectiveKindMap[".zero"] = DK_ZERO;
4067 DirectiveKindMap[".extern"] = DK_EXTERN;
4068 DirectiveKindMap[".globl"] = DK_GLOBL;
4069 DirectiveKindMap[".global"] = DK_GLOBAL;
4070 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4071 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4072 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4073 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4074 DirectiveKindMap[".reference"] = DK_REFERENCE;
4075 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4076 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4077 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4078 DirectiveKindMap[".comm"] = DK_COMM;
4079 DirectiveKindMap[".common"] = DK_COMMON;
4080 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4081 DirectiveKindMap[".abort"] = DK_ABORT;
4082 DirectiveKindMap[".include"] = DK_INCLUDE;
4083 DirectiveKindMap[".incbin"] = DK_INCBIN;
4084 DirectiveKindMap[".code16"] = DK_CODE16;
4085 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4086 DirectiveKindMap[".rept"] = DK_REPT;
4087 DirectiveKindMap[".rep"] = DK_REPT;
4088 DirectiveKindMap[".irp"] = DK_IRP;
4089 DirectiveKindMap[".irpc"] = DK_IRPC;
4090 DirectiveKindMap[".endr"] = DK_ENDR;
4091 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4092 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4093 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4094 DirectiveKindMap[".if"] = DK_IF;
4095 DirectiveKindMap[".ifne"] = DK_IFNE;
4096 DirectiveKindMap[".ifb"] = DK_IFB;
4097 DirectiveKindMap[".ifnb"] = DK_IFNB;
4098 DirectiveKindMap[".ifc"] = DK_IFC;
4099 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4100 DirectiveKindMap[".ifnc"] = DK_IFNC;
4101 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4102 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4103 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4104 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4105 DirectiveKindMap[".else"] = DK_ELSE;
4106 DirectiveKindMap[".end"] = DK_END;
4107 DirectiveKindMap[".endif"] = DK_ENDIF;
4108 DirectiveKindMap[".skip"] = DK_SKIP;
4109 DirectiveKindMap[".space"] = DK_SPACE;
4110 DirectiveKindMap[".file"] = DK_FILE;
4111 DirectiveKindMap[".line"] = DK_LINE;
4112 DirectiveKindMap[".loc"] = DK_LOC;
4113 DirectiveKindMap[".stabs"] = DK_STABS;
4114 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4115 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4116 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4117 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4118 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4119 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4120 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4121 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4122 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4123 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4124 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4125 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4126 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4127 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4128 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4129 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4130 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4131 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4132 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4133 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4134 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4135 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4136 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4137 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4138 DirectiveKindMap[".macro"] = DK_MACRO;
4139 DirectiveKindMap[".endm"] = DK_ENDM;
4140 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4141 DirectiveKindMap[".purgem"] = DK_PURGEM;
4142 DirectiveKindMap[".err"] = DK_ERR;
4143 DirectiveKindMap[".error"] = DK_ERROR;
4146 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4147 AsmToken EndToken, StartToken = getTok();
4149 unsigned NestLevel = 0;
4151 // Check whether we have reached the end of the file.
4152 if (getLexer().is(AsmToken::Eof)) {
4153 Error(DirectiveLoc, "no matching '.endr' in definition");
4157 if (Lexer.is(AsmToken::Identifier) &&
4158 (getTok().getIdentifier() == ".rept")) {
4162 // Otherwise, check whether we have reached the .endr.
4163 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4164 if (NestLevel == 0) {
4165 EndToken = getTok();
4167 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4168 TokError("unexpected token in '.endr' directive");
4176 // Otherwise, scan till the end of the statement.
4177 eatToEndOfStatement();
4180 const char *BodyStart = StartToken.getLoc().getPointer();
4181 const char *BodyEnd = EndToken.getLoc().getPointer();
4182 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4184 // We Are Anonymous.
4185 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4186 return &MacroLikeBodies.back();
4189 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4190 raw_svector_ostream &OS) {
4193 MemoryBuffer *Instantiation =
4194 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4196 // Create the macro instantiation object and add to the current macro
4197 // instantiation stack.
4198 MacroInstantiation *MI = new MacroInstantiation(
4199 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4200 ActiveMacros.push_back(MI);
4202 // Jump to the macro instantiation and prime the lexer.
4203 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4204 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4208 /// parseDirectiveRept
4209 /// ::= .rep | .rept count
4210 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4211 const MCExpr *CountExpr;
4212 SMLoc CountLoc = getTok().getLoc();
4213 if (parseExpression(CountExpr))
4217 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4218 eatToEndOfStatement();
4219 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4223 return Error(CountLoc, "Count is negative");
4225 if (Lexer.isNot(AsmToken::EndOfStatement))
4226 return TokError("unexpected token in '" + Dir + "' directive");
4228 // Eat the end of statement.
4231 // Lex the rept definition.
4232 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4236 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4237 // to hold the macro body with substitutions.
4238 SmallString<256> Buf;
4239 raw_svector_ostream OS(Buf);
4241 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4244 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4249 /// parseDirectiveIrp
4250 /// ::= .irp symbol,values
4251 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4252 MCAsmMacroParameter Parameter;
4254 if (parseIdentifier(Parameter.Name))
4255 return TokError("expected identifier in '.irp' directive");
4257 if (Lexer.isNot(AsmToken::Comma))
4258 return TokError("expected comma in '.irp' directive");
4262 MCAsmMacroArguments A;
4263 if (parseMacroArguments(0, A))
4266 // Eat the end of statement.
4269 // Lex the irp definition.
4270 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4274 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4275 // to hold the macro body with substitutions.
4276 SmallString<256> Buf;
4277 raw_svector_ostream OS(Buf);
4279 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4280 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4284 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4289 /// parseDirectiveIrpc
4290 /// ::= .irpc symbol,values
4291 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4292 MCAsmMacroParameter Parameter;
4294 if (parseIdentifier(Parameter.Name))
4295 return TokError("expected identifier in '.irpc' directive");
4297 if (Lexer.isNot(AsmToken::Comma))
4298 return TokError("expected comma in '.irpc' directive");
4302 MCAsmMacroArguments A;
4303 if (parseMacroArguments(0, A))
4306 if (A.size() != 1 || A.front().size() != 1)
4307 return TokError("unexpected token in '.irpc' directive");
4309 // Eat the end of statement.
4312 // Lex the irpc definition.
4313 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4317 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4318 // to hold the macro body with substitutions.
4319 SmallString<256> Buf;
4320 raw_svector_ostream OS(Buf);
4322 StringRef Values = A.front().front().getString();
4323 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4324 MCAsmMacroArgument Arg;
4325 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4327 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4331 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4336 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4337 if (ActiveMacros.empty())
4338 return TokError("unmatched '.endr' directive");
4340 // The only .repl that should get here are the ones created by
4341 // instantiateMacroLikeBody.
4342 assert(getLexer().is(AsmToken::EndOfStatement));
4348 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4350 const MCExpr *Value;
4351 SMLoc ExprLoc = getLexer().getLoc();
4352 if (parseExpression(Value))
4354 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4356 return Error(ExprLoc, "unexpected expression in _emit");
4357 uint64_t IntValue = MCE->getValue();
4358 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4359 return Error(ExprLoc, "literal value out of range for directive");
4361 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4365 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4366 const MCExpr *Value;
4367 SMLoc ExprLoc = getLexer().getLoc();
4368 if (parseExpression(Value))
4370 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4372 return Error(ExprLoc, "unexpected expression in align");
4373 uint64_t IntValue = MCE->getValue();
4374 if (!isPowerOf2_64(IntValue))
4375 return Error(ExprLoc, "literal value not a power of two greater then zero");
4377 Info.AsmRewrites->push_back(
4378 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4382 // We are comparing pointers, but the pointers are relative to a single string.
4383 // Thus, this should always be deterministic.
4384 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4385 const AsmRewrite *AsmRewriteB) {
4386 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4388 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4391 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4392 // rewrite to the same location. Make sure the SizeDirective rewrite is
4393 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4394 // ensures the sort algorithm is stable.
4395 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4396 AsmRewritePrecedence[AsmRewriteB->Kind])
4399 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4400 AsmRewritePrecedence[AsmRewriteB->Kind])
4402 llvm_unreachable("Unstable rewrite sort.");
4405 bool AsmParser::parseMSInlineAsm(
4406 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4407 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4408 SmallVectorImpl<std::string> &Constraints,
4409 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4410 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4411 SmallVector<void *, 4> InputDecls;
4412 SmallVector<void *, 4> OutputDecls;
4413 SmallVector<bool, 4> InputDeclsAddressOf;
4414 SmallVector<bool, 4> OutputDeclsAddressOf;
4415 SmallVector<std::string, 4> InputConstraints;
4416 SmallVector<std::string, 4> OutputConstraints;
4417 SmallVector<unsigned, 4> ClobberRegs;
4419 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4424 // While we have input, parse each statement.
4425 unsigned InputIdx = 0;
4426 unsigned OutputIdx = 0;
4427 while (getLexer().isNot(AsmToken::Eof)) {
4428 ParseStatementInfo Info(&AsmStrRewrites);
4429 if (parseStatement(Info))
4432 if (Info.ParseError)
4435 if (Info.Opcode == ~0U)
4438 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4440 // Build the list of clobbers, outputs and inputs.
4441 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4442 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4445 if (Operand->isImm())
4448 // Register operand.
4449 if (Operand->isReg() && !Operand->needAddressOf()) {
4450 unsigned NumDefs = Desc.getNumDefs();
4452 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4453 ClobberRegs.push_back(Operand->getReg());
4457 // Expr/Input or Output.
4458 StringRef SymName = Operand->getSymName();
4459 if (SymName.empty())
4462 void *OpDecl = Operand->getOpDecl();
4466 bool isOutput = (i == 1) && Desc.mayStore();
4467 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4470 OutputDecls.push_back(OpDecl);
4471 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4472 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4473 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4475 InputDecls.push_back(OpDecl);
4476 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4477 InputConstraints.push_back(Operand->getConstraint().str());
4478 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4482 // Consider implicit defs to be clobbers. Think of cpuid and push.
4483 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4484 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4485 ClobberRegs.push_back(ImpDefs[I]);
4488 // Set the number of Outputs and Inputs.
4489 NumOutputs = OutputDecls.size();
4490 NumInputs = InputDecls.size();
4492 // Set the unique clobbers.
4493 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4494 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4496 Clobbers.assign(ClobberRegs.size(), std::string());
4497 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4498 raw_string_ostream OS(Clobbers[I]);
4499 IP->printRegName(OS, ClobberRegs[I]);
4502 // Merge the various outputs and inputs. Output are expected first.
4503 if (NumOutputs || NumInputs) {
4504 unsigned NumExprs = NumOutputs + NumInputs;
4505 OpDecls.resize(NumExprs);
4506 Constraints.resize(NumExprs);
4507 for (unsigned i = 0; i < NumOutputs; ++i) {
4508 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4509 Constraints[i] = OutputConstraints[i];
4511 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4512 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4513 Constraints[j] = InputConstraints[i];
4517 // Build the IR assembly string.
4518 std::string AsmStringIR;
4519 raw_string_ostream OS(AsmStringIR);
4520 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4521 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4522 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4523 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4524 E = AsmStrRewrites.end();
4526 AsmRewriteKind Kind = (*I).Kind;
4527 if (Kind == AOK_Delete)
4530 const char *Loc = (*I).Loc.getPointer();
4531 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4533 // Emit everything up to the immediate/expression.
4534 unsigned Len = Loc - AsmStart;
4536 OS << StringRef(AsmStart, Len);
4538 // Skip the original expression.
4539 if (Kind == AOK_Skip) {
4540 AsmStart = Loc + (*I).Len;
4544 unsigned AdditionalSkip = 0;
4545 // Rewrite expressions in $N notation.
4550 OS << "$$" << (*I).Val;
4556 OS << '$' << InputIdx++;
4559 OS << '$' << OutputIdx++;
4561 case AOK_SizeDirective:
4564 case 8: OS << "byte ptr "; break;
4565 case 16: OS << "word ptr "; break;
4566 case 32: OS << "dword ptr "; break;
4567 case 64: OS << "qword ptr "; break;
4568 case 80: OS << "xword ptr "; break;
4569 case 128: OS << "xmmword ptr "; break;
4570 case 256: OS << "ymmword ptr "; break;
4577 unsigned Val = (*I).Val;
4578 OS << ".align " << Val;
4580 // Skip the original immediate.
4581 assert(Val < 10 && "Expected alignment less then 2^10.");
4582 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4585 case AOK_DotOperator:
4590 // Skip the original expression.
4591 AsmStart = Loc + (*I).Len + AdditionalSkip;
4594 // Emit the remainder of the asm string.
4595 if (AsmStart != AsmEnd)
4596 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4598 AsmString = OS.str();
4602 /// \brief Create an MCAsmParser instance.
4603 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4604 MCStreamer &Out, const MCAsmInfo &MAI) {
4605 return new AsmParser(SM, C, Out, MAI);