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 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
195 void addDirectiveHandler(StringRef Directive,
196 ExtensionDirectiveHandler Handler) override {
197 ExtensionDirectiveMap[Directive] = Handler;
201 /// @name MCAsmParser Interface
204 SourceMgr &getSourceManager() override { return SrcMgr; }
205 MCAsmLexer &getLexer() override { return Lexer; }
206 MCContext &getContext() override { return Ctx; }
207 MCStreamer &getStreamer() override { return Out; }
208 unsigned getAssemblerDialect() override {
209 if (AssemblerDialect == ~0U)
210 return MAI.getAssemblerDialect();
212 return AssemblerDialect;
214 void setAssemblerDialect(unsigned i) override {
215 AssemblerDialect = i;
218 void Note(SMLoc L, const Twine &Msg,
219 ArrayRef<SMRange> Ranges = None) override;
220 bool Warning(SMLoc L, const Twine &Msg,
221 ArrayRef<SMRange> Ranges = None) override;
222 bool Error(SMLoc L, const Twine &Msg,
223 ArrayRef<SMRange> Ranges = None) override;
225 const AsmToken &Lex() override;
227 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
228 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
230 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
231 unsigned &NumOutputs, unsigned &NumInputs,
232 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
233 SmallVectorImpl<std::string> &Constraints,
234 SmallVectorImpl<std::string> &Clobbers,
235 const MCInstrInfo *MII, const MCInstPrinter *IP,
236 MCAsmParserSemaCallback &SI) override;
238 bool parseExpression(const MCExpr *&Res);
239 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
240 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
241 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
242 bool parseAbsoluteExpression(int64_t &Res) override;
244 /// \brief Parse an identifier or string (as a quoted identifier)
245 /// and set \p Res to the identifier contents.
246 bool parseIdentifier(StringRef &Res) override;
247 void eatToEndOfStatement() override;
249 void checkForValidSection() override;
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 StringRef parseStringToEndOfStatement() override;
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 bool parseEscapedString(std::string &Data) override;
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 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
644 0, StringRef(), getContext().getMainFileName()));
647 // While we have input, parse each statement.
648 while (Lexer.isNot(AsmToken::Eof)) {
649 ParseStatementInfo Info;
650 if (!parseStatement(Info))
653 // We had an error, validate that one was emitted and recover by skipping to
655 assert(HadError && "Parse statement returned an error, but none emitted!");
656 eatToEndOfStatement();
659 if (TheCondState.TheCond != StartingCondState.TheCond ||
660 TheCondState.Ignore != StartingCondState.Ignore)
661 return TokError("unmatched .ifs or .elses");
663 // Check to see there are no empty DwarfFile slots.
664 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
665 getContext().getMCDwarfFiles();
666 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
667 if (MCDwarfFiles[i].Name.empty())
668 TokError("unassigned file number: " + Twine(i) + " for .file directives");
671 // Check to see that all assembler local symbols were actually defined.
672 // Targets that don't do subsections via symbols may not want this, though,
673 // so conservatively exclude them. Only do this if we're finalizing, though,
674 // as otherwise we won't necessarilly have seen everything yet.
675 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
676 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
677 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
680 MCSymbol *Sym = i->getValue();
681 // Variable symbols may not be marked as defined, so check those
682 // explicitly. If we know it's a variable, we have a definition for
683 // the purposes of this check.
684 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
685 // FIXME: We would really like to refer back to where the symbol was
686 // first referenced for a source location. We need to add something
687 // to track that. Currently, we just point to the end of the file.
689 getLexer().getLoc(), SourceMgr::DK_Error,
690 "assembler local symbol '" + Sym->getName() + "' not defined");
694 // Finalize the output stream if there are no errors and if the client wants
696 if (!HadError && !NoFinalize)
702 void AsmParser::checkForValidSection() {
703 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
704 TokError("expected section directive before assembly directive");
709 /// \brief Throw away the rest of the line for testing purposes.
710 void AsmParser::eatToEndOfStatement() {
711 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
715 if (Lexer.is(AsmToken::EndOfStatement))
719 StringRef AsmParser::parseStringToEndOfStatement() {
720 const char *Start = getTok().getLoc().getPointer();
722 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
725 const char *End = getTok().getLoc().getPointer();
726 return StringRef(Start, End - Start);
729 StringRef AsmParser::parseStringToComma() {
730 const char *Start = getTok().getLoc().getPointer();
732 while (Lexer.isNot(AsmToken::EndOfStatement) &&
733 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
736 const char *End = getTok().getLoc().getPointer();
737 return StringRef(Start, End - Start);
740 /// \brief Parse a paren expression and return it.
741 /// NOTE: This assumes the leading '(' has already been consumed.
743 /// parenexpr ::= expr)
745 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
746 if (parseExpression(Res))
748 if (Lexer.isNot(AsmToken::RParen))
749 return TokError("expected ')' in parentheses expression");
750 EndLoc = Lexer.getTok().getEndLoc();
755 /// \brief Parse a bracket expression and return it.
756 /// NOTE: This assumes the leading '[' has already been consumed.
758 /// bracketexpr ::= expr]
760 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
761 if (parseExpression(Res))
763 if (Lexer.isNot(AsmToken::RBrac))
764 return TokError("expected ']' in brackets expression");
765 EndLoc = Lexer.getTok().getEndLoc();
770 /// \brief Parse a primary expression and return it.
771 /// primaryexpr ::= (parenexpr
772 /// primaryexpr ::= symbol
773 /// primaryexpr ::= number
774 /// primaryexpr ::= '.'
775 /// primaryexpr ::= ~,+,- primaryexpr
776 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
777 SMLoc FirstTokenLoc = getLexer().getLoc();
778 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
779 switch (FirstTokenKind) {
781 return TokError("unknown token in expression");
782 // If we have an error assume that we've already handled it.
783 case AsmToken::Error:
785 case AsmToken::Exclaim:
786 Lex(); // Eat the operator.
787 if (parsePrimaryExpr(Res, EndLoc))
789 Res = MCUnaryExpr::CreateLNot(Res, getContext());
791 case AsmToken::Dollar:
793 case AsmToken::String:
794 case AsmToken::Identifier: {
795 StringRef Identifier;
796 if (parseIdentifier(Identifier)) {
797 if (FirstTokenKind == AsmToken::Dollar) {
798 if (Lexer.getMAI().getDollarIsPC()) {
799 // This is a '$' reference, which references the current PC. Emit a
800 // temporary label to the streamer and refer to it.
801 MCSymbol *Sym = Ctx.CreateTempSymbol();
803 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
805 EndLoc = FirstTokenLoc;
808 return Error(FirstTokenLoc, "invalid token in expression");
811 // Parse symbol variant
812 std::pair<StringRef, StringRef> Split;
813 if (!MAI.useParensForSymbolVariant()) {
814 Split = Identifier.split('@');
815 } else if (Lexer.is(AsmToken::LParen)) {
816 Lexer.Lex(); // eat (
818 parseIdentifier(VName);
819 if (Lexer.isNot(AsmToken::RParen)) {
820 return Error(Lexer.getTok().getLoc(),
821 "unexpected token in variant, expected ')'");
823 Lexer.Lex(); // eat )
824 Split = std::make_pair(Identifier, VName);
827 EndLoc = SMLoc::getFromPointer(Identifier.end());
829 // This is a symbol reference.
830 StringRef SymbolName = Identifier;
831 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
833 // Lookup the symbol variant if used.
834 if (Split.second.size()) {
835 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
836 if (Variant != MCSymbolRefExpr::VK_Invalid) {
837 SymbolName = Split.first;
838 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
839 Variant = MCSymbolRefExpr::VK_None;
841 return Error(SMLoc::getFromPointer(Split.second.begin()),
842 "invalid variant '" + Split.second + "'");
846 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
848 // If this is an absolute variable reference, substitute it now to preserve
849 // semantics in the face of reassignment.
850 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
852 return Error(EndLoc, "unexpected modifier on variable reference");
854 Res = Sym->getVariableValue();
858 // Otherwise create a symbol ref.
859 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
862 case AsmToken::BigNum:
863 return TokError("literal value out of range for directive");
864 case AsmToken::Integer: {
865 SMLoc Loc = getTok().getLoc();
866 int64_t IntVal = getTok().getIntVal();
867 Res = MCConstantExpr::Create(IntVal, getContext());
868 EndLoc = Lexer.getTok().getEndLoc();
870 // Look for 'b' or 'f' following an Integer as a directional label
871 if (Lexer.getKind() == AsmToken::Identifier) {
872 StringRef IDVal = getTok().getString();
873 // Lookup the symbol variant if used.
874 std::pair<StringRef, StringRef> Split = IDVal.split('@');
875 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
876 if (Split.first.size() != IDVal.size()) {
877 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
878 if (Variant == MCSymbolRefExpr::VK_Invalid) {
879 Variant = MCSymbolRefExpr::VK_None;
880 return TokError("invalid variant '" + Split.second + "'");
884 if (IDVal == "f" || IDVal == "b") {
886 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
887 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
888 if (IDVal == "b" && Sym->isUndefined())
889 return Error(Loc, "invalid reference to undefined symbol");
890 EndLoc = Lexer.getTok().getEndLoc();
891 Lex(); // Eat identifier.
896 case AsmToken::Real: {
897 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
898 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
899 Res = MCConstantExpr::Create(IntVal, getContext());
900 EndLoc = Lexer.getTok().getEndLoc();
904 case AsmToken::Dot: {
905 // This is a '.' reference, which references the current PC. Emit a
906 // temporary label to the streamer and refer to it.
907 MCSymbol *Sym = Ctx.CreateTempSymbol();
909 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
910 EndLoc = Lexer.getTok().getEndLoc();
911 Lex(); // Eat identifier.
914 case AsmToken::LParen:
915 Lex(); // Eat the '('.
916 return parseParenExpr(Res, EndLoc);
917 case AsmToken::LBrac:
918 if (!PlatformParser->HasBracketExpressions())
919 return TokError("brackets expression not supported on this target");
920 Lex(); // Eat the '['.
921 return parseBracketExpr(Res, EndLoc);
922 case AsmToken::Minus:
923 Lex(); // Eat the operator.
924 if (parsePrimaryExpr(Res, EndLoc))
926 Res = MCUnaryExpr::CreateMinus(Res, getContext());
929 Lex(); // Eat the operator.
930 if (parsePrimaryExpr(Res, EndLoc))
932 Res = MCUnaryExpr::CreatePlus(Res, getContext());
934 case AsmToken::Tilde:
935 Lex(); // Eat the operator.
936 if (parsePrimaryExpr(Res, EndLoc))
938 Res = MCUnaryExpr::CreateNot(Res, getContext());
943 bool AsmParser::parseExpression(const MCExpr *&Res) {
945 return parseExpression(Res, EndLoc);
949 AsmParser::applyModifierToExpr(const MCExpr *E,
950 MCSymbolRefExpr::VariantKind Variant) {
951 // Ask the target implementation about this expression first.
952 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
955 // Recurse over the given expression, rebuilding it to apply the given variant
956 // if there is exactly one symbol.
957 switch (E->getKind()) {
959 case MCExpr::Constant:
962 case MCExpr::SymbolRef: {
963 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
965 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
966 TokError("invalid variant on expression '" + getTok().getIdentifier() +
967 "' (already modified)");
971 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
974 case MCExpr::Unary: {
975 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
976 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
979 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
982 case MCExpr::Binary: {
983 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
984 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
985 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
995 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
999 llvm_unreachable("Invalid expression kind!");
1002 /// \brief Parse an expression and return it.
1004 /// expr ::= expr &&,|| expr -> lowest.
1005 /// expr ::= expr |,^,&,! expr
1006 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1007 /// expr ::= expr <<,>> expr
1008 /// expr ::= expr +,- expr
1009 /// expr ::= expr *,/,% expr -> highest.
1010 /// expr ::= primaryexpr
1012 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1013 // Parse the expression.
1015 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1018 // As a special case, we support 'a op b @ modifier' by rewriting the
1019 // expression to include the modifier. This is inefficient, but in general we
1020 // expect users to use 'a@modifier op b'.
1021 if (Lexer.getKind() == AsmToken::At) {
1024 if (Lexer.isNot(AsmToken::Identifier))
1025 return TokError("unexpected symbol modifier following '@'");
1027 MCSymbolRefExpr::VariantKind Variant =
1028 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1029 if (Variant == MCSymbolRefExpr::VK_Invalid)
1030 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1032 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1034 return TokError("invalid modifier '" + getTok().getIdentifier() +
1035 "' (no symbols present)");
1042 // Try to constant fold it up front, if possible.
1044 if (Res->EvaluateAsAbsolute(Value))
1045 Res = MCConstantExpr::Create(Value, getContext());
1050 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1052 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1055 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1058 SMLoc StartLoc = Lexer.getLoc();
1059 if (parseExpression(Expr))
1062 if (!Expr->EvaluateAsAbsolute(Res))
1063 return Error(StartLoc, "expected absolute expression");
1068 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1069 MCBinaryExpr::Opcode &Kind) {
1072 return 0; // not a binop.
1074 // Lowest Precedence: &&, ||
1075 case AsmToken::AmpAmp:
1076 Kind = MCBinaryExpr::LAnd;
1078 case AsmToken::PipePipe:
1079 Kind = MCBinaryExpr::LOr;
1082 // Low Precedence: |, &, ^
1084 // FIXME: gas seems to support '!' as an infix operator?
1085 case AsmToken::Pipe:
1086 Kind = MCBinaryExpr::Or;
1088 case AsmToken::Caret:
1089 Kind = MCBinaryExpr::Xor;
1092 Kind = MCBinaryExpr::And;
1095 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1096 case AsmToken::EqualEqual:
1097 Kind = MCBinaryExpr::EQ;
1099 case AsmToken::ExclaimEqual:
1100 case AsmToken::LessGreater:
1101 Kind = MCBinaryExpr::NE;
1103 case AsmToken::Less:
1104 Kind = MCBinaryExpr::LT;
1106 case AsmToken::LessEqual:
1107 Kind = MCBinaryExpr::LTE;
1109 case AsmToken::Greater:
1110 Kind = MCBinaryExpr::GT;
1112 case AsmToken::GreaterEqual:
1113 Kind = MCBinaryExpr::GTE;
1116 // Intermediate Precedence: <<, >>
1117 case AsmToken::LessLess:
1118 Kind = MCBinaryExpr::Shl;
1120 case AsmToken::GreaterGreater:
1121 Kind = MCBinaryExpr::Shr;
1124 // High Intermediate Precedence: +, -
1125 case AsmToken::Plus:
1126 Kind = MCBinaryExpr::Add;
1128 case AsmToken::Minus:
1129 Kind = MCBinaryExpr::Sub;
1132 // Highest Precedence: *, /, %
1133 case AsmToken::Star:
1134 Kind = MCBinaryExpr::Mul;
1136 case AsmToken::Slash:
1137 Kind = MCBinaryExpr::Div;
1139 case AsmToken::Percent:
1140 Kind = MCBinaryExpr::Mod;
1145 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1146 /// Res contains the LHS of the expression on input.
1147 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1150 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1151 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1153 // If the next token is lower precedence than we are allowed to eat, return
1154 // successfully with what we ate already.
1155 if (TokPrec < Precedence)
1160 // Eat the next primary expression.
1162 if (parsePrimaryExpr(RHS, EndLoc))
1165 // If BinOp binds less tightly with RHS than the operator after RHS, let
1166 // the pending operator take RHS as its LHS.
1167 MCBinaryExpr::Opcode Dummy;
1168 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1169 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1172 // Merge LHS and RHS according to operator.
1173 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1178 /// ::= EndOfStatement
1179 /// ::= Label* Directive ...Operands... EndOfStatement
1180 /// ::= Label* Identifier OperandList* EndOfStatement
1181 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1182 if (Lexer.is(AsmToken::EndOfStatement)) {
1188 // Statements always start with an identifier or are a full line comment.
1189 AsmToken ID = getTok();
1190 SMLoc IDLoc = ID.getLoc();
1192 int64_t LocalLabelVal = -1;
1193 // A full line comment is a '#' as the first token.
1194 if (Lexer.is(AsmToken::Hash))
1195 return parseCppHashLineFilenameComment(IDLoc);
1197 // Allow an integer followed by a ':' as a directional local label.
1198 if (Lexer.is(AsmToken::Integer)) {
1199 LocalLabelVal = getTok().getIntVal();
1200 if (LocalLabelVal < 0) {
1201 if (!TheCondState.Ignore)
1202 return TokError("unexpected token at start of statement");
1205 IDVal = getTok().getString();
1206 Lex(); // Consume the integer token to be used as an identifier token.
1207 if (Lexer.getKind() != AsmToken::Colon) {
1208 if (!TheCondState.Ignore)
1209 return TokError("unexpected token at start of statement");
1212 } else if (Lexer.is(AsmToken::Dot)) {
1213 // Treat '.' as a valid identifier in this context.
1216 } else if (parseIdentifier(IDVal)) {
1217 if (!TheCondState.Ignore)
1218 return TokError("unexpected token at start of statement");
1222 // Handle conditional assembly here before checking for skipping. We
1223 // have to do this so that .endif isn't skipped in a ".if 0" block for
1225 StringMap<DirectiveKind>::const_iterator DirKindIt =
1226 DirectiveKindMap.find(IDVal);
1227 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1229 : DirKindIt->getValue();
1235 return parseDirectiveIf(IDLoc);
1237 return parseDirectiveIfb(IDLoc, true);
1239 return parseDirectiveIfb(IDLoc, false);
1241 return parseDirectiveIfc(IDLoc, true);
1243 return parseDirectiveIfeqs(IDLoc);
1245 return parseDirectiveIfc(IDLoc, false);
1247 return parseDirectiveIfdef(IDLoc, true);
1250 return parseDirectiveIfdef(IDLoc, false);
1252 return parseDirectiveElseIf(IDLoc);
1254 return parseDirectiveElse(IDLoc);
1256 return parseDirectiveEndIf(IDLoc);
1259 // Ignore the statement if in the middle of inactive conditional
1261 if (TheCondState.Ignore) {
1262 eatToEndOfStatement();
1266 // FIXME: Recurse on local labels?
1268 // See what kind of statement we have.
1269 switch (Lexer.getKind()) {
1270 case AsmToken::Colon: {
1271 checkForValidSection();
1273 // identifier ':' -> Label.
1276 // Diagnose attempt to use '.' as a label.
1278 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1280 // Diagnose attempt to use a variable as a label.
1282 // FIXME: Diagnostics. Note the location of the definition as a label.
1283 // FIXME: This doesn't diagnose assignment to a symbol which has been
1284 // implicitly marked as external.
1286 if (LocalLabelVal == -1)
1287 Sym = getContext().GetOrCreateSymbol(IDVal);
1289 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1290 if (!Sym->isUndefined() || Sym->isVariable())
1291 return Error(IDLoc, "invalid symbol redefinition");
1294 if (!ParsingInlineAsm)
1297 // If we are generating dwarf for assembly source files then gather the
1298 // info to make a dwarf label entry for this label if needed.
1299 if (getContext().getGenDwarfForAssembly())
1300 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1303 getTargetParser().onLabelParsed(Sym);
1305 // Consume any end of statement token, if present, to avoid spurious
1306 // AddBlankLine calls().
1307 if (Lexer.is(AsmToken::EndOfStatement)) {
1309 if (Lexer.is(AsmToken::Eof))
1316 case AsmToken::Equal:
1317 // identifier '=' ... -> assignment statement
1320 return parseAssignment(IDVal, true);
1322 default: // Normal instruction or directive.
1326 // If macros are enabled, check to see if this is a macro instantiation.
1327 if (areMacrosEnabled())
1328 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1329 return handleMacroEntry(M, IDLoc);
1332 // Otherwise, we have a normal instruction or directive.
1334 // Directives start with "."
1335 if (IDVal[0] == '.' && IDVal != ".") {
1336 // There are several entities interested in parsing directives:
1338 // 1. The target-specific assembly parser. Some directives are target
1339 // specific or may potentially behave differently on certain targets.
1340 // 2. Asm parser extensions. For example, platform-specific parsers
1341 // (like the ELF parser) register themselves as extensions.
1342 // 3. The generic directive parser implemented by this class. These are
1343 // all the directives that behave in a target and platform independent
1344 // manner, or at least have a default behavior that's shared between
1345 // all targets and platforms.
1347 // First query the target-specific parser. It will return 'true' if it
1348 // isn't interested in this directive.
1349 if (!getTargetParser().ParseDirective(ID))
1352 // Next, check the extension directive map to see if any extension has
1353 // registered itself to parse this directive.
1354 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1355 ExtensionDirectiveMap.lookup(IDVal);
1357 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1359 // Finally, if no one else is interested in this directive, it must be
1360 // generic and familiar to this class.
1366 return parseDirectiveSet(IDVal, true);
1368 return parseDirectiveSet(IDVal, false);
1370 return parseDirectiveAscii(IDVal, false);
1373 return parseDirectiveAscii(IDVal, true);
1375 return parseDirectiveValue(1);
1379 return parseDirectiveValue(2);
1383 return parseDirectiveValue(4);
1386 return parseDirectiveValue(8);
1388 return parseDirectiveOctaValue();
1391 return parseDirectiveRealValue(APFloat::IEEEsingle);
1393 return parseDirectiveRealValue(APFloat::IEEEdouble);
1395 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1396 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1399 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1400 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1403 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1405 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1407 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1409 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1411 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1413 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1415 return parseDirectiveOrg();
1417 return parseDirectiveFill();
1419 return parseDirectiveZero();
1421 eatToEndOfStatement(); // .extern is the default, ignore it.
1425 return parseDirectiveSymbolAttribute(MCSA_Global);
1426 case DK_LAZY_REFERENCE:
1427 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1428 case DK_NO_DEAD_STRIP:
1429 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1430 case DK_SYMBOL_RESOLVER:
1431 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1432 case DK_PRIVATE_EXTERN:
1433 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1435 return parseDirectiveSymbolAttribute(MCSA_Reference);
1436 case DK_WEAK_DEFINITION:
1437 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1438 case DK_WEAK_REFERENCE:
1439 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1440 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1441 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1444 return parseDirectiveComm(/*IsLocal=*/false);
1446 return parseDirectiveComm(/*IsLocal=*/true);
1448 return parseDirectiveAbort();
1450 return parseDirectiveInclude();
1452 return parseDirectiveIncbin();
1455 return TokError(Twine(IDVal) + " not supported yet");
1457 return parseDirectiveRept(IDLoc, IDVal);
1459 return parseDirectiveIrp(IDLoc);
1461 return parseDirectiveIrpc(IDLoc);
1463 return parseDirectiveEndr(IDLoc);
1464 case DK_BUNDLE_ALIGN_MODE:
1465 return parseDirectiveBundleAlignMode();
1466 case DK_BUNDLE_LOCK:
1467 return parseDirectiveBundleLock();
1468 case DK_BUNDLE_UNLOCK:
1469 return parseDirectiveBundleUnlock();
1471 return parseDirectiveLEB128(true);
1473 return parseDirectiveLEB128(false);
1476 return parseDirectiveSpace(IDVal);
1478 return parseDirectiveFile(IDLoc);
1480 return parseDirectiveLine();
1482 return parseDirectiveLoc();
1484 return parseDirectiveStabs();
1485 case DK_CFI_SECTIONS:
1486 return parseDirectiveCFISections();
1487 case DK_CFI_STARTPROC:
1488 return parseDirectiveCFIStartProc();
1489 case DK_CFI_ENDPROC:
1490 return parseDirectiveCFIEndProc();
1491 case DK_CFI_DEF_CFA:
1492 return parseDirectiveCFIDefCfa(IDLoc);
1493 case DK_CFI_DEF_CFA_OFFSET:
1494 return parseDirectiveCFIDefCfaOffset();
1495 case DK_CFI_ADJUST_CFA_OFFSET:
1496 return parseDirectiveCFIAdjustCfaOffset();
1497 case DK_CFI_DEF_CFA_REGISTER:
1498 return parseDirectiveCFIDefCfaRegister(IDLoc);
1500 return parseDirectiveCFIOffset(IDLoc);
1501 case DK_CFI_REL_OFFSET:
1502 return parseDirectiveCFIRelOffset(IDLoc);
1503 case DK_CFI_PERSONALITY:
1504 return parseDirectiveCFIPersonalityOrLsda(true);
1506 return parseDirectiveCFIPersonalityOrLsda(false);
1507 case DK_CFI_REMEMBER_STATE:
1508 return parseDirectiveCFIRememberState();
1509 case DK_CFI_RESTORE_STATE:
1510 return parseDirectiveCFIRestoreState();
1511 case DK_CFI_SAME_VALUE:
1512 return parseDirectiveCFISameValue(IDLoc);
1513 case DK_CFI_RESTORE:
1514 return parseDirectiveCFIRestore(IDLoc);
1516 return parseDirectiveCFIEscape();
1517 case DK_CFI_SIGNAL_FRAME:
1518 return parseDirectiveCFISignalFrame();
1519 case DK_CFI_UNDEFINED:
1520 return parseDirectiveCFIUndefined(IDLoc);
1521 case DK_CFI_REGISTER:
1522 return parseDirectiveCFIRegister(IDLoc);
1523 case DK_CFI_WINDOW_SAVE:
1524 return parseDirectiveCFIWindowSave();
1527 return parseDirectiveMacrosOnOff(IDVal);
1529 return parseDirectiveMacro(IDLoc);
1532 return parseDirectiveEndMacro(IDVal);
1534 return parseDirectivePurgeMacro(IDLoc);
1536 return parseDirectiveEnd(IDLoc);
1538 return parseDirectiveError(IDLoc, false);
1540 return parseDirectiveError(IDLoc, true);
1543 return Error(IDLoc, "unknown directive");
1546 // __asm _emit or __asm __emit
1547 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1548 IDVal == "_EMIT" || IDVal == "__EMIT"))
1549 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1552 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1553 return parseDirectiveMSAlign(IDLoc, Info);
1555 checkForValidSection();
1557 // Canonicalize the opcode to lower case.
1558 std::string OpcodeStr = IDVal.lower();
1559 ParseInstructionInfo IInfo(Info.AsmRewrites);
1560 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1561 Info.ParsedOperands);
1562 Info.ParseError = HadError;
1564 // Dump the parsed representation, if requested.
1565 if (getShowParsedOperands()) {
1566 SmallString<256> Str;
1567 raw_svector_ostream OS(Str);
1568 OS << "parsed instruction: [";
1569 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1572 Info.ParsedOperands[i]->print(OS);
1576 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1579 // If we are generating dwarf for assembly source files and the current
1580 // section is the initial text section then generate a .loc directive for
1582 if (!HadError && getContext().getGenDwarfForAssembly() &&
1583 getContext().getGenDwarfSection() ==
1584 getStreamer().getCurrentSection().first) {
1586 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1588 // If we previously parsed a cpp hash file line comment then make sure the
1589 // current Dwarf File is for the CppHashFilename if not then emit the
1590 // Dwarf File table for it and adjust the line number for the .loc.
1591 if (CppHashFilename.size() != 0) {
1592 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1593 0, StringRef(), CppHashFilename);
1594 getContext().setGenDwarfFileNumber(FileNumber);
1596 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1597 // cache with the different Loc from the call above we save the last
1598 // info we queried here with SrcMgr.FindLineNumber().
1599 unsigned CppHashLocLineNo;
1600 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1601 CppHashLocLineNo = LastQueryLine;
1603 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1604 LastQueryLine = CppHashLocLineNo;
1605 LastQueryIDLoc = CppHashLoc;
1606 LastQueryBuffer = CppHashBuf;
1608 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1611 getStreamer().EmitDwarfLocDirective(
1612 getContext().getGenDwarfFileNumber(), Line, 0,
1613 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1617 // If parsing succeeded, match the instruction.
1620 HadError = getTargetParser().MatchAndEmitInstruction(
1621 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1625 // Don't skip the rest of the line, the instruction parser is responsible for
1630 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1631 /// since they may not be able to be tokenized to get to the end of line token.
1632 void AsmParser::eatToEndOfLine() {
1633 if (!Lexer.is(AsmToken::EndOfStatement))
1634 Lexer.LexUntilEndOfLine();
1639 /// parseCppHashLineFilenameComment as this:
1640 /// ::= # number "filename"
1641 /// or just as a full line comment if it doesn't have a number and a string.
1642 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1643 Lex(); // Eat the hash token.
1645 if (getLexer().isNot(AsmToken::Integer)) {
1646 // Consume the line since in cases it is not a well-formed line directive,
1647 // as if were simply a full line comment.
1652 int64_t LineNumber = getTok().getIntVal();
1655 if (getLexer().isNot(AsmToken::String)) {
1660 StringRef Filename = getTok().getString();
1661 // Get rid of the enclosing quotes.
1662 Filename = Filename.substr(1, Filename.size() - 2);
1664 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1666 CppHashFilename = Filename;
1667 CppHashLineNumber = LineNumber;
1668 CppHashBuf = CurBuffer;
1670 // Ignore any trailing characters, they're just comment.
1675 /// \brief will use the last parsed cpp hash line filename comment
1676 /// for the Filename and LineNo if any in the diagnostic.
1677 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1678 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1679 raw_ostream &OS = errs();
1681 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1682 const SMLoc &DiagLoc = Diag.getLoc();
1683 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1684 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1686 // Like SourceMgr::printMessage() we need to print the include stack if any
1687 // before printing the message.
1688 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1689 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1690 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1691 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1694 // If we have not parsed a cpp hash line filename comment or the source
1695 // manager changed or buffer changed (like in a nested include) then just
1696 // print the normal diagnostic using its Filename and LineNo.
1697 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1698 DiagBuf != CppHashBuf) {
1699 if (Parser->SavedDiagHandler)
1700 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1706 // Use the CppHashFilename and calculate a line number based on the
1707 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1709 const std::string &Filename = Parser->CppHashFilename;
1711 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1712 int CppHashLocLineNo =
1713 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1715 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1717 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1718 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1719 Diag.getLineContents(), Diag.getRanges());
1721 if (Parser->SavedDiagHandler)
1722 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1724 NewDiag.print(0, OS);
1727 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1728 // difference being that that function accepts '@' as part of identifiers and
1729 // we can't do that. AsmLexer.cpp should probably be changed to handle
1730 // '@' as a special case when needed.
1731 static bool isIdentifierChar(char c) {
1732 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1736 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1737 ArrayRef<MCAsmMacroParameter> Parameters,
1738 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1739 unsigned NParameters = Parameters.size();
1740 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1741 return Error(L, "Wrong number of arguments");
1743 // A macro without parameters is handled differently on Darwin:
1744 // gas accepts no arguments and does no substitutions
1745 while (!Body.empty()) {
1746 // Scan for the next substitution.
1747 std::size_t End = Body.size(), Pos = 0;
1748 for (; Pos != End; ++Pos) {
1749 // Check for a substitution or escape.
1750 if (IsDarwin && !NParameters) {
1751 // This macro has no parameters, look for $0, $1, etc.
1752 if (Body[Pos] != '$' || Pos + 1 == End)
1755 char Next = Body[Pos + 1];
1756 if (Next == '$' || Next == 'n' ||
1757 isdigit(static_cast<unsigned char>(Next)))
1760 // This macro has parameters, look for \foo, \bar, etc.
1761 if (Body[Pos] == '\\' && Pos + 1 != End)
1767 OS << Body.slice(0, Pos);
1769 // Check if we reached the end.
1773 if (IsDarwin && !NParameters) {
1774 switch (Body[Pos + 1]) {
1780 // $n => number of arguments
1785 // $[0-9] => argument
1787 // Missing arguments are ignored.
1788 unsigned Index = Body[Pos + 1] - '0';
1789 if (Index >= A.size())
1792 // Otherwise substitute with the token values, with spaces eliminated.
1793 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1794 ie = A[Index].end();
1796 OS << it->getString();
1802 unsigned I = Pos + 1;
1803 while (isIdentifierChar(Body[I]) && I + 1 != End)
1806 const char *Begin = Body.data() + Pos + 1;
1807 StringRef Argument(Begin, I - (Pos + 1));
1809 for (; Index < NParameters; ++Index)
1810 if (Parameters[Index].Name == Argument)
1813 if (Index == NParameters) {
1814 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1817 OS << '\\' << Argument;
1821 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1822 ie = A[Index].end();
1824 if (it->getKind() == AsmToken::String)
1825 OS << it->getStringContents();
1827 OS << it->getString();
1829 Pos += 1 + Argument.size();
1832 // Update the scan point.
1833 Body = Body.substr(Pos);
1839 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1840 SMLoc EL, MemoryBuffer *I)
1841 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1844 static bool isOperator(AsmToken::TokenKind kind) {
1848 case AsmToken::Plus:
1849 case AsmToken::Minus:
1850 case AsmToken::Tilde:
1851 case AsmToken::Slash:
1852 case AsmToken::Star:
1854 case AsmToken::Equal:
1855 case AsmToken::EqualEqual:
1856 case AsmToken::Pipe:
1857 case AsmToken::PipePipe:
1858 case AsmToken::Caret:
1860 case AsmToken::AmpAmp:
1861 case AsmToken::Exclaim:
1862 case AsmToken::ExclaimEqual:
1863 case AsmToken::Percent:
1864 case AsmToken::Less:
1865 case AsmToken::LessEqual:
1866 case AsmToken::LessLess:
1867 case AsmToken::LessGreater:
1868 case AsmToken::Greater:
1869 case AsmToken::GreaterEqual:
1870 case AsmToken::GreaterGreater:
1876 class AsmLexerSkipSpaceRAII {
1878 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1879 Lexer.setSkipSpace(SkipSpace);
1882 ~AsmLexerSkipSpaceRAII() {
1883 Lexer.setSkipSpace(true);
1891 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA) {
1892 unsigned ParenLevel = 0;
1893 unsigned AddTokens = 0;
1895 // Darwin doesn't use spaces to delmit arguments.
1896 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1899 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1900 return TokError("unexpected token in macro instantiation");
1902 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1905 if (Lexer.is(AsmToken::Space)) {
1906 Lex(); // Eat spaces
1908 // Spaces can delimit parameters, but could also be part an expression.
1909 // If the token after a space is an operator, add the token and the next
1910 // one into this argument
1912 if (isOperator(Lexer.getKind())) {
1913 // Check to see whether the token is used as an operator,
1914 // or part of an identifier
1915 const char *NextChar = getTok().getEndLoc().getPointer();
1916 if (*NextChar == ' ')
1920 if (!AddTokens && ParenLevel == 0) {
1926 // handleMacroEntry relies on not advancing the lexer here
1927 // to be able to fill in the remaining default parameter values
1928 if (Lexer.is(AsmToken::EndOfStatement))
1931 // Adjust the current parentheses level.
1932 if (Lexer.is(AsmToken::LParen))
1934 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1937 // Append the token to the current argument list.
1938 MA.push_back(getTok());
1944 if (ParenLevel != 0)
1945 return TokError("unbalanced parentheses in macro argument");
1949 // Parse the macro instantiation arguments.
1950 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1951 MCAsmMacroArguments &A) {
1952 const unsigned NParameters = M ? M->Parameters.size() : 0;
1953 bool NamedParametersFound = false;
1954 SmallVector<SMLoc, 4> FALocs;
1956 A.resize(NParameters);
1957 FALocs.resize(NParameters);
1959 // Parse two kinds of macro invocations:
1960 // - macros defined without any parameters accept an arbitrary number of them
1961 // - macros defined with parameters accept at most that many of them
1962 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1964 SMLoc IDLoc = Lexer.getLoc();
1965 MCAsmMacroParameter FA;
1967 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1968 if (parseIdentifier(FA.Name)) {
1969 Error(IDLoc, "invalid argument identifier for formal argument");
1970 eatToEndOfStatement();
1974 if (!Lexer.is(AsmToken::Equal)) {
1975 TokError("expected '=' after formal parameter identifier");
1976 eatToEndOfStatement();
1981 NamedParametersFound = true;
1984 if (NamedParametersFound && FA.Name.empty()) {
1985 Error(IDLoc, "cannot mix positional and keyword arguments");
1986 eatToEndOfStatement();
1990 if (parseMacroArgument(FA.Value))
1993 unsigned PI = Parameter;
1994 if (!FA.Name.empty()) {
1996 for (FAI = 0; FAI < NParameters; ++FAI)
1997 if (M->Parameters[FAI].Name == FA.Name)
2000 if (FAI >= NParameters) {
2002 "parameter named '" + FA.Name + "' does not exist for macro '" +
2003 (M ? M->Name : "<unnamed>") + "'");
2009 if (!FA.Value.empty()) {
2014 if (FALocs.size() <= PI)
2015 FALocs.resize(PI + 1);
2017 FALocs[PI] = Lexer.getLoc();
2020 // At the end of the statement, fill in remaining arguments that have
2021 // default values. If there aren't any, then the next argument is
2022 // required but missing
2023 if (Lexer.is(AsmToken::EndOfStatement)) {
2024 bool Failure = false;
2025 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2026 if (A[FAI].empty()) {
2027 if (M->Parameters[FAI].Required) {
2028 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2029 "missing value for required parameter "
2030 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2034 if (!M->Parameters[FAI].Value.empty())
2035 A[FAI] = M->Parameters[FAI].Value;
2041 if (Lexer.is(AsmToken::Comma))
2045 return TokError("too many positional arguments");
2048 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2049 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2050 return (I == MacroMap.end()) ? NULL : I->getValue();
2053 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2054 MacroMap[Name] = new MCAsmMacro(Macro);
2057 void AsmParser::undefineMacro(StringRef Name) {
2058 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2059 if (I != MacroMap.end()) {
2060 delete I->getValue();
2065 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2066 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2067 // this, although we should protect against infinite loops.
2068 if (ActiveMacros.size() == 20)
2069 return TokError("macros cannot be nested more than 20 levels deep");
2071 MCAsmMacroArguments A;
2072 if (parseMacroArguments(M, A))
2075 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2076 // to hold the macro body with substitutions.
2077 SmallString<256> Buf;
2078 StringRef Body = M->Body;
2079 raw_svector_ostream OS(Buf);
2081 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2084 // We include the .endmacro in the buffer as our cue to exit the macro
2086 OS << ".endmacro\n";
2088 MemoryBuffer *Instantiation =
2089 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2091 // Create the macro instantiation object and add to the current macro
2092 // instantiation stack.
2093 MacroInstantiation *MI = new MacroInstantiation(
2094 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2095 ActiveMacros.push_back(MI);
2097 // Jump to the macro instantiation and prime the lexer.
2098 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2099 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2105 void AsmParser::handleMacroExit() {
2106 // Jump to the EndOfStatement we should return to, and consume it.
2107 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2110 // Pop the instantiation entry.
2111 delete ActiveMacros.back();
2112 ActiveMacros.pop_back();
2115 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2116 switch (Value->getKind()) {
2117 case MCExpr::Binary: {
2118 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2119 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2121 case MCExpr::Target:
2122 case MCExpr::Constant:
2124 case MCExpr::SymbolRef: {
2126 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2128 return isUsedIn(Sym, S.getVariableValue());
2132 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2135 llvm_unreachable("Unknown expr kind!");
2138 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2140 // FIXME: Use better location, we should use proper tokens.
2141 SMLoc EqualLoc = Lexer.getLoc();
2143 const MCExpr *Value;
2144 if (parseExpression(Value))
2147 // Note: we don't count b as used in "a = b". This is to allow
2151 if (Lexer.isNot(AsmToken::EndOfStatement))
2152 return TokError("unexpected token in assignment");
2154 // Eat the end of statement marker.
2157 // Validate that the LHS is allowed to be a variable (either it has not been
2158 // used as a symbol, or it is an absolute symbol).
2159 MCSymbol *Sym = getContext().LookupSymbol(Name);
2161 // Diagnose assignment to a label.
2163 // FIXME: Diagnostics. Note the location of the definition as a label.
2164 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2165 if (isUsedIn(Sym, Value))
2166 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2167 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2168 ; // Allow redefinitions of undefined symbols only used in directives.
2169 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2170 ; // Allow redefinitions of variables that haven't yet been used.
2171 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2172 return Error(EqualLoc, "redefinition of '" + Name + "'");
2173 else if (!Sym->isVariable())
2174 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2175 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2176 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2179 // Don't count these checks as uses.
2180 Sym->setUsed(false);
2181 } else if (Name == ".") {
2182 if (Out.EmitValueToOffset(Value, 0)) {
2183 Error(EqualLoc, "expected absolute expression");
2184 eatToEndOfStatement();
2188 Sym = getContext().GetOrCreateSymbol(Name);
2190 // Do the assignment.
2191 Out.EmitAssignment(Sym, Value);
2193 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2198 /// parseIdentifier:
2201 bool AsmParser::parseIdentifier(StringRef &Res) {
2202 // The assembler has relaxed rules for accepting identifiers, in particular we
2203 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2204 // separate tokens. At this level, we have already lexed so we cannot (currently)
2205 // handle this as a context dependent token, instead we detect adjacent tokens
2206 // and return the combined identifier.
2207 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2208 SMLoc PrefixLoc = getLexer().getLoc();
2210 // Consume the prefix character, and check for a following identifier.
2212 if (Lexer.isNot(AsmToken::Identifier))
2215 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2216 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2219 // Construct the joined identifier and consume the token.
2221 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2226 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2229 Res = getTok().getIdentifier();
2231 Lex(); // Consume the identifier token.
2236 /// parseDirectiveSet:
2237 /// ::= .equ identifier ',' expression
2238 /// ::= .equiv identifier ',' expression
2239 /// ::= .set identifier ',' expression
2240 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2243 if (parseIdentifier(Name))
2244 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2246 if (getLexer().isNot(AsmToken::Comma))
2247 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2250 return parseAssignment(Name, allow_redef, true);
2253 bool AsmParser::parseEscapedString(std::string &Data) {
2254 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2257 StringRef Str = getTok().getStringContents();
2258 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2259 if (Str[i] != '\\') {
2264 // Recognize escaped characters. Note that this escape semantics currently
2265 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2268 return TokError("unexpected backslash at end of string");
2270 // Recognize octal sequences.
2271 if ((unsigned)(Str[i] - '0') <= 7) {
2272 // Consume up to three octal characters.
2273 unsigned Value = Str[i] - '0';
2275 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2277 Value = Value * 8 + (Str[i] - '0');
2279 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2281 Value = Value * 8 + (Str[i] - '0');
2286 return TokError("invalid octal escape sequence (out of range)");
2288 Data += (unsigned char)Value;
2292 // Otherwise recognize individual escapes.
2295 // Just reject invalid escape sequences for now.
2296 return TokError("invalid escape sequence (unrecognized character)");
2298 case 'b': Data += '\b'; break;
2299 case 'f': Data += '\f'; break;
2300 case 'n': Data += '\n'; break;
2301 case 'r': Data += '\r'; break;
2302 case 't': Data += '\t'; break;
2303 case '"': Data += '"'; break;
2304 case '\\': Data += '\\'; break;
2311 /// parseDirectiveAscii:
2312 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2313 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2314 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2315 checkForValidSection();
2318 if (getLexer().isNot(AsmToken::String))
2319 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2322 if (parseEscapedString(Data))
2325 getStreamer().EmitBytes(Data);
2327 getStreamer().EmitBytes(StringRef("\0", 1));
2331 if (getLexer().is(AsmToken::EndOfStatement))
2334 if (getLexer().isNot(AsmToken::Comma))
2335 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2344 /// parseDirectiveValue
2345 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2346 bool AsmParser::parseDirectiveValue(unsigned Size) {
2347 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2348 checkForValidSection();
2351 const MCExpr *Value;
2352 SMLoc ExprLoc = getLexer().getLoc();
2353 if (parseExpression(Value))
2356 // Special case constant expressions to match code generator.
2357 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2358 assert(Size <= 8 && "Invalid size");
2359 uint64_t IntValue = MCE->getValue();
2360 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2361 return Error(ExprLoc, "literal value out of range for directive");
2362 getStreamer().EmitIntValue(IntValue, Size);
2364 getStreamer().EmitValue(Value, Size);
2366 if (getLexer().is(AsmToken::EndOfStatement))
2369 // FIXME: Improve diagnostic.
2370 if (getLexer().isNot(AsmToken::Comma))
2371 return TokError("unexpected token in directive");
2380 /// ParseDirectiveOctaValue
2381 /// ::= .octa [ hexconstant (, hexconstant)* ]
2382 bool AsmParser::parseDirectiveOctaValue() {
2383 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2384 checkForValidSection();
2387 if (Lexer.getKind() == AsmToken::Error)
2389 if (Lexer.getKind() != AsmToken::Integer &&
2390 Lexer.getKind() != AsmToken::BigNum)
2391 return TokError("unknown token in expression");
2393 SMLoc ExprLoc = getLexer().getLoc();
2394 APInt IntValue = getTok().getAPIntVal();
2398 if (IntValue.isIntN(64)) {
2400 lo = IntValue.getZExtValue();
2401 } else if (IntValue.isIntN(128)) {
2402 // It might actually have more than 128 bits, but the top ones are zero.
2403 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2404 lo = IntValue.getLoBits(64).getZExtValue();
2406 return Error(ExprLoc, "literal value out of range for directive");
2408 if (MAI.isLittleEndian()) {
2409 getStreamer().EmitIntValue(lo, 8);
2410 getStreamer().EmitIntValue(hi, 8);
2412 getStreamer().EmitIntValue(hi, 8);
2413 getStreamer().EmitIntValue(lo, 8);
2416 if (getLexer().is(AsmToken::EndOfStatement))
2419 // FIXME: Improve diagnostic.
2420 if (getLexer().isNot(AsmToken::Comma))
2421 return TokError("unexpected token in directive");
2430 /// parseDirectiveRealValue
2431 /// ::= (.single | .double) [ expression (, expression)* ]
2432 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2433 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2434 checkForValidSection();
2437 // We don't truly support arithmetic on floating point expressions, so we
2438 // have to manually parse unary prefixes.
2440 if (getLexer().is(AsmToken::Minus)) {
2443 } else if (getLexer().is(AsmToken::Plus))
2446 if (getLexer().isNot(AsmToken::Integer) &&
2447 getLexer().isNot(AsmToken::Real) &&
2448 getLexer().isNot(AsmToken::Identifier))
2449 return TokError("unexpected token in directive");
2451 // Convert to an APFloat.
2452 APFloat Value(Semantics);
2453 StringRef IDVal = getTok().getString();
2454 if (getLexer().is(AsmToken::Identifier)) {
2455 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2456 Value = APFloat::getInf(Semantics);
2457 else if (!IDVal.compare_lower("nan"))
2458 Value = APFloat::getNaN(Semantics, false, ~0);
2460 return TokError("invalid floating point literal");
2461 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2462 APFloat::opInvalidOp)
2463 return TokError("invalid floating point literal");
2467 // Consume the numeric token.
2470 // Emit the value as an integer.
2471 APInt AsInt = Value.bitcastToAPInt();
2472 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2473 AsInt.getBitWidth() / 8);
2475 if (getLexer().is(AsmToken::EndOfStatement))
2478 if (getLexer().isNot(AsmToken::Comma))
2479 return TokError("unexpected token in directive");
2488 /// parseDirectiveZero
2489 /// ::= .zero expression
2490 bool AsmParser::parseDirectiveZero() {
2491 checkForValidSection();
2494 if (parseAbsoluteExpression(NumBytes))
2498 if (getLexer().is(AsmToken::Comma)) {
2500 if (parseAbsoluteExpression(Val))
2504 if (getLexer().isNot(AsmToken::EndOfStatement))
2505 return TokError("unexpected token in '.zero' directive");
2509 getStreamer().EmitFill(NumBytes, Val);
2514 /// parseDirectiveFill
2515 /// ::= .fill expression [ , expression [ , expression ] ]
2516 bool AsmParser::parseDirectiveFill() {
2517 checkForValidSection();
2519 SMLoc RepeatLoc = getLexer().getLoc();
2521 if (parseAbsoluteExpression(NumValues))
2524 if (NumValues < 0) {
2526 "'.fill' directive with negative repeat count has no effect");
2530 int64_t FillSize = 1;
2531 int64_t FillExpr = 0;
2533 SMLoc SizeLoc, ExprLoc;
2534 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2535 if (getLexer().isNot(AsmToken::Comma))
2536 return TokError("unexpected token in '.fill' directive");
2539 SizeLoc = getLexer().getLoc();
2540 if (parseAbsoluteExpression(FillSize))
2543 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2544 if (getLexer().isNot(AsmToken::Comma))
2545 return TokError("unexpected token in '.fill' directive");
2548 ExprLoc = getLexer().getLoc();
2549 if (parseAbsoluteExpression(FillExpr))
2552 if (getLexer().isNot(AsmToken::EndOfStatement))
2553 return TokError("unexpected token in '.fill' directive");
2560 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2564 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2568 if (!isUInt<32>(FillExpr) && FillSize > 4)
2569 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2571 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2572 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2574 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2575 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2576 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2582 /// parseDirectiveOrg
2583 /// ::= .org expression [ , expression ]
2584 bool AsmParser::parseDirectiveOrg() {
2585 checkForValidSection();
2587 const MCExpr *Offset;
2588 SMLoc Loc = getTok().getLoc();
2589 if (parseExpression(Offset))
2592 // Parse optional fill expression.
2593 int64_t FillExpr = 0;
2594 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2595 if (getLexer().isNot(AsmToken::Comma))
2596 return TokError("unexpected token in '.org' directive");
2599 if (parseAbsoluteExpression(FillExpr))
2602 if (getLexer().isNot(AsmToken::EndOfStatement))
2603 return TokError("unexpected token in '.org' directive");
2608 // Only limited forms of relocatable expressions are accepted here, it
2609 // has to be relative to the current section. The streamer will return
2610 // 'true' if the expression wasn't evaluatable.
2611 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2612 return Error(Loc, "expected assembly-time absolute expression");
2617 /// parseDirectiveAlign
2618 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2619 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2620 checkForValidSection();
2622 SMLoc AlignmentLoc = getLexer().getLoc();
2624 if (parseAbsoluteExpression(Alignment))
2628 bool HasFillExpr = false;
2629 int64_t FillExpr = 0;
2630 int64_t MaxBytesToFill = 0;
2631 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2632 if (getLexer().isNot(AsmToken::Comma))
2633 return TokError("unexpected token in directive");
2636 // The fill expression can be omitted while specifying a maximum number of
2637 // alignment bytes, e.g:
2639 if (getLexer().isNot(AsmToken::Comma)) {
2641 if (parseAbsoluteExpression(FillExpr))
2645 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2646 if (getLexer().isNot(AsmToken::Comma))
2647 return TokError("unexpected token in directive");
2650 MaxBytesLoc = getLexer().getLoc();
2651 if (parseAbsoluteExpression(MaxBytesToFill))
2654 if (getLexer().isNot(AsmToken::EndOfStatement))
2655 return TokError("unexpected token in directive");
2664 // Compute alignment in bytes.
2666 // FIXME: Diagnose overflow.
2667 if (Alignment >= 32) {
2668 Error(AlignmentLoc, "invalid alignment value");
2672 Alignment = 1ULL << Alignment;
2674 // Reject alignments that aren't a power of two, for gas compatibility.
2675 if (!isPowerOf2_64(Alignment))
2676 Error(AlignmentLoc, "alignment must be a power of 2");
2679 // Diagnose non-sensical max bytes to align.
2680 if (MaxBytesLoc.isValid()) {
2681 if (MaxBytesToFill < 1) {
2682 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2683 "many bytes, ignoring maximum bytes expression");
2687 if (MaxBytesToFill >= Alignment) {
2688 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2694 // Check whether we should use optimal code alignment for this .align
2696 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2697 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2698 ValueSize == 1 && UseCodeAlign) {
2699 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2701 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2702 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2709 /// parseDirectiveFile
2710 /// ::= .file [number] filename
2711 /// ::= .file number directory filename
2712 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2713 // FIXME: I'm not sure what this is.
2714 int64_t FileNumber = -1;
2715 SMLoc FileNumberLoc = getLexer().getLoc();
2716 if (getLexer().is(AsmToken::Integer)) {
2717 FileNumber = getTok().getIntVal();
2721 return TokError("file number less than one");
2724 if (getLexer().isNot(AsmToken::String))
2725 return TokError("unexpected token in '.file' directive");
2727 // Usually the directory and filename together, otherwise just the directory.
2728 // Allow the strings to have escaped octal character sequence.
2729 std::string Path = getTok().getString();
2730 if (parseEscapedString(Path))
2734 StringRef Directory;
2736 std::string FilenameData;
2737 if (getLexer().is(AsmToken::String)) {
2738 if (FileNumber == -1)
2739 return TokError("explicit path specified, but no file number");
2740 if (parseEscapedString(FilenameData))
2742 Filename = FilenameData;
2749 if (getLexer().isNot(AsmToken::EndOfStatement))
2750 return TokError("unexpected token in '.file' directive");
2752 if (FileNumber == -1)
2753 getStreamer().EmitFileDirective(Filename);
2755 if (getContext().getGenDwarfForAssembly() == true)
2757 "input can't have .file dwarf directives when -g is "
2758 "used to generate dwarf debug info for assembly code");
2760 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2762 Error(FileNumberLoc, "file number already allocated");
2768 /// parseDirectiveLine
2769 /// ::= .line [number]
2770 bool AsmParser::parseDirectiveLine() {
2771 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2772 if (getLexer().isNot(AsmToken::Integer))
2773 return TokError("unexpected token in '.line' directive");
2775 int64_t LineNumber = getTok().getIntVal();
2779 // FIXME: Do something with the .line.
2782 if (getLexer().isNot(AsmToken::EndOfStatement))
2783 return TokError("unexpected token in '.line' directive");
2788 /// parseDirectiveLoc
2789 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2790 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2791 /// The first number is a file number, must have been previously assigned with
2792 /// a .file directive, the second number is the line number and optionally the
2793 /// third number is a column position (zero if not specified). The remaining
2794 /// optional items are .loc sub-directives.
2795 bool AsmParser::parseDirectiveLoc() {
2796 if (getLexer().isNot(AsmToken::Integer))
2797 return TokError("unexpected token in '.loc' directive");
2798 int64_t FileNumber = getTok().getIntVal();
2800 return TokError("file number less than one in '.loc' directive");
2801 if (!getContext().isValidDwarfFileNumber(FileNumber))
2802 return TokError("unassigned file number in '.loc' directive");
2805 int64_t LineNumber = 0;
2806 if (getLexer().is(AsmToken::Integer)) {
2807 LineNumber = getTok().getIntVal();
2809 return TokError("line number less than zero in '.loc' directive");
2813 int64_t ColumnPos = 0;
2814 if (getLexer().is(AsmToken::Integer)) {
2815 ColumnPos = getTok().getIntVal();
2817 return TokError("column position less than zero in '.loc' directive");
2821 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2823 int64_t Discriminator = 0;
2824 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2826 if (getLexer().is(AsmToken::EndOfStatement))
2830 SMLoc Loc = getTok().getLoc();
2831 if (parseIdentifier(Name))
2832 return TokError("unexpected token in '.loc' directive");
2834 if (Name == "basic_block")
2835 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2836 else if (Name == "prologue_end")
2837 Flags |= DWARF2_FLAG_PROLOGUE_END;
2838 else if (Name == "epilogue_begin")
2839 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2840 else if (Name == "is_stmt") {
2841 Loc = getTok().getLoc();
2842 const MCExpr *Value;
2843 if (parseExpression(Value))
2845 // The expression must be the constant 0 or 1.
2846 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2847 int Value = MCE->getValue();
2849 Flags &= ~DWARF2_FLAG_IS_STMT;
2850 else if (Value == 1)
2851 Flags |= DWARF2_FLAG_IS_STMT;
2853 return Error(Loc, "is_stmt value not 0 or 1");
2855 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2857 } else if (Name == "isa") {
2858 Loc = getTok().getLoc();
2859 const MCExpr *Value;
2860 if (parseExpression(Value))
2862 // The expression must be a constant greater or equal to 0.
2863 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2864 int Value = MCE->getValue();
2866 return Error(Loc, "isa number less than zero");
2869 return Error(Loc, "isa number not a constant value");
2871 } else if (Name == "discriminator") {
2872 if (parseAbsoluteExpression(Discriminator))
2875 return Error(Loc, "unknown sub-directive in '.loc' directive");
2878 if (getLexer().is(AsmToken::EndOfStatement))
2883 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2884 Isa, Discriminator, StringRef());
2889 /// parseDirectiveStabs
2890 /// ::= .stabs string, number, number, number
2891 bool AsmParser::parseDirectiveStabs() {
2892 return TokError("unsupported directive '.stabs'");
2895 /// parseDirectiveCFISections
2896 /// ::= .cfi_sections section [, section]
2897 bool AsmParser::parseDirectiveCFISections() {
2902 if (parseIdentifier(Name))
2903 return TokError("Expected an identifier");
2905 if (Name == ".eh_frame")
2907 else if (Name == ".debug_frame")
2910 if (getLexer().is(AsmToken::Comma)) {
2913 if (parseIdentifier(Name))
2914 return TokError("Expected an identifier");
2916 if (Name == ".eh_frame")
2918 else if (Name == ".debug_frame")
2922 getStreamer().EmitCFISections(EH, Debug);
2926 /// parseDirectiveCFIStartProc
2927 /// ::= .cfi_startproc [simple]
2928 bool AsmParser::parseDirectiveCFIStartProc() {
2930 if (getLexer().isNot(AsmToken::EndOfStatement))
2931 if (parseIdentifier(Simple) || Simple != "simple")
2932 return TokError("unexpected token in .cfi_startproc directive");
2934 getStreamer().EmitCFIStartProc(!Simple.empty());
2938 /// parseDirectiveCFIEndProc
2939 /// ::= .cfi_endproc
2940 bool AsmParser::parseDirectiveCFIEndProc() {
2941 getStreamer().EmitCFIEndProc();
2945 /// \brief parse register name or number.
2946 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2947 SMLoc DirectiveLoc) {
2950 if (getLexer().isNot(AsmToken::Integer)) {
2951 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2953 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2955 return parseAbsoluteExpression(Register);
2960 /// parseDirectiveCFIDefCfa
2961 /// ::= .cfi_def_cfa register, offset
2962 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2963 int64_t Register = 0;
2964 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2967 if (getLexer().isNot(AsmToken::Comma))
2968 return TokError("unexpected token in directive");
2972 if (parseAbsoluteExpression(Offset))
2975 getStreamer().EmitCFIDefCfa(Register, Offset);
2979 /// parseDirectiveCFIDefCfaOffset
2980 /// ::= .cfi_def_cfa_offset offset
2981 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2983 if (parseAbsoluteExpression(Offset))
2986 getStreamer().EmitCFIDefCfaOffset(Offset);
2990 /// parseDirectiveCFIRegister
2991 /// ::= .cfi_register register, register
2992 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2993 int64_t Register1 = 0;
2994 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2997 if (getLexer().isNot(AsmToken::Comma))
2998 return TokError("unexpected token in directive");
3001 int64_t Register2 = 0;
3002 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3005 getStreamer().EmitCFIRegister(Register1, Register2);
3009 /// parseDirectiveCFIWindowSave
3010 /// ::= .cfi_window_save
3011 bool AsmParser::parseDirectiveCFIWindowSave() {
3012 getStreamer().EmitCFIWindowSave();
3016 /// parseDirectiveCFIAdjustCfaOffset
3017 /// ::= .cfi_adjust_cfa_offset adjustment
3018 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3019 int64_t Adjustment = 0;
3020 if (parseAbsoluteExpression(Adjustment))
3023 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3027 /// parseDirectiveCFIDefCfaRegister
3028 /// ::= .cfi_def_cfa_register register
3029 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3030 int64_t Register = 0;
3031 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3034 getStreamer().EmitCFIDefCfaRegister(Register);
3038 /// parseDirectiveCFIOffset
3039 /// ::= .cfi_offset register, offset
3040 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3041 int64_t Register = 0;
3044 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3047 if (getLexer().isNot(AsmToken::Comma))
3048 return TokError("unexpected token in directive");
3051 if (parseAbsoluteExpression(Offset))
3054 getStreamer().EmitCFIOffset(Register, Offset);
3058 /// parseDirectiveCFIRelOffset
3059 /// ::= .cfi_rel_offset register, offset
3060 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3061 int64_t Register = 0;
3063 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3066 if (getLexer().isNot(AsmToken::Comma))
3067 return TokError("unexpected token in directive");
3071 if (parseAbsoluteExpression(Offset))
3074 getStreamer().EmitCFIRelOffset(Register, Offset);
3078 static bool isValidEncoding(int64_t Encoding) {
3079 if (Encoding & ~0xff)
3082 if (Encoding == dwarf::DW_EH_PE_omit)
3085 const unsigned Format = Encoding & 0xf;
3086 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3087 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3088 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3089 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3092 const unsigned Application = Encoding & 0x70;
3093 if (Application != dwarf::DW_EH_PE_absptr &&
3094 Application != dwarf::DW_EH_PE_pcrel)
3100 /// parseDirectiveCFIPersonalityOrLsda
3101 /// IsPersonality true for cfi_personality, false for cfi_lsda
3102 /// ::= .cfi_personality encoding, [symbol_name]
3103 /// ::= .cfi_lsda encoding, [symbol_name]
3104 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3105 int64_t Encoding = 0;
3106 if (parseAbsoluteExpression(Encoding))
3108 if (Encoding == dwarf::DW_EH_PE_omit)
3111 if (!isValidEncoding(Encoding))
3112 return TokError("unsupported encoding.");
3114 if (getLexer().isNot(AsmToken::Comma))
3115 return TokError("unexpected token in directive");
3119 if (parseIdentifier(Name))
3120 return TokError("expected identifier in directive");
3122 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3125 getStreamer().EmitCFIPersonality(Sym, Encoding);
3127 getStreamer().EmitCFILsda(Sym, Encoding);
3131 /// parseDirectiveCFIRememberState
3132 /// ::= .cfi_remember_state
3133 bool AsmParser::parseDirectiveCFIRememberState() {
3134 getStreamer().EmitCFIRememberState();
3138 /// parseDirectiveCFIRestoreState
3139 /// ::= .cfi_remember_state
3140 bool AsmParser::parseDirectiveCFIRestoreState() {
3141 getStreamer().EmitCFIRestoreState();
3145 /// parseDirectiveCFISameValue
3146 /// ::= .cfi_same_value register
3147 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3148 int64_t Register = 0;
3150 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3153 getStreamer().EmitCFISameValue(Register);
3157 /// parseDirectiveCFIRestore
3158 /// ::= .cfi_restore register
3159 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3160 int64_t Register = 0;
3161 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3164 getStreamer().EmitCFIRestore(Register);
3168 /// parseDirectiveCFIEscape
3169 /// ::= .cfi_escape expression[,...]
3170 bool AsmParser::parseDirectiveCFIEscape() {
3173 if (parseAbsoluteExpression(CurrValue))
3176 Values.push_back((uint8_t)CurrValue);
3178 while (getLexer().is(AsmToken::Comma)) {
3181 if (parseAbsoluteExpression(CurrValue))
3184 Values.push_back((uint8_t)CurrValue);
3187 getStreamer().EmitCFIEscape(Values);
3191 /// parseDirectiveCFISignalFrame
3192 /// ::= .cfi_signal_frame
3193 bool AsmParser::parseDirectiveCFISignalFrame() {
3194 if (getLexer().isNot(AsmToken::EndOfStatement))
3195 return Error(getLexer().getLoc(),
3196 "unexpected token in '.cfi_signal_frame'");
3198 getStreamer().EmitCFISignalFrame();
3202 /// parseDirectiveCFIUndefined
3203 /// ::= .cfi_undefined register
3204 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3205 int64_t Register = 0;
3207 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3210 getStreamer().EmitCFIUndefined(Register);
3214 /// parseDirectiveMacrosOnOff
3217 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3218 if (getLexer().isNot(AsmToken::EndOfStatement))
3219 return Error(getLexer().getLoc(),
3220 "unexpected token in '" + Directive + "' directive");
3222 setMacrosEnabled(Directive == ".macros_on");
3226 /// parseDirectiveMacro
3227 /// ::= .macro name[,] [parameters]
3228 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3230 if (parseIdentifier(Name))
3231 return TokError("expected identifier in '.macro' directive");
3233 if (getLexer().is(AsmToken::Comma))
3236 MCAsmMacroParameters Parameters;
3237 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3238 MCAsmMacroParameter Parameter;
3239 if (parseIdentifier(Parameter.Name))
3240 return TokError("expected identifier in '.macro' directive");
3242 if (Lexer.is(AsmToken::Colon)) {
3243 Lex(); // consume ':'
3246 StringRef Qualifier;
3248 QualLoc = Lexer.getLoc();
3249 if (parseIdentifier(Qualifier))
3250 return Error(QualLoc, "missing parameter qualifier for "
3251 "'" + Parameter.Name + "' in macro '" + Name + "'");
3253 if (Qualifier == "req")
3254 Parameter.Required = true;
3256 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3257 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3260 if (getLexer().is(AsmToken::Equal)) {
3265 ParamLoc = Lexer.getLoc();
3266 if (parseMacroArgument(Parameter.Value))
3269 if (Parameter.Required)
3270 Warning(ParamLoc, "pointless default value for required parameter "
3271 "'" + Parameter.Name + "' in macro '" + Name + "'");
3274 Parameters.push_back(Parameter);
3276 if (getLexer().is(AsmToken::Comma))
3280 // Eat the end of statement.
3283 AsmToken EndToken, StartToken = getTok();
3284 unsigned MacroDepth = 0;
3286 // Lex the macro definition.
3288 // Check whether we have reached the end of the file.
3289 if (getLexer().is(AsmToken::Eof))
3290 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3292 // Otherwise, check whether we have reach the .endmacro.
3293 if (getLexer().is(AsmToken::Identifier)) {
3294 if (getTok().getIdentifier() == ".endm" ||
3295 getTok().getIdentifier() == ".endmacro") {
3296 if (MacroDepth == 0) { // Outermost macro.
3297 EndToken = getTok();
3299 if (getLexer().isNot(AsmToken::EndOfStatement))
3300 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3304 // Otherwise we just found the end of an inner macro.
3307 } else if (getTok().getIdentifier() == ".macro") {
3308 // We allow nested macros. Those aren't instantiated until the outermost
3309 // macro is expanded so just ignore them for now.
3314 // Otherwise, scan til the end of the statement.
3315 eatToEndOfStatement();
3318 if (lookupMacro(Name)) {
3319 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3322 const char *BodyStart = StartToken.getLoc().getPointer();
3323 const char *BodyEnd = EndToken.getLoc().getPointer();
3324 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3325 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3326 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3330 /// checkForBadMacro
3332 /// With the support added for named parameters there may be code out there that
3333 /// is transitioning from positional parameters. In versions of gas that did
3334 /// not support named parameters they would be ignored on the macro definition.
3335 /// But to support both styles of parameters this is not possible so if a macro
3336 /// definition has named parameters but does not use them and has what appears
3337 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3338 /// warning that the positional parameter found in body which have no effect.
3339 /// Hoping the developer will either remove the named parameters from the macro
3340 /// definition so the positional parameters get used if that was what was
3341 /// intended or change the macro to use the named parameters. It is possible
3342 /// this warning will trigger when the none of the named parameters are used
3343 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3344 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3346 ArrayRef<MCAsmMacroParameter> Parameters) {
3347 // If this macro is not defined with named parameters the warning we are
3348 // checking for here doesn't apply.
3349 unsigned NParameters = Parameters.size();
3350 if (NParameters == 0)
3353 bool NamedParametersFound = false;
3354 bool PositionalParametersFound = false;
3356 // Look at the body of the macro for use of both the named parameters and what
3357 // are likely to be positional parameters. This is what expandMacro() is
3358 // doing when it finds the parameters in the body.
3359 while (!Body.empty()) {
3360 // Scan for the next possible parameter.
3361 std::size_t End = Body.size(), Pos = 0;
3362 for (; Pos != End; ++Pos) {
3363 // Check for a substitution or escape.
3364 // This macro is defined with parameters, look for \foo, \bar, etc.
3365 if (Body[Pos] == '\\' && Pos + 1 != End)
3368 // This macro should have parameters, but look for $0, $1, ..., $n too.
3369 if (Body[Pos] != '$' || Pos + 1 == End)
3371 char Next = Body[Pos + 1];
3372 if (Next == '$' || Next == 'n' ||
3373 isdigit(static_cast<unsigned char>(Next)))
3377 // Check if we reached the end.
3381 if (Body[Pos] == '$') {
3382 switch (Body[Pos + 1]) {
3387 // $n => number of arguments
3389 PositionalParametersFound = true;
3392 // $[0-9] => argument
3394 PositionalParametersFound = true;
3400 unsigned I = Pos + 1;
3401 while (isIdentifierChar(Body[I]) && I + 1 != End)
3404 const char *Begin = Body.data() + Pos + 1;
3405 StringRef Argument(Begin, I - (Pos + 1));
3407 for (; Index < NParameters; ++Index)
3408 if (Parameters[Index].Name == Argument)
3411 if (Index == NParameters) {
3412 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3418 NamedParametersFound = true;
3419 Pos += 1 + Argument.size();
3422 // Update the scan point.
3423 Body = Body.substr(Pos);
3426 if (!NamedParametersFound && PositionalParametersFound)
3427 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3428 "used in macro body, possible positional parameter "
3429 "found in body which will have no effect");
3432 /// parseDirectiveEndMacro
3435 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3436 if (getLexer().isNot(AsmToken::EndOfStatement))
3437 return TokError("unexpected token in '" + Directive + "' directive");
3439 // If we are inside a macro instantiation, terminate the current
3441 if (isInsideMacroInstantiation()) {
3446 // Otherwise, this .endmacro is a stray entry in the file; well formed
3447 // .endmacro directives are handled during the macro definition parsing.
3448 return TokError("unexpected '" + Directive + "' in file, "
3449 "no current macro definition");
3452 /// parseDirectivePurgeMacro
3454 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3456 if (parseIdentifier(Name))
3457 return TokError("expected identifier in '.purgem' directive");
3459 if (getLexer().isNot(AsmToken::EndOfStatement))
3460 return TokError("unexpected token in '.purgem' directive");
3462 if (!lookupMacro(Name))
3463 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3465 undefineMacro(Name);
3469 /// parseDirectiveBundleAlignMode
3470 /// ::= {.bundle_align_mode} expression
3471 bool AsmParser::parseDirectiveBundleAlignMode() {
3472 checkForValidSection();
3474 // Expect a single argument: an expression that evaluates to a constant
3475 // in the inclusive range 0-30.
3476 SMLoc ExprLoc = getLexer().getLoc();
3477 int64_t AlignSizePow2;
3478 if (parseAbsoluteExpression(AlignSizePow2))
3480 else if (getLexer().isNot(AsmToken::EndOfStatement))
3481 return TokError("unexpected token after expression in"
3482 " '.bundle_align_mode' directive");
3483 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3484 return Error(ExprLoc,
3485 "invalid bundle alignment size (expected between 0 and 30)");
3489 // Because of AlignSizePow2's verified range we can safely truncate it to
3491 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3495 /// parseDirectiveBundleLock
3496 /// ::= {.bundle_lock} [align_to_end]
3497 bool AsmParser::parseDirectiveBundleLock() {
3498 checkForValidSection();
3499 bool AlignToEnd = false;
3501 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3503 SMLoc Loc = getTok().getLoc();
3504 const char *kInvalidOptionError =
3505 "invalid option for '.bundle_lock' directive";
3507 if (parseIdentifier(Option))
3508 return Error(Loc, kInvalidOptionError);
3510 if (Option != "align_to_end")
3511 return Error(Loc, kInvalidOptionError);
3512 else if (getLexer().isNot(AsmToken::EndOfStatement))
3514 "unexpected token after '.bundle_lock' directive option");
3520 getStreamer().EmitBundleLock(AlignToEnd);
3524 /// parseDirectiveBundleLock
3525 /// ::= {.bundle_lock}
3526 bool AsmParser::parseDirectiveBundleUnlock() {
3527 checkForValidSection();
3529 if (getLexer().isNot(AsmToken::EndOfStatement))
3530 return TokError("unexpected token in '.bundle_unlock' directive");
3533 getStreamer().EmitBundleUnlock();
3537 /// parseDirectiveSpace
3538 /// ::= (.skip | .space) expression [ , expression ]
3539 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3540 checkForValidSection();
3543 if (parseAbsoluteExpression(NumBytes))
3546 int64_t FillExpr = 0;
3547 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3548 if (getLexer().isNot(AsmToken::Comma))
3549 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3552 if (parseAbsoluteExpression(FillExpr))
3555 if (getLexer().isNot(AsmToken::EndOfStatement))
3556 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3562 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3565 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3566 getStreamer().EmitFill(NumBytes, FillExpr);
3571 /// parseDirectiveLEB128
3572 /// ::= (.sleb128 | .uleb128) expression
3573 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3574 checkForValidSection();
3575 const MCExpr *Value;
3577 if (parseExpression(Value))
3580 if (getLexer().isNot(AsmToken::EndOfStatement))
3581 return TokError("unexpected token in directive");
3584 getStreamer().EmitSLEB128Value(Value);
3586 getStreamer().EmitULEB128Value(Value);
3591 /// parseDirectiveSymbolAttribute
3592 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3593 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3594 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3597 SMLoc Loc = getTok().getLoc();
3599 if (parseIdentifier(Name))
3600 return Error(Loc, "expected identifier in directive");
3602 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3604 // Assembler local symbols don't make any sense here. Complain loudly.
3605 if (Sym->isTemporary())
3606 return Error(Loc, "non-local symbol required in directive");
3608 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3609 return Error(Loc, "unable to emit symbol attribute");
3611 if (getLexer().is(AsmToken::EndOfStatement))
3614 if (getLexer().isNot(AsmToken::Comma))
3615 return TokError("unexpected token in directive");
3624 /// parseDirectiveComm
3625 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3626 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3627 checkForValidSection();
3629 SMLoc IDLoc = getLexer().getLoc();
3631 if (parseIdentifier(Name))
3632 return TokError("expected identifier in directive");
3634 // Handle the identifier as the key symbol.
3635 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3637 if (getLexer().isNot(AsmToken::Comma))
3638 return TokError("unexpected token in directive");
3642 SMLoc SizeLoc = getLexer().getLoc();
3643 if (parseAbsoluteExpression(Size))
3646 int64_t Pow2Alignment = 0;
3647 SMLoc Pow2AlignmentLoc;
3648 if (getLexer().is(AsmToken::Comma)) {
3650 Pow2AlignmentLoc = getLexer().getLoc();
3651 if (parseAbsoluteExpression(Pow2Alignment))
3654 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3655 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3656 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3658 // If this target takes alignments in bytes (not log) validate and convert.
3659 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3660 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3661 if (!isPowerOf2_64(Pow2Alignment))
3662 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3663 Pow2Alignment = Log2_64(Pow2Alignment);
3667 if (getLexer().isNot(AsmToken::EndOfStatement))
3668 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3672 // NOTE: a size of zero for a .comm should create a undefined symbol
3673 // but a size of .lcomm creates a bss symbol of size zero.
3675 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3676 "be less than zero");
3678 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3679 // may internally end up wanting an alignment in bytes.
3680 // FIXME: Diagnose overflow.
3681 if (Pow2Alignment < 0)
3682 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3683 "alignment, can't be less than zero");
3685 if (!Sym->isUndefined())
3686 return Error(IDLoc, "invalid symbol redefinition");
3688 // Create the Symbol as a common or local common with Size and Pow2Alignment
3690 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3694 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3698 /// parseDirectiveAbort
3699 /// ::= .abort [... message ...]
3700 bool AsmParser::parseDirectiveAbort() {
3701 // FIXME: Use loc from directive.
3702 SMLoc Loc = getLexer().getLoc();
3704 StringRef Str = parseStringToEndOfStatement();
3705 if (getLexer().isNot(AsmToken::EndOfStatement))
3706 return TokError("unexpected token in '.abort' directive");
3711 Error(Loc, ".abort detected. Assembly stopping.");
3713 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3714 // FIXME: Actually abort assembly here.
3719 /// parseDirectiveInclude
3720 /// ::= .include "filename"
3721 bool AsmParser::parseDirectiveInclude() {
3722 if (getLexer().isNot(AsmToken::String))
3723 return TokError("expected string in '.include' directive");
3725 // Allow the strings to have escaped octal character sequence.
3726 std::string Filename;
3727 if (parseEscapedString(Filename))
3729 SMLoc IncludeLoc = getLexer().getLoc();
3732 if (getLexer().isNot(AsmToken::EndOfStatement))
3733 return TokError("unexpected token in '.include' directive");
3735 // Attempt to switch the lexer to the included file before consuming the end
3736 // of statement to avoid losing it when we switch.
3737 if (enterIncludeFile(Filename)) {
3738 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3745 /// parseDirectiveIncbin
3746 /// ::= .incbin "filename"
3747 bool AsmParser::parseDirectiveIncbin() {
3748 if (getLexer().isNot(AsmToken::String))
3749 return TokError("expected string in '.incbin' directive");
3751 // Allow the strings to have escaped octal character sequence.
3752 std::string Filename;
3753 if (parseEscapedString(Filename))
3755 SMLoc IncbinLoc = getLexer().getLoc();
3758 if (getLexer().isNot(AsmToken::EndOfStatement))
3759 return TokError("unexpected token in '.incbin' directive");
3761 // Attempt to process the included file.
3762 if (processIncbinFile(Filename)) {
3763 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3770 /// parseDirectiveIf
3771 /// ::= .if expression
3772 /// ::= .ifne expression
3773 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3774 TheCondStack.push_back(TheCondState);
3775 TheCondState.TheCond = AsmCond::IfCond;
3776 if (TheCondState.Ignore) {
3777 eatToEndOfStatement();
3780 if (parseAbsoluteExpression(ExprValue))
3783 if (getLexer().isNot(AsmToken::EndOfStatement))
3784 return TokError("unexpected token in '.if' directive");
3788 TheCondState.CondMet = ExprValue;
3789 TheCondState.Ignore = !TheCondState.CondMet;
3795 /// parseDirectiveIfb
3797 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3798 TheCondStack.push_back(TheCondState);
3799 TheCondState.TheCond = AsmCond::IfCond;
3801 if (TheCondState.Ignore) {
3802 eatToEndOfStatement();
3804 StringRef Str = parseStringToEndOfStatement();
3806 if (getLexer().isNot(AsmToken::EndOfStatement))
3807 return TokError("unexpected token in '.ifb' directive");
3811 TheCondState.CondMet = ExpectBlank == Str.empty();
3812 TheCondState.Ignore = !TheCondState.CondMet;
3818 /// parseDirectiveIfc
3819 /// ::= .ifc string1, string2
3820 /// ::= .ifnc string1, string2
3821 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3822 TheCondStack.push_back(TheCondState);
3823 TheCondState.TheCond = AsmCond::IfCond;
3825 if (TheCondState.Ignore) {
3826 eatToEndOfStatement();
3828 StringRef Str1 = parseStringToComma();
3830 if (getLexer().isNot(AsmToken::Comma))
3831 return TokError("unexpected token in '.ifc' directive");
3835 StringRef Str2 = parseStringToEndOfStatement();
3837 if (getLexer().isNot(AsmToken::EndOfStatement))
3838 return TokError("unexpected token in '.ifc' directive");
3842 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3843 TheCondState.Ignore = !TheCondState.CondMet;
3849 /// parseDirectiveIfeqs
3850 /// ::= .ifeqs string1, string2
3851 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3852 if (Lexer.isNot(AsmToken::String)) {
3853 TokError("expected string parameter for '.ifeqs' directive");
3854 eatToEndOfStatement();
3858 StringRef String1 = getTok().getStringContents();
3861 if (Lexer.isNot(AsmToken::Comma)) {
3862 TokError("expected comma after first string for '.ifeqs' directive");
3863 eatToEndOfStatement();
3869 if (Lexer.isNot(AsmToken::String)) {
3870 TokError("expected string parameter for '.ifeqs' directive");
3871 eatToEndOfStatement();
3875 StringRef String2 = getTok().getStringContents();
3878 TheCondStack.push_back(TheCondState);
3879 TheCondState.TheCond = AsmCond::IfCond;
3880 TheCondState.CondMet = String1 == String2;
3881 TheCondState.Ignore = !TheCondState.CondMet;
3886 /// parseDirectiveIfdef
3887 /// ::= .ifdef symbol
3888 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3890 TheCondStack.push_back(TheCondState);
3891 TheCondState.TheCond = AsmCond::IfCond;
3893 if (TheCondState.Ignore) {
3894 eatToEndOfStatement();
3896 if (parseIdentifier(Name))
3897 return TokError("expected identifier after '.ifdef'");
3901 MCSymbol *Sym = getContext().LookupSymbol(Name);
3904 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3906 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3907 TheCondState.Ignore = !TheCondState.CondMet;
3913 /// parseDirectiveElseIf
3914 /// ::= .elseif expression
3915 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3916 if (TheCondState.TheCond != AsmCond::IfCond &&
3917 TheCondState.TheCond != AsmCond::ElseIfCond)
3918 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3920 TheCondState.TheCond = AsmCond::ElseIfCond;
3922 bool LastIgnoreState = false;
3923 if (!TheCondStack.empty())
3924 LastIgnoreState = TheCondStack.back().Ignore;
3925 if (LastIgnoreState || TheCondState.CondMet) {
3926 TheCondState.Ignore = true;
3927 eatToEndOfStatement();
3930 if (parseAbsoluteExpression(ExprValue))
3933 if (getLexer().isNot(AsmToken::EndOfStatement))
3934 return TokError("unexpected token in '.elseif' directive");
3937 TheCondState.CondMet = ExprValue;
3938 TheCondState.Ignore = !TheCondState.CondMet;
3944 /// parseDirectiveElse
3946 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3947 if (getLexer().isNot(AsmToken::EndOfStatement))
3948 return TokError("unexpected token in '.else' directive");
3952 if (TheCondState.TheCond != AsmCond::IfCond &&
3953 TheCondState.TheCond != AsmCond::ElseIfCond)
3954 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3956 TheCondState.TheCond = AsmCond::ElseCond;
3957 bool LastIgnoreState = false;
3958 if (!TheCondStack.empty())
3959 LastIgnoreState = TheCondStack.back().Ignore;
3960 if (LastIgnoreState || TheCondState.CondMet)
3961 TheCondState.Ignore = true;
3963 TheCondState.Ignore = false;
3968 /// parseDirectiveEnd
3970 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3971 if (getLexer().isNot(AsmToken::EndOfStatement))
3972 return TokError("unexpected token in '.end' directive");
3976 while (Lexer.isNot(AsmToken::Eof))
3982 /// parseDirectiveError
3984 /// ::= .error [string]
3985 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
3986 if (!TheCondStack.empty()) {
3987 if (TheCondStack.back().Ignore) {
3988 eatToEndOfStatement();
3994 return Error(L, ".err encountered");
3996 StringRef Message = ".error directive invoked in source file";
3997 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3998 if (Lexer.isNot(AsmToken::String)) {
3999 TokError(".error argument must be a string");
4000 eatToEndOfStatement();
4004 Message = getTok().getStringContents();
4012 /// parseDirectiveEndIf
4014 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4015 if (getLexer().isNot(AsmToken::EndOfStatement))
4016 return TokError("unexpected token in '.endif' directive");
4020 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4021 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4023 if (!TheCondStack.empty()) {
4024 TheCondState = TheCondStack.back();
4025 TheCondStack.pop_back();
4031 void AsmParser::initializeDirectiveKindMap() {
4032 DirectiveKindMap[".set"] = DK_SET;
4033 DirectiveKindMap[".equ"] = DK_EQU;
4034 DirectiveKindMap[".equiv"] = DK_EQUIV;
4035 DirectiveKindMap[".ascii"] = DK_ASCII;
4036 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4037 DirectiveKindMap[".string"] = DK_STRING;
4038 DirectiveKindMap[".byte"] = DK_BYTE;
4039 DirectiveKindMap[".short"] = DK_SHORT;
4040 DirectiveKindMap[".value"] = DK_VALUE;
4041 DirectiveKindMap[".2byte"] = DK_2BYTE;
4042 DirectiveKindMap[".long"] = DK_LONG;
4043 DirectiveKindMap[".int"] = DK_INT;
4044 DirectiveKindMap[".4byte"] = DK_4BYTE;
4045 DirectiveKindMap[".quad"] = DK_QUAD;
4046 DirectiveKindMap[".8byte"] = DK_8BYTE;
4047 DirectiveKindMap[".octa"] = DK_OCTA;
4048 DirectiveKindMap[".single"] = DK_SINGLE;
4049 DirectiveKindMap[".float"] = DK_FLOAT;
4050 DirectiveKindMap[".double"] = DK_DOUBLE;
4051 DirectiveKindMap[".align"] = DK_ALIGN;
4052 DirectiveKindMap[".align32"] = DK_ALIGN32;
4053 DirectiveKindMap[".balign"] = DK_BALIGN;
4054 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4055 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4056 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4057 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4058 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4059 DirectiveKindMap[".org"] = DK_ORG;
4060 DirectiveKindMap[".fill"] = DK_FILL;
4061 DirectiveKindMap[".zero"] = DK_ZERO;
4062 DirectiveKindMap[".extern"] = DK_EXTERN;
4063 DirectiveKindMap[".globl"] = DK_GLOBL;
4064 DirectiveKindMap[".global"] = DK_GLOBAL;
4065 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4066 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4067 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4068 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4069 DirectiveKindMap[".reference"] = DK_REFERENCE;
4070 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4071 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4072 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4073 DirectiveKindMap[".comm"] = DK_COMM;
4074 DirectiveKindMap[".common"] = DK_COMMON;
4075 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4076 DirectiveKindMap[".abort"] = DK_ABORT;
4077 DirectiveKindMap[".include"] = DK_INCLUDE;
4078 DirectiveKindMap[".incbin"] = DK_INCBIN;
4079 DirectiveKindMap[".code16"] = DK_CODE16;
4080 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4081 DirectiveKindMap[".rept"] = DK_REPT;
4082 DirectiveKindMap[".rep"] = DK_REPT;
4083 DirectiveKindMap[".irp"] = DK_IRP;
4084 DirectiveKindMap[".irpc"] = DK_IRPC;
4085 DirectiveKindMap[".endr"] = DK_ENDR;
4086 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4087 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4088 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4089 DirectiveKindMap[".if"] = DK_IF;
4090 DirectiveKindMap[".ifne"] = DK_IFNE;
4091 DirectiveKindMap[".ifb"] = DK_IFB;
4092 DirectiveKindMap[".ifnb"] = DK_IFNB;
4093 DirectiveKindMap[".ifc"] = DK_IFC;
4094 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4095 DirectiveKindMap[".ifnc"] = DK_IFNC;
4096 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4097 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4098 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4099 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4100 DirectiveKindMap[".else"] = DK_ELSE;
4101 DirectiveKindMap[".end"] = DK_END;
4102 DirectiveKindMap[".endif"] = DK_ENDIF;
4103 DirectiveKindMap[".skip"] = DK_SKIP;
4104 DirectiveKindMap[".space"] = DK_SPACE;
4105 DirectiveKindMap[".file"] = DK_FILE;
4106 DirectiveKindMap[".line"] = DK_LINE;
4107 DirectiveKindMap[".loc"] = DK_LOC;
4108 DirectiveKindMap[".stabs"] = DK_STABS;
4109 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4110 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4111 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4112 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4113 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4114 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4115 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4116 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4117 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4118 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4119 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4120 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4121 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4122 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4123 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4124 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4125 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4126 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4127 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4128 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4129 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4130 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4131 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4132 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4133 DirectiveKindMap[".macro"] = DK_MACRO;
4134 DirectiveKindMap[".endm"] = DK_ENDM;
4135 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4136 DirectiveKindMap[".purgem"] = DK_PURGEM;
4137 DirectiveKindMap[".err"] = DK_ERR;
4138 DirectiveKindMap[".error"] = DK_ERROR;
4141 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4142 AsmToken EndToken, StartToken = getTok();
4144 unsigned NestLevel = 0;
4146 // Check whether we have reached the end of the file.
4147 if (getLexer().is(AsmToken::Eof)) {
4148 Error(DirectiveLoc, "no matching '.endr' in definition");
4152 if (Lexer.is(AsmToken::Identifier) &&
4153 (getTok().getIdentifier() == ".rept")) {
4157 // Otherwise, check whether we have reached the .endr.
4158 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4159 if (NestLevel == 0) {
4160 EndToken = getTok();
4162 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4163 TokError("unexpected token in '.endr' directive");
4171 // Otherwise, scan till the end of the statement.
4172 eatToEndOfStatement();
4175 const char *BodyStart = StartToken.getLoc().getPointer();
4176 const char *BodyEnd = EndToken.getLoc().getPointer();
4177 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4179 // We Are Anonymous.
4180 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4181 return &MacroLikeBodies.back();
4184 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4185 raw_svector_ostream &OS) {
4188 MemoryBuffer *Instantiation =
4189 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4191 // Create the macro instantiation object and add to the current macro
4192 // instantiation stack.
4193 MacroInstantiation *MI = new MacroInstantiation(
4194 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4195 ActiveMacros.push_back(MI);
4197 // Jump to the macro instantiation and prime the lexer.
4198 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4199 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4203 /// parseDirectiveRept
4204 /// ::= .rep | .rept count
4205 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4206 const MCExpr *CountExpr;
4207 SMLoc CountLoc = getTok().getLoc();
4208 if (parseExpression(CountExpr))
4212 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4213 eatToEndOfStatement();
4214 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4218 return Error(CountLoc, "Count is negative");
4220 if (Lexer.isNot(AsmToken::EndOfStatement))
4221 return TokError("unexpected token in '" + Dir + "' directive");
4223 // Eat the end of statement.
4226 // Lex the rept definition.
4227 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4231 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4232 // to hold the macro body with substitutions.
4233 SmallString<256> Buf;
4234 raw_svector_ostream OS(Buf);
4236 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4239 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4244 /// parseDirectiveIrp
4245 /// ::= .irp symbol,values
4246 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4247 MCAsmMacroParameter Parameter;
4249 if (parseIdentifier(Parameter.Name))
4250 return TokError("expected identifier in '.irp' directive");
4252 if (Lexer.isNot(AsmToken::Comma))
4253 return TokError("expected comma in '.irp' directive");
4257 MCAsmMacroArguments A;
4258 if (parseMacroArguments(0, A))
4261 // Eat the end of statement.
4264 // Lex the irp definition.
4265 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4269 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4270 // to hold the macro body with substitutions.
4271 SmallString<256> Buf;
4272 raw_svector_ostream OS(Buf);
4274 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4275 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4279 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4284 /// parseDirectiveIrpc
4285 /// ::= .irpc symbol,values
4286 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4287 MCAsmMacroParameter Parameter;
4289 if (parseIdentifier(Parameter.Name))
4290 return TokError("expected identifier in '.irpc' directive");
4292 if (Lexer.isNot(AsmToken::Comma))
4293 return TokError("expected comma in '.irpc' directive");
4297 MCAsmMacroArguments A;
4298 if (parseMacroArguments(0, A))
4301 if (A.size() != 1 || A.front().size() != 1)
4302 return TokError("unexpected token in '.irpc' directive");
4304 // Eat the end of statement.
4307 // Lex the irpc definition.
4308 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4312 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4313 // to hold the macro body with substitutions.
4314 SmallString<256> Buf;
4315 raw_svector_ostream OS(Buf);
4317 StringRef Values = A.front().front().getString();
4318 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4319 MCAsmMacroArgument Arg;
4320 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4322 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4326 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4331 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4332 if (ActiveMacros.empty())
4333 return TokError("unmatched '.endr' directive");
4335 // The only .repl that should get here are the ones created by
4336 // instantiateMacroLikeBody.
4337 assert(getLexer().is(AsmToken::EndOfStatement));
4343 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4345 const MCExpr *Value;
4346 SMLoc ExprLoc = getLexer().getLoc();
4347 if (parseExpression(Value))
4349 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4351 return Error(ExprLoc, "unexpected expression in _emit");
4352 uint64_t IntValue = MCE->getValue();
4353 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4354 return Error(ExprLoc, "literal value out of range for directive");
4356 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4360 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4361 const MCExpr *Value;
4362 SMLoc ExprLoc = getLexer().getLoc();
4363 if (parseExpression(Value))
4365 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4367 return Error(ExprLoc, "unexpected expression in align");
4368 uint64_t IntValue = MCE->getValue();
4369 if (!isPowerOf2_64(IntValue))
4370 return Error(ExprLoc, "literal value not a power of two greater then zero");
4372 Info.AsmRewrites->push_back(
4373 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4377 // We are comparing pointers, but the pointers are relative to a single string.
4378 // Thus, this should always be deterministic.
4379 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4380 const AsmRewrite *AsmRewriteB) {
4381 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4383 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4386 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4387 // rewrite to the same location. Make sure the SizeDirective rewrite is
4388 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4389 // ensures the sort algorithm is stable.
4390 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4391 AsmRewritePrecedence[AsmRewriteB->Kind])
4394 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4395 AsmRewritePrecedence[AsmRewriteB->Kind])
4397 llvm_unreachable("Unstable rewrite sort.");
4400 bool AsmParser::parseMSInlineAsm(
4401 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4402 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4403 SmallVectorImpl<std::string> &Constraints,
4404 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4405 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4406 SmallVector<void *, 4> InputDecls;
4407 SmallVector<void *, 4> OutputDecls;
4408 SmallVector<bool, 4> InputDeclsAddressOf;
4409 SmallVector<bool, 4> OutputDeclsAddressOf;
4410 SmallVector<std::string, 4> InputConstraints;
4411 SmallVector<std::string, 4> OutputConstraints;
4412 SmallVector<unsigned, 4> ClobberRegs;
4414 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4419 // While we have input, parse each statement.
4420 unsigned InputIdx = 0;
4421 unsigned OutputIdx = 0;
4422 while (getLexer().isNot(AsmToken::Eof)) {
4423 ParseStatementInfo Info(&AsmStrRewrites);
4424 if (parseStatement(Info))
4427 if (Info.ParseError)
4430 if (Info.Opcode == ~0U)
4433 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4435 // Build the list of clobbers, outputs and inputs.
4436 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4437 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4440 if (Operand->isImm())
4443 // Register operand.
4444 if (Operand->isReg() && !Operand->needAddressOf()) {
4445 unsigned NumDefs = Desc.getNumDefs();
4447 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4448 ClobberRegs.push_back(Operand->getReg());
4452 // Expr/Input or Output.
4453 StringRef SymName = Operand->getSymName();
4454 if (SymName.empty())
4457 void *OpDecl = Operand->getOpDecl();
4461 bool isOutput = (i == 1) && Desc.mayStore();
4462 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4465 OutputDecls.push_back(OpDecl);
4466 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4467 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4468 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4470 InputDecls.push_back(OpDecl);
4471 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4472 InputConstraints.push_back(Operand->getConstraint().str());
4473 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4477 // Consider implicit defs to be clobbers. Think of cpuid and push.
4478 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4479 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4480 ClobberRegs.push_back(ImpDefs[I]);
4483 // Set the number of Outputs and Inputs.
4484 NumOutputs = OutputDecls.size();
4485 NumInputs = InputDecls.size();
4487 // Set the unique clobbers.
4488 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4489 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4491 Clobbers.assign(ClobberRegs.size(), std::string());
4492 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4493 raw_string_ostream OS(Clobbers[I]);
4494 IP->printRegName(OS, ClobberRegs[I]);
4497 // Merge the various outputs and inputs. Output are expected first.
4498 if (NumOutputs || NumInputs) {
4499 unsigned NumExprs = NumOutputs + NumInputs;
4500 OpDecls.resize(NumExprs);
4501 Constraints.resize(NumExprs);
4502 for (unsigned i = 0; i < NumOutputs; ++i) {
4503 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4504 Constraints[i] = OutputConstraints[i];
4506 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4507 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4508 Constraints[j] = InputConstraints[i];
4512 // Build the IR assembly string.
4513 std::string AsmStringIR;
4514 raw_string_ostream OS(AsmStringIR);
4515 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4516 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4517 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4518 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4519 E = AsmStrRewrites.end();
4521 AsmRewriteKind Kind = (*I).Kind;
4522 if (Kind == AOK_Delete)
4525 const char *Loc = (*I).Loc.getPointer();
4526 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4528 // Emit everything up to the immediate/expression.
4529 unsigned Len = Loc - AsmStart;
4531 OS << StringRef(AsmStart, Len);
4533 // Skip the original expression.
4534 if (Kind == AOK_Skip) {
4535 AsmStart = Loc + (*I).Len;
4539 unsigned AdditionalSkip = 0;
4540 // Rewrite expressions in $N notation.
4545 OS << "$$" << (*I).Val;
4551 OS << '$' << InputIdx++;
4554 OS << '$' << OutputIdx++;
4556 case AOK_SizeDirective:
4559 case 8: OS << "byte ptr "; break;
4560 case 16: OS << "word ptr "; break;
4561 case 32: OS << "dword ptr "; break;
4562 case 64: OS << "qword ptr "; break;
4563 case 80: OS << "xword ptr "; break;
4564 case 128: OS << "xmmword ptr "; break;
4565 case 256: OS << "ymmword ptr "; break;
4572 unsigned Val = (*I).Val;
4573 OS << ".align " << Val;
4575 // Skip the original immediate.
4576 assert(Val < 10 && "Expected alignment less then 2^10.");
4577 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4580 case AOK_DotOperator:
4581 // Insert the dot if the user omitted it.
4583 if (AsmStringIR.back() != '.')
4589 // Skip the original expression.
4590 AsmStart = Loc + (*I).Len + AdditionalSkip;
4593 // Emit the remainder of the asm string.
4594 if (AsmStart != AsmEnd)
4595 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4597 AsmString = OS.str();
4601 /// \brief Create an MCAsmParser instance.
4602 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4603 MCStreamer &Out, const MCAsmInfo &MAI) {
4604 return new AsmParser(SM, C, Out, MAI);