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/SmallString.h"
16 #include "llvm/ADT/STLExtras.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/MCParser/AsmCond.h"
26 #include "llvm/MC/MCParser/AsmLexer.h"
27 #include "llvm/MC/MCParser/MCAsmParser.h"
28 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/MCTargetAsmParser.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/raw_ostream.h"
47 FatalAssemblerWarnings("fatal-assembler-warnings",
48 cl::desc("Consider warnings as error"));
50 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
54 /// \brief Helper types for tracking macro definitions.
55 typedef std::vector<AsmToken> MCAsmMacroArgument;
56 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
58 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
63 MCAsmMacroParameters Parameters;
66 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
67 Name(N), Body(B), Parameters(P) {}
69 MCAsmMacro(const MCAsmMacro& Other)
70 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
73 /// \brief Helper class for storing information about an active macro
75 struct MacroInstantiation {
76 /// The macro being instantiated.
77 const MCAsmMacro *TheMacro;
79 /// The macro instantiation with substitutions.
80 MemoryBuffer *Instantiation;
82 /// The location of the instantiation.
83 SMLoc InstantiationLoc;
85 /// The buffer where parsing should resume upon instantiation completion.
88 /// The location where parsing should resume upon instantiation completion.
92 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
96 struct ParseStatementInfo {
97 /// \brief The parsed operands from the last parsed statement.
98 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
100 /// \brief The opcode from the last parsed instruction.
103 /// \brief Was there an error parsing the inline assembly?
106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112 ~ParseStatementInfo() {
113 // Free any parsed operands.
114 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
115 delete ParsedOperands[i];
116 ParsedOperands.clear();
120 /// \brief The concrete assembly parser instance.
121 class AsmParser : public MCAsmParser {
122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
128 const MCAsmInfo &MAI;
130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
132 MCAsmParserExtension *PlatformParser;
134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
141 /// \brief maps directive names to handler methods in parser
142 /// extensions. Extensions register themselves in this map by calling
143 /// addDirectiveHandler.
144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
146 /// \brief Map of currently defined macros.
147 StringMap<MCAsmMacro*> MacroMap;
149 /// \brief Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
152 /// \brief List of bodies of anonymous macros.
153 std::deque<MCAsmMacro> MacroLikeBodies;
155 /// Boolean tracking whether macro substitution is enabled.
156 unsigned MacrosEnabledFlag : 1;
158 /// Flag tracking whether any errors have been encountered.
159 unsigned HadError : 1;
161 /// The values from the last parsed cpp hash file line comment if any.
162 StringRef CppHashFilename;
163 int64_t CppHashLineNumber;
166 /// When generating dwarf for assembly source files we need to calculate the
167 /// logical line number based on the last parsed cpp hash file line comment
168 /// and current line. Since this is slow and messes up the SourceMgr's
169 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
170 SMLoc LastQueryIDLoc;
172 unsigned LastQueryLine;
174 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
175 unsigned AssemblerDialect;
177 /// \brief is Darwin compatibility enabled?
180 /// \brief Are we parsing ms-style inline assembly?
181 bool ParsingInlineAsm;
184 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
185 const MCAsmInfo &MAI);
186 virtual ~AsmParser();
188 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
190 virtual void addDirectiveHandler(StringRef Directive,
191 ExtensionDirectiveHandler Handler) {
192 ExtensionDirectiveMap[Directive] = Handler;
196 /// @name MCAsmParser Interface
199 virtual SourceMgr &getSourceManager() { return SrcMgr; }
200 virtual MCAsmLexer &getLexer() { return Lexer; }
201 virtual MCContext &getContext() { return Ctx; }
202 virtual MCStreamer &getStreamer() { return Out; }
203 virtual unsigned getAssemblerDialect() {
204 if (AssemblerDialect == ~0U)
205 return MAI.getAssemblerDialect();
207 return AssemblerDialect;
209 virtual void setAssemblerDialect(unsigned i) {
210 AssemblerDialect = i;
213 virtual bool Warning(SMLoc L, const Twine &Msg,
214 ArrayRef<SMRange> Ranges = None);
215 virtual bool Error(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None);
218 virtual const AsmToken &Lex();
220 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
221 bool isParsingInlineAsm() { return ParsingInlineAsm; }
223 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
224 unsigned &NumOutputs, unsigned &NumInputs,
225 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
226 SmallVectorImpl<std::string> &Constraints,
227 SmallVectorImpl<std::string> &Clobbers,
228 const MCInstrInfo *MII,
229 const MCInstPrinter *IP,
230 MCAsmParserSemaCallback &SI);
232 bool parseExpression(const MCExpr *&Res);
233 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
234 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
235 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
236 virtual bool parseAbsoluteExpression(int64_t &Res);
238 /// \brief Parse an identifier or string (as a quoted identifier)
239 /// and set \p Res to the identifier contents.
240 virtual bool parseIdentifier(StringRef &Res);
241 virtual void eatToEndOfStatement();
243 virtual void checkForValidSection();
248 bool parseStatement(ParseStatementInfo &Info);
249 void eatToEndOfLine();
250 bool parseCppHashLineFilenameComment(const SMLoc &L);
252 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
253 MCAsmMacroParameters Parameters);
254 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
255 const MCAsmMacroParameters &Parameters,
256 const MCAsmMacroArguments &A,
259 /// \brief Are macros enabled in the parser?
260 bool areMacrosEnabled() {return MacrosEnabledFlag;}
262 /// \brief Control a flag in the parser that enables or disables macros.
263 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
265 /// \brief Lookup a previously defined macro.
266 /// \param Name Macro name.
267 /// \returns Pointer to macro. NULL if no such macro was defined.
268 const MCAsmMacro* lookupMacro(StringRef Name);
270 /// \brief Define a new macro with the given name and information.
271 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
273 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
274 void undefineMacro(StringRef Name);
276 /// \brief Are we inside a macro instantiation?
277 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
279 /// \brief Handle entry to macro instantiation.
281 /// \param M The macro.
282 /// \param NameLoc Instantiation location.
283 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
285 /// \brief Handle exit from macro instantiation.
286 void handleMacroExit();
288 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
289 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
290 /// correct delimiter by the method.
291 bool parseMacroArgument(MCAsmMacroArgument &MA,
292 AsmToken::TokenKind &ArgumentDelimiter);
294 /// \brief Parse all macro arguments for a given macro.
295 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
297 void printMacroInstantiations();
298 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
299 ArrayRef<SMRange> Ranges = None) const {
300 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
302 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
304 /// \brief Enter the specified file. This returns true on failure.
305 bool enterIncludeFile(const std::string &Filename);
307 /// \brief Process the specified file for the .incbin directive.
308 /// This returns true on failure.
309 bool processIncbinFile(const std::string &Filename);
311 /// \brief Reset the current lexer position to that given by \p Loc. The
312 /// current token is not set; clients should ensure Lex() is called
315 /// \param InBuffer If not -1, should be the known buffer id that contains the
317 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
319 /// \brief Parse up to the end of statement and a return the contents from the
320 /// current token until the end of the statement; the current token on exit
321 /// will be either the EndOfStatement or EOF.
322 virtual StringRef parseStringToEndOfStatement();
324 /// \brief Parse until the end of a statement or a comma is encountered,
325 /// return the contents from the current token up to the end or comma.
326 StringRef parseStringToComma();
328 bool parseAssignment(StringRef Name, bool allow_redef,
329 bool NoDeadStrip = false);
331 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
332 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
335 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
337 // Generic (target and platform independent) directive parsing.
339 DK_NO_DIRECTIVE, // Placeholder
340 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
341 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
342 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
343 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
344 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
345 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
346 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
347 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
348 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
349 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
350 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
351 DK_ELSEIF, DK_ELSE, DK_ENDIF,
352 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
353 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
354 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
355 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
356 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
357 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
358 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
359 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
360 DK_SLEB128, DK_ULEB128
363 /// \brief Maps directive name --> DirectiveKind enum, for
364 /// directives parsed by this class.
365 StringMap<DirectiveKind> DirectiveKindMap;
367 // ".ascii", ".asciz", ".string"
368 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
369 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
370 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
371 bool parseDirectiveFill(); // ".fill"
372 bool parseDirectiveZero(); // ".zero"
373 // ".set", ".equ", ".equiv"
374 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
375 bool parseDirectiveOrg(); // ".org"
376 // ".align{,32}", ".p2align{,w,l}"
377 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
379 // ".file", ".line", ".loc", ".stabs"
380 bool parseDirectiveFile(SMLoc DirectiveLoc);
381 bool parseDirectiveLine();
382 bool parseDirectiveLoc();
383 bool parseDirectiveStabs();
386 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
387 bool parseDirectiveCFIWindowSave();
388 bool parseDirectiveCFISections();
389 bool parseDirectiveCFIStartProc();
390 bool parseDirectiveCFIEndProc();
391 bool parseDirectiveCFIDefCfaOffset();
392 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIAdjustCfaOffset();
394 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
395 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
398 bool parseDirectiveCFIRememberState();
399 bool parseDirectiveCFIRestoreState();
400 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIEscape();
403 bool parseDirectiveCFISignalFrame();
404 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
407 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
408 bool parseDirectiveEndMacro(StringRef Directive);
409 bool parseDirectiveMacro(SMLoc DirectiveLoc);
410 bool parseDirectiveMacrosOnOff(StringRef Directive);
412 // ".bundle_align_mode"
413 bool parseDirectiveBundleAlignMode();
415 bool parseDirectiveBundleLock();
417 bool parseDirectiveBundleUnlock();
420 bool parseDirectiveSpace(StringRef IDVal);
422 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
423 bool parseDirectiveLEB128(bool Signed);
425 /// \brief Parse a directive like ".globl" which
426 /// accepts a single symbol (which should be a label or an external).
427 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
429 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
431 bool parseDirectiveAbort(); // ".abort"
432 bool parseDirectiveInclude(); // ".include"
433 bool parseDirectiveIncbin(); // ".incbin"
435 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
436 // ".ifb" or ".ifnb", depending on ExpectBlank.
437 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
438 // ".ifc" or ".ifnc", depending on ExpectEqual.
439 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
440 // ".ifdef" or ".ifndef", depending on expect_defined
441 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
442 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
443 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
444 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
445 virtual bool parseEscapedString(std::string &Data);
447 const MCExpr *applyModifierToExpr(const MCExpr *E,
448 MCSymbolRefExpr::VariantKind Variant);
450 // Macro-like directives
451 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
452 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
453 raw_svector_ostream &OS);
454 bool parseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
455 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
456 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
457 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
459 // "_emit" or "__emit"
460 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
464 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
466 void initializeDirectiveKindMap();
472 extern MCAsmParserExtension *createDarwinAsmParser();
473 extern MCAsmParserExtension *createELFAsmParser();
474 extern MCAsmParserExtension *createCOFFAsmParser();
478 enum { DEFAULT_ADDRSPACE = 0 };
480 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
481 const MCAsmInfo &_MAI)
482 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
483 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
484 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
485 ParsingInlineAsm(false) {
486 // Save the old handler.
487 SavedDiagHandler = SrcMgr.getDiagHandler();
488 SavedDiagContext = SrcMgr.getDiagContext();
489 // Set our own handler which calls the saved handler.
490 SrcMgr.setDiagHandler(DiagHandler, this);
491 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
493 // Initialize the platform / file format parser.
495 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
497 if (_MAI.hasMicrosoftFastStdCallMangling()) {
498 PlatformParser = createCOFFAsmParser();
499 PlatformParser->Initialize(*this);
500 } else if (_MAI.hasSubsectionsViaSymbols()) {
501 PlatformParser = createDarwinAsmParser();
502 PlatformParser->Initialize(*this);
505 PlatformParser = createELFAsmParser();
506 PlatformParser->Initialize(*this);
509 initializeDirectiveKindMap();
512 AsmParser::~AsmParser() {
513 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
515 // Destroy any macros.
516 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
519 delete it->getValue();
521 delete PlatformParser;
524 void AsmParser::printMacroInstantiations() {
525 // Print the active macro instantiation stack.
526 for (std::vector<MacroInstantiation *>::const_reverse_iterator
527 it = ActiveMacros.rbegin(),
528 ie = ActiveMacros.rend();
530 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
531 "while in macro instantiation");
534 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
535 if (FatalAssemblerWarnings)
536 return Error(L, Msg, Ranges);
537 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
538 printMacroInstantiations();
542 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
544 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
545 printMacroInstantiations();
549 bool AsmParser::enterIncludeFile(const std::string &Filename) {
550 std::string IncludedFile;
551 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
557 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
562 /// Process the specified .incbin file by searching for it in the include paths
563 /// then just emitting the byte contents of the file to the streamer. This
564 /// returns true on failure.
565 bool AsmParser::processIncbinFile(const std::string &Filename) {
566 std::string IncludedFile;
567 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
571 // Pick up the bytes from the file and emit them.
572 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
576 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
577 if (InBuffer != -1) {
578 CurBuffer = InBuffer;
580 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
582 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
585 const AsmToken &AsmParser::Lex() {
586 const AsmToken *tok = &Lexer.Lex();
588 if (tok->is(AsmToken::Eof)) {
589 // If this is the end of an included file, pop the parent file off the
591 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
592 if (ParentIncludeLoc != SMLoc()) {
593 jumpToLoc(ParentIncludeLoc);
598 if (tok->is(AsmToken::Error))
599 Error(Lexer.getErrLoc(), Lexer.getErr());
604 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
605 // Create the initial section, if requested.
606 if (!NoInitialTextSection)
613 AsmCond StartingCondState = TheCondState;
615 // If we are generating dwarf for assembly source files save the initial text
616 // section and generate a .file directive.
617 if (getContext().getGenDwarfForAssembly()) {
618 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
619 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
620 getStreamer().EmitLabel(SectionStartSym);
621 getContext().setGenDwarfSectionStartSym(SectionStartSym);
622 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
624 getContext().getMainFileName());
627 // While we have input, parse each statement.
628 while (Lexer.isNot(AsmToken::Eof)) {
629 ParseStatementInfo Info;
630 if (!parseStatement(Info))
633 // We had an error, validate that one was emitted and recover by skipping to
635 assert(HadError && "Parse statement returned an error, but none emitted!");
636 eatToEndOfStatement();
639 if (TheCondState.TheCond != StartingCondState.TheCond ||
640 TheCondState.Ignore != StartingCondState.Ignore)
641 return TokError("unmatched .ifs or .elses");
643 // Check to see there are no empty DwarfFile slots.
644 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
645 getContext().getMCDwarfFiles();
646 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
647 if (!MCDwarfFiles[i])
648 TokError("unassigned file number: " + Twine(i) + " for .file directives");
651 // Check to see that all assembler local symbols were actually defined.
652 // Targets that don't do subsections via symbols may not want this, though,
653 // so conservatively exclude them. Only do this if we're finalizing, though,
654 // as otherwise we won't necessarilly have seen everything yet.
655 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
656 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
657 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
660 MCSymbol *Sym = i->getValue();
661 // Variable symbols may not be marked as defined, so check those
662 // explicitly. If we know it's a variable, we have a definition for
663 // the purposes of this check.
664 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
665 // FIXME: We would really like to refer back to where the symbol was
666 // first referenced for a source location. We need to add something
667 // to track that. Currently, we just point to the end of the file.
669 getLexer().getLoc(), SourceMgr::DK_Error,
670 "assembler local symbol '" + Sym->getName() + "' not defined");
674 // Finalize the output stream if there are no errors and if the client wants
676 if (!HadError && !NoFinalize)
682 void AsmParser::checkForValidSection() {
683 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
684 TokError("expected section directive before assembly directive");
685 Out.InitToTextSection();
689 /// \brief Throw away the rest of the line for testing purposes.
690 void AsmParser::eatToEndOfStatement() {
691 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
695 if (Lexer.is(AsmToken::EndOfStatement))
699 StringRef AsmParser::parseStringToEndOfStatement() {
700 const char *Start = getTok().getLoc().getPointer();
702 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
705 const char *End = getTok().getLoc().getPointer();
706 return StringRef(Start, End - Start);
709 StringRef AsmParser::parseStringToComma() {
710 const char *Start = getTok().getLoc().getPointer();
712 while (Lexer.isNot(AsmToken::EndOfStatement) &&
713 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
716 const char *End = getTok().getLoc().getPointer();
717 return StringRef(Start, End - Start);
720 /// \brief Parse a paren expression and return it.
721 /// NOTE: This assumes the leading '(' has already been consumed.
723 /// parenexpr ::= expr)
725 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
726 if (parseExpression(Res))
728 if (Lexer.isNot(AsmToken::RParen))
729 return TokError("expected ')' in parentheses expression");
730 EndLoc = Lexer.getTok().getEndLoc();
735 /// \brief Parse a bracket expression and return it.
736 /// NOTE: This assumes the leading '[' has already been consumed.
738 /// bracketexpr ::= expr]
740 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
741 if (parseExpression(Res))
743 if (Lexer.isNot(AsmToken::RBrac))
744 return TokError("expected ']' in brackets expression");
745 EndLoc = Lexer.getTok().getEndLoc();
750 /// \brief Parse a primary expression and return it.
751 /// primaryexpr ::= (parenexpr
752 /// primaryexpr ::= symbol
753 /// primaryexpr ::= number
754 /// primaryexpr ::= '.'
755 /// primaryexpr ::= ~,+,- primaryexpr
756 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
757 SMLoc FirstTokenLoc = getLexer().getLoc();
758 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
759 switch (FirstTokenKind) {
761 return TokError("unknown token in expression");
762 // If we have an error assume that we've already handled it.
763 case AsmToken::Error:
765 case AsmToken::Exclaim:
766 Lex(); // Eat the operator.
767 if (parsePrimaryExpr(Res, EndLoc))
769 Res = MCUnaryExpr::CreateLNot(Res, getContext());
771 case AsmToken::Dollar:
772 case AsmToken::String:
773 case AsmToken::Identifier: {
774 StringRef Identifier;
775 if (parseIdentifier(Identifier)) {
776 if (FirstTokenKind == AsmToken::Dollar) {
777 if (Lexer.getMAI().getDollarIsPC()) {
778 // This is a '$' reference, which references the current PC. Emit a
779 // temporary label to the streamer and refer to it.
780 MCSymbol *Sym = Ctx.CreateTempSymbol();
782 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
783 EndLoc = FirstTokenLoc;
786 return Error(FirstTokenLoc, "invalid token in expression");
791 EndLoc = SMLoc::getFromPointer(Identifier.end());
793 // This is a symbol reference.
794 std::pair<StringRef, StringRef> Split = Identifier.split('@');
795 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
797 // Lookup the symbol variant if used.
798 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
799 if (Split.first.size() != Identifier.size()) {
800 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
801 if (Variant == MCSymbolRefExpr::VK_Invalid) {
802 Variant = MCSymbolRefExpr::VK_None;
803 return TokError("invalid variant '" + Split.second + "'");
807 // If this is an absolute variable reference, substitute it now to preserve
808 // semantics in the face of reassignment.
809 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
811 return Error(EndLoc, "unexpected modifier on variable reference");
813 Res = Sym->getVariableValue();
817 // Otherwise create a symbol ref.
818 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
821 case AsmToken::Integer: {
822 SMLoc Loc = getTok().getLoc();
823 int64_t IntVal = getTok().getIntVal();
824 Res = MCConstantExpr::Create(IntVal, getContext());
825 EndLoc = Lexer.getTok().getEndLoc();
827 // Look for 'b' or 'f' following an Integer as a directional label
828 if (Lexer.getKind() == AsmToken::Identifier) {
829 StringRef IDVal = getTok().getString();
830 // Lookup the symbol variant if used.
831 std::pair<StringRef, StringRef> Split = IDVal.split('@');
832 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
833 if (Split.first.size() != IDVal.size()) {
834 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
835 if (Variant == MCSymbolRefExpr::VK_Invalid) {
836 Variant = MCSymbolRefExpr::VK_None;
837 return TokError("invalid variant '" + Split.second + "'");
841 if (IDVal == "f" || IDVal == "b") {
843 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
844 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
845 if (IDVal == "b" && Sym->isUndefined())
846 return Error(Loc, "invalid reference to undefined symbol");
847 EndLoc = Lexer.getTok().getEndLoc();
848 Lex(); // Eat identifier.
853 case AsmToken::Real: {
854 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
855 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
856 Res = MCConstantExpr::Create(IntVal, getContext());
857 EndLoc = Lexer.getTok().getEndLoc();
861 case AsmToken::Dot: {
862 // This is a '.' reference, which references the current PC. Emit a
863 // temporary label to the streamer and refer to it.
864 MCSymbol *Sym = Ctx.CreateTempSymbol();
866 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
867 EndLoc = Lexer.getTok().getEndLoc();
868 Lex(); // Eat identifier.
871 case AsmToken::LParen:
872 Lex(); // Eat the '('.
873 return parseParenExpr(Res, EndLoc);
874 case AsmToken::LBrac:
875 if (!PlatformParser->HasBracketExpressions())
876 return TokError("brackets expression not supported on this target");
877 Lex(); // Eat the '['.
878 return parseBracketExpr(Res, EndLoc);
879 case AsmToken::Minus:
880 Lex(); // Eat the operator.
881 if (parsePrimaryExpr(Res, EndLoc))
883 Res = MCUnaryExpr::CreateMinus(Res, getContext());
886 Lex(); // Eat the operator.
887 if (parsePrimaryExpr(Res, EndLoc))
889 Res = MCUnaryExpr::CreatePlus(Res, getContext());
891 case AsmToken::Tilde:
892 Lex(); // Eat the operator.
893 if (parsePrimaryExpr(Res, EndLoc))
895 Res = MCUnaryExpr::CreateNot(Res, getContext());
900 bool AsmParser::parseExpression(const MCExpr *&Res) {
902 return parseExpression(Res, EndLoc);
906 AsmParser::applyModifierToExpr(const MCExpr *E,
907 MCSymbolRefExpr::VariantKind Variant) {
908 // Ask the target implementation about this expression first.
909 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
912 // Recurse over the given expression, rebuilding it to apply the given variant
913 // if there is exactly one symbol.
914 switch (E->getKind()) {
916 case MCExpr::Constant:
919 case MCExpr::SymbolRef: {
920 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
922 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
923 TokError("invalid variant on expression '" + getTok().getIdentifier() +
924 "' (already modified)");
928 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
931 case MCExpr::Unary: {
932 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
933 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
936 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
939 case MCExpr::Binary: {
940 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
941 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
942 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
952 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
956 llvm_unreachable("Invalid expression kind!");
959 /// \brief Parse an expression and return it.
961 /// expr ::= expr &&,|| expr -> lowest.
962 /// expr ::= expr |,^,&,! expr
963 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
964 /// expr ::= expr <<,>> expr
965 /// expr ::= expr +,- expr
966 /// expr ::= expr *,/,% expr -> highest.
967 /// expr ::= primaryexpr
969 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
970 // Parse the expression.
972 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
975 // As a special case, we support 'a op b @ modifier' by rewriting the
976 // expression to include the modifier. This is inefficient, but in general we
977 // expect users to use 'a@modifier op b'.
978 if (Lexer.getKind() == AsmToken::At) {
981 if (Lexer.isNot(AsmToken::Identifier))
982 return TokError("unexpected symbol modifier following '@'");
984 MCSymbolRefExpr::VariantKind Variant =
985 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
986 if (Variant == MCSymbolRefExpr::VK_Invalid)
987 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
989 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
991 return TokError("invalid modifier '" + getTok().getIdentifier() +
992 "' (no symbols present)");
999 // Try to constant fold it up front, if possible.
1001 if (Res->EvaluateAsAbsolute(Value))
1002 Res = MCConstantExpr::Create(Value, getContext());
1007 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1009 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1012 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1015 SMLoc StartLoc = Lexer.getLoc();
1016 if (parseExpression(Expr))
1019 if (!Expr->EvaluateAsAbsolute(Res))
1020 return Error(StartLoc, "expected absolute expression");
1025 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1026 MCBinaryExpr::Opcode &Kind) {
1029 return 0; // not a binop.
1031 // Lowest Precedence: &&, ||
1032 case AsmToken::AmpAmp:
1033 Kind = MCBinaryExpr::LAnd;
1035 case AsmToken::PipePipe:
1036 Kind = MCBinaryExpr::LOr;
1039 // Low Precedence: |, &, ^
1041 // FIXME: gas seems to support '!' as an infix operator?
1042 case AsmToken::Pipe:
1043 Kind = MCBinaryExpr::Or;
1045 case AsmToken::Caret:
1046 Kind = MCBinaryExpr::Xor;
1049 Kind = MCBinaryExpr::And;
1052 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1053 case AsmToken::EqualEqual:
1054 Kind = MCBinaryExpr::EQ;
1056 case AsmToken::ExclaimEqual:
1057 case AsmToken::LessGreater:
1058 Kind = MCBinaryExpr::NE;
1060 case AsmToken::Less:
1061 Kind = MCBinaryExpr::LT;
1063 case AsmToken::LessEqual:
1064 Kind = MCBinaryExpr::LTE;
1066 case AsmToken::Greater:
1067 Kind = MCBinaryExpr::GT;
1069 case AsmToken::GreaterEqual:
1070 Kind = MCBinaryExpr::GTE;
1073 // Intermediate Precedence: <<, >>
1074 case AsmToken::LessLess:
1075 Kind = MCBinaryExpr::Shl;
1077 case AsmToken::GreaterGreater:
1078 Kind = MCBinaryExpr::Shr;
1081 // High Intermediate Precedence: +, -
1082 case AsmToken::Plus:
1083 Kind = MCBinaryExpr::Add;
1085 case AsmToken::Minus:
1086 Kind = MCBinaryExpr::Sub;
1089 // Highest Precedence: *, /, %
1090 case AsmToken::Star:
1091 Kind = MCBinaryExpr::Mul;
1093 case AsmToken::Slash:
1094 Kind = MCBinaryExpr::Div;
1096 case AsmToken::Percent:
1097 Kind = MCBinaryExpr::Mod;
1102 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1103 /// Res contains the LHS of the expression on input.
1104 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1107 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1108 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1110 // If the next token is lower precedence than we are allowed to eat, return
1111 // successfully with what we ate already.
1112 if (TokPrec < Precedence)
1117 // Eat the next primary expression.
1119 if (parsePrimaryExpr(RHS, EndLoc))
1122 // If BinOp binds less tightly with RHS than the operator after RHS, let
1123 // the pending operator take RHS as its LHS.
1124 MCBinaryExpr::Opcode Dummy;
1125 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1126 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1129 // Merge LHS and RHS according to operator.
1130 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1135 /// ::= EndOfStatement
1136 /// ::= Label* Directive ...Operands... EndOfStatement
1137 /// ::= Label* Identifier OperandList* EndOfStatement
1138 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1139 if (Lexer.is(AsmToken::EndOfStatement)) {
1145 // Statements always start with an identifier or are a full line comment.
1146 AsmToken ID = getTok();
1147 SMLoc IDLoc = ID.getLoc();
1149 int64_t LocalLabelVal = -1;
1150 // A full line comment is a '#' as the first token.
1151 if (Lexer.is(AsmToken::Hash))
1152 return parseCppHashLineFilenameComment(IDLoc);
1154 // Allow an integer followed by a ':' as a directional local label.
1155 if (Lexer.is(AsmToken::Integer)) {
1156 LocalLabelVal = getTok().getIntVal();
1157 if (LocalLabelVal < 0) {
1158 if (!TheCondState.Ignore)
1159 return TokError("unexpected token at start of statement");
1162 IDVal = getTok().getString();
1163 Lex(); // Consume the integer token to be used as an identifier token.
1164 if (Lexer.getKind() != AsmToken::Colon) {
1165 if (!TheCondState.Ignore)
1166 return TokError("unexpected token at start of statement");
1169 } else if (Lexer.is(AsmToken::Dot)) {
1170 // Treat '.' as a valid identifier in this context.
1173 } else if (parseIdentifier(IDVal)) {
1174 if (!TheCondState.Ignore)
1175 return TokError("unexpected token at start of statement");
1179 // Handle conditional assembly here before checking for skipping. We
1180 // have to do this so that .endif isn't skipped in a ".if 0" block for
1182 StringMap<DirectiveKind>::const_iterator DirKindIt =
1183 DirectiveKindMap.find(IDVal);
1184 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1186 : DirKindIt->getValue();
1191 return parseDirectiveIf(IDLoc);
1193 return parseDirectiveIfb(IDLoc, true);
1195 return parseDirectiveIfb(IDLoc, false);
1197 return parseDirectiveIfc(IDLoc, true);
1199 return parseDirectiveIfc(IDLoc, false);
1201 return parseDirectiveIfdef(IDLoc, true);
1204 return parseDirectiveIfdef(IDLoc, false);
1206 return parseDirectiveElseIf(IDLoc);
1208 return parseDirectiveElse(IDLoc);
1210 return parseDirectiveEndIf(IDLoc);
1213 // Ignore the statement if in the middle of inactive conditional
1215 if (TheCondState.Ignore) {
1216 eatToEndOfStatement();
1220 // FIXME: Recurse on local labels?
1222 // See what kind of statement we have.
1223 switch (Lexer.getKind()) {
1224 case AsmToken::Colon: {
1225 checkForValidSection();
1227 // identifier ':' -> Label.
1230 // Diagnose attempt to use '.' as a label.
1232 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1234 // Diagnose attempt to use a variable as a label.
1236 // FIXME: Diagnostics. Note the location of the definition as a label.
1237 // FIXME: This doesn't diagnose assignment to a symbol which has been
1238 // implicitly marked as external.
1240 if (LocalLabelVal == -1)
1241 Sym = getContext().GetOrCreateSymbol(IDVal);
1243 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1244 if (!Sym->isUndefined() || Sym->isVariable())
1245 return Error(IDLoc, "invalid symbol redefinition");
1248 if (!ParsingInlineAsm)
1251 // If we are generating dwarf for assembly source files then gather the
1252 // info to make a dwarf label entry for this label if needed.
1253 if (getContext().getGenDwarfForAssembly())
1254 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1257 // Consume any end of statement token, if present, to avoid spurious
1258 // AddBlankLine calls().
1259 if (Lexer.is(AsmToken::EndOfStatement)) {
1261 if (Lexer.is(AsmToken::Eof))
1268 case AsmToken::Equal:
1269 // identifier '=' ... -> assignment statement
1272 return parseAssignment(IDVal, true);
1274 default: // Normal instruction or directive.
1278 // If macros are enabled, check to see if this is a macro instantiation.
1279 if (areMacrosEnabled())
1280 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1281 return handleMacroEntry(M, IDLoc);
1284 // Otherwise, we have a normal instruction or directive.
1286 // Directives start with "."
1287 if (IDVal[0] == '.' && IDVal != ".") {
1288 // There are several entities interested in parsing directives:
1290 // 1. The target-specific assembly parser. Some directives are target
1291 // specific or may potentially behave differently on certain targets.
1292 // 2. Asm parser extensions. For example, platform-specific parsers
1293 // (like the ELF parser) register themselves as extensions.
1294 // 3. The generic directive parser implemented by this class. These are
1295 // all the directives that behave in a target and platform independent
1296 // manner, or at least have a default behavior that's shared between
1297 // all targets and platforms.
1299 // First query the target-specific parser. It will return 'true' if it
1300 // isn't interested in this directive.
1301 if (!getTargetParser().ParseDirective(ID))
1304 // Next, check the extention directive map to see if any extension has
1305 // registered itself to parse this directive.
1306 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1307 ExtensionDirectiveMap.lookup(IDVal);
1309 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1311 // Finally, if no one else is interested in this directive, it must be
1312 // generic and familiar to this class.
1318 return parseDirectiveSet(IDVal, true);
1320 return parseDirectiveSet(IDVal, false);
1322 return parseDirectiveAscii(IDVal, false);
1325 return parseDirectiveAscii(IDVal, true);
1327 return parseDirectiveValue(1);
1331 return parseDirectiveValue(2);
1335 return parseDirectiveValue(4);
1338 return parseDirectiveValue(8);
1341 return parseDirectiveRealValue(APFloat::IEEEsingle);
1343 return parseDirectiveRealValue(APFloat::IEEEdouble);
1345 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1346 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1349 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1350 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1353 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1355 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1357 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1359 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1361 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1363 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1365 return parseDirectiveOrg();
1367 return parseDirectiveFill();
1369 return parseDirectiveZero();
1371 eatToEndOfStatement(); // .extern is the default, ignore it.
1375 return parseDirectiveSymbolAttribute(MCSA_Global);
1376 case DK_LAZY_REFERENCE:
1377 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1378 case DK_NO_DEAD_STRIP:
1379 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1380 case DK_SYMBOL_RESOLVER:
1381 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1382 case DK_PRIVATE_EXTERN:
1383 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1385 return parseDirectiveSymbolAttribute(MCSA_Reference);
1386 case DK_WEAK_DEFINITION:
1387 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1388 case DK_WEAK_REFERENCE:
1389 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1390 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1391 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1394 return parseDirectiveComm(/*IsLocal=*/false);
1396 return parseDirectiveComm(/*IsLocal=*/true);
1398 return parseDirectiveAbort();
1400 return parseDirectiveInclude();
1402 return parseDirectiveIncbin();
1405 return TokError(Twine(IDVal) + " not supported yet");
1407 return parseDirectiveRept(IDLoc);
1409 return parseDirectiveIrp(IDLoc);
1411 return parseDirectiveIrpc(IDLoc);
1413 return parseDirectiveEndr(IDLoc);
1414 case DK_BUNDLE_ALIGN_MODE:
1415 return parseDirectiveBundleAlignMode();
1416 case DK_BUNDLE_LOCK:
1417 return parseDirectiveBundleLock();
1418 case DK_BUNDLE_UNLOCK:
1419 return parseDirectiveBundleUnlock();
1421 return parseDirectiveLEB128(true);
1423 return parseDirectiveLEB128(false);
1426 return parseDirectiveSpace(IDVal);
1428 return parseDirectiveFile(IDLoc);
1430 return parseDirectiveLine();
1432 return parseDirectiveLoc();
1434 return parseDirectiveStabs();
1435 case DK_CFI_SECTIONS:
1436 return parseDirectiveCFISections();
1437 case DK_CFI_STARTPROC:
1438 return parseDirectiveCFIStartProc();
1439 case DK_CFI_ENDPROC:
1440 return parseDirectiveCFIEndProc();
1441 case DK_CFI_DEF_CFA:
1442 return parseDirectiveCFIDefCfa(IDLoc);
1443 case DK_CFI_DEF_CFA_OFFSET:
1444 return parseDirectiveCFIDefCfaOffset();
1445 case DK_CFI_ADJUST_CFA_OFFSET:
1446 return parseDirectiveCFIAdjustCfaOffset();
1447 case DK_CFI_DEF_CFA_REGISTER:
1448 return parseDirectiveCFIDefCfaRegister(IDLoc);
1450 return parseDirectiveCFIOffset(IDLoc);
1451 case DK_CFI_REL_OFFSET:
1452 return parseDirectiveCFIRelOffset(IDLoc);
1453 case DK_CFI_PERSONALITY:
1454 return parseDirectiveCFIPersonalityOrLsda(true);
1456 return parseDirectiveCFIPersonalityOrLsda(false);
1457 case DK_CFI_REMEMBER_STATE:
1458 return parseDirectiveCFIRememberState();
1459 case DK_CFI_RESTORE_STATE:
1460 return parseDirectiveCFIRestoreState();
1461 case DK_CFI_SAME_VALUE:
1462 return parseDirectiveCFISameValue(IDLoc);
1463 case DK_CFI_RESTORE:
1464 return parseDirectiveCFIRestore(IDLoc);
1466 return parseDirectiveCFIEscape();
1467 case DK_CFI_SIGNAL_FRAME:
1468 return parseDirectiveCFISignalFrame();
1469 case DK_CFI_UNDEFINED:
1470 return parseDirectiveCFIUndefined(IDLoc);
1471 case DK_CFI_REGISTER:
1472 return parseDirectiveCFIRegister(IDLoc);
1473 case DK_CFI_WINDOW_SAVE:
1474 return parseDirectiveCFIWindowSave();
1477 return parseDirectiveMacrosOnOff(IDVal);
1479 return parseDirectiveMacro(IDLoc);
1482 return parseDirectiveEndMacro(IDVal);
1484 return parseDirectivePurgeMacro(IDLoc);
1487 return Error(IDLoc, "unknown directive");
1490 // __asm _emit or __asm __emit
1491 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1492 IDVal == "_EMIT" || IDVal == "__EMIT"))
1493 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1496 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1497 return parseDirectiveMSAlign(IDLoc, Info);
1499 checkForValidSection();
1501 // Canonicalize the opcode to lower case.
1502 std::string OpcodeStr = IDVal.lower();
1503 ParseInstructionInfo IInfo(Info.AsmRewrites);
1504 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1505 Info.ParsedOperands);
1506 Info.ParseError = HadError;
1508 // Dump the parsed representation, if requested.
1509 if (getShowParsedOperands()) {
1510 SmallString<256> Str;
1511 raw_svector_ostream OS(Str);
1512 OS << "parsed instruction: [";
1513 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1516 Info.ParsedOperands[i]->print(OS);
1520 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1523 // If we are generating dwarf for assembly source files and the current
1524 // section is the initial text section then generate a .loc directive for
1526 if (!HadError && getContext().getGenDwarfForAssembly() &&
1527 getContext().getGenDwarfSection() ==
1528 getStreamer().getCurrentSection().first) {
1530 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1532 // If we previously parsed a cpp hash file line comment then make sure the
1533 // current Dwarf File is for the CppHashFilename if not then emit the
1534 // Dwarf File table for it and adjust the line number for the .loc.
1535 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1536 getContext().getMCDwarfFiles();
1537 if (CppHashFilename.size() != 0) {
1538 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1540 getStreamer().EmitDwarfFileDirective(
1541 getContext().nextGenDwarfFileNumber(), StringRef(),
1544 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1545 // cache with the different Loc from the call above we save the last
1546 // info we queried here with SrcMgr.FindLineNumber().
1547 unsigned CppHashLocLineNo;
1548 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1549 CppHashLocLineNo = LastQueryLine;
1551 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1552 LastQueryLine = CppHashLocLineNo;
1553 LastQueryIDLoc = CppHashLoc;
1554 LastQueryBuffer = CppHashBuf;
1556 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1559 getStreamer().EmitDwarfLocDirective(
1560 getContext().getGenDwarfFileNumber(), Line, 0,
1561 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1565 // If parsing succeeded, match the instruction.
1568 HadError = getTargetParser().MatchAndEmitInstruction(
1569 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1573 // Don't skip the rest of the line, the instruction parser is responsible for
1578 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1579 /// since they may not be able to be tokenized to get to the end of line token.
1580 void AsmParser::eatToEndOfLine() {
1581 if (!Lexer.is(AsmToken::EndOfStatement))
1582 Lexer.LexUntilEndOfLine();
1587 /// parseCppHashLineFilenameComment as this:
1588 /// ::= # number "filename"
1589 /// or just as a full line comment if it doesn't have a number and a string.
1590 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1591 Lex(); // Eat the hash token.
1593 if (getLexer().isNot(AsmToken::Integer)) {
1594 // Consume the line since in cases it is not a well-formed line directive,
1595 // as if were simply a full line comment.
1600 int64_t LineNumber = getTok().getIntVal();
1603 if (getLexer().isNot(AsmToken::String)) {
1608 StringRef Filename = getTok().getString();
1609 // Get rid of the enclosing quotes.
1610 Filename = Filename.substr(1, Filename.size() - 2);
1612 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1614 CppHashFilename = Filename;
1615 CppHashLineNumber = LineNumber;
1616 CppHashBuf = CurBuffer;
1618 // Ignore any trailing characters, they're just comment.
1623 /// \brief will use the last parsed cpp hash line filename comment
1624 /// for the Filename and LineNo if any in the diagnostic.
1625 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1626 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1627 raw_ostream &OS = errs();
1629 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1630 const SMLoc &DiagLoc = Diag.getLoc();
1631 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1632 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1634 // Like SourceMgr::printMessage() we need to print the include stack if any
1635 // before printing the message.
1636 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1637 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1638 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1639 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1642 // If we have not parsed a cpp hash line filename comment or the source
1643 // manager changed or buffer changed (like in a nested include) then just
1644 // print the normal diagnostic using its Filename and LineNo.
1645 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1646 DiagBuf != CppHashBuf) {
1647 if (Parser->SavedDiagHandler)
1648 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1654 // Use the CppHashFilename and calculate a line number based on the
1655 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1657 const std::string &Filename = Parser->CppHashFilename;
1659 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1660 int CppHashLocLineNo =
1661 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1663 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1665 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1666 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1667 Diag.getLineContents(), Diag.getRanges());
1669 if (Parser->SavedDiagHandler)
1670 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1672 NewDiag.print(0, OS);
1675 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1676 // difference being that that function accepts '@' as part of identifiers and
1677 // we can't do that. AsmLexer.cpp should probably be changed to handle
1678 // '@' as a special case when needed.
1679 static bool isIdentifierChar(char c) {
1680 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1684 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1685 const MCAsmMacroParameters &Parameters,
1686 const MCAsmMacroArguments &A, const SMLoc &L) {
1687 unsigned NParameters = Parameters.size();
1688 if (NParameters != 0 && NParameters != A.size())
1689 return Error(L, "Wrong number of arguments");
1691 // A macro without parameters is handled differently on Darwin:
1692 // gas accepts no arguments and does no substitutions
1693 while (!Body.empty()) {
1694 // Scan for the next substitution.
1695 std::size_t End = Body.size(), Pos = 0;
1696 for (; Pos != End; ++Pos) {
1697 // Check for a substitution or escape.
1699 // This macro has no parameters, look for $0, $1, etc.
1700 if (Body[Pos] != '$' || Pos + 1 == End)
1703 char Next = Body[Pos + 1];
1704 if (Next == '$' || Next == 'n' ||
1705 isdigit(static_cast<unsigned char>(Next)))
1708 // This macro has parameters, look for \foo, \bar, etc.
1709 if (Body[Pos] == '\\' && Pos + 1 != End)
1715 OS << Body.slice(0, Pos);
1717 // Check if we reached the end.
1722 switch (Body[Pos + 1]) {
1728 // $n => number of arguments
1733 // $[0-9] => argument
1735 // Missing arguments are ignored.
1736 unsigned Index = Body[Pos + 1] - '0';
1737 if (Index >= A.size())
1740 // Otherwise substitute with the token values, with spaces eliminated.
1741 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1742 ie = A[Index].end();
1744 OS << it->getString();
1750 unsigned I = Pos + 1;
1751 while (isIdentifierChar(Body[I]) && I + 1 != End)
1754 const char *Begin = Body.data() + Pos + 1;
1755 StringRef Argument(Begin, I - (Pos + 1));
1757 for (; Index < NParameters; ++Index)
1758 if (Parameters[Index].first == Argument)
1761 if (Index == NParameters) {
1762 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1765 OS << '\\' << Argument;
1769 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1770 ie = A[Index].end();
1772 if (it->getKind() == AsmToken::String)
1773 OS << it->getStringContents();
1775 OS << it->getString();
1777 Pos += 1 + Argument.size();
1780 // Update the scan point.
1781 Body = Body.substr(Pos);
1787 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1788 SMLoc EL, MemoryBuffer *I)
1789 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1792 static bool isOperator(AsmToken::TokenKind kind) {
1796 case AsmToken::Plus:
1797 case AsmToken::Minus:
1798 case AsmToken::Tilde:
1799 case AsmToken::Slash:
1800 case AsmToken::Star:
1802 case AsmToken::Equal:
1803 case AsmToken::EqualEqual:
1804 case AsmToken::Pipe:
1805 case AsmToken::PipePipe:
1806 case AsmToken::Caret:
1808 case AsmToken::AmpAmp:
1809 case AsmToken::Exclaim:
1810 case AsmToken::ExclaimEqual:
1811 case AsmToken::Percent:
1812 case AsmToken::Less:
1813 case AsmToken::LessEqual:
1814 case AsmToken::LessLess:
1815 case AsmToken::LessGreater:
1816 case AsmToken::Greater:
1817 case AsmToken::GreaterEqual:
1818 case AsmToken::GreaterGreater:
1823 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA,
1824 AsmToken::TokenKind &ArgumentDelimiter) {
1825 unsigned ParenLevel = 0;
1826 unsigned AddTokens = 0;
1828 // gas accepts arguments separated by whitespace, except on Darwin
1830 Lexer.setSkipSpace(false);
1833 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1834 Lexer.setSkipSpace(true);
1835 return TokError("unexpected token in macro instantiation");
1838 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1839 // Spaces and commas cannot be mixed to delimit parameters
1840 if (ArgumentDelimiter == AsmToken::Eof)
1841 ArgumentDelimiter = AsmToken::Comma;
1842 else if (ArgumentDelimiter != AsmToken::Comma) {
1843 Lexer.setSkipSpace(true);
1844 return TokError("expected ' ' for macro argument separator");
1849 if (Lexer.is(AsmToken::Space)) {
1850 Lex(); // Eat spaces
1852 // Spaces can delimit parameters, but could also be part an expression.
1853 // If the token after a space is an operator, add the token and the next
1854 // one into this argument
1855 if (ArgumentDelimiter == AsmToken::Space ||
1856 ArgumentDelimiter == AsmToken::Eof) {
1857 if (isOperator(Lexer.getKind())) {
1858 // Check to see whether the token is used as an operator,
1859 // or part of an identifier
1860 const char *NextChar = getTok().getEndLoc().getPointer();
1861 if (*NextChar == ' ')
1865 if (!AddTokens && ParenLevel == 0) {
1866 if (ArgumentDelimiter == AsmToken::Eof &&
1867 !isOperator(Lexer.getKind()))
1868 ArgumentDelimiter = AsmToken::Space;
1874 // handleMacroEntry relies on not advancing the lexer here
1875 // to be able to fill in the remaining default parameter values
1876 if (Lexer.is(AsmToken::EndOfStatement))
1879 // Adjust the current parentheses level.
1880 if (Lexer.is(AsmToken::LParen))
1882 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1885 // Append the token to the current argument list.
1886 MA.push_back(getTok());
1892 Lexer.setSkipSpace(true);
1893 if (ParenLevel != 0)
1894 return TokError("unbalanced parentheses in macro argument");
1898 // Parse the macro instantiation arguments.
1899 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1900 MCAsmMacroArguments &A) {
1901 const unsigned NParameters = M ? M->Parameters.size() : 0;
1902 // Argument delimiter is initially unknown. It will be set by
1903 // parseMacroArgument()
1904 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1906 // Parse two kinds of macro invocations:
1907 // - macros defined without any parameters accept an arbitrary number of them
1908 // - macros defined with parameters accept at most that many of them
1909 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1911 MCAsmMacroArgument MA;
1913 if (parseMacroArgument(MA, ArgumentDelimiter))
1916 if (!MA.empty() || !NParameters)
1918 else if (NParameters) {
1919 if (!M->Parameters[Parameter].second.empty())
1920 A.push_back(M->Parameters[Parameter].second);
1923 // At the end of the statement, fill in remaining arguments that have
1924 // default values. If there aren't any, then the next argument is
1925 // required but missing
1926 if (Lexer.is(AsmToken::EndOfStatement)) {
1927 if (NParameters && Parameter < NParameters - 1) {
1928 if (M->Parameters[Parameter + 1].second.empty())
1929 return TokError("macro argument '" +
1930 Twine(M->Parameters[Parameter + 1].first) +
1938 if (Lexer.is(AsmToken::Comma))
1941 return TokError("Too many arguments");
1944 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
1945 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1946 return (I == MacroMap.end()) ? NULL : I->getValue();
1949 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
1950 MacroMap[Name] = new MCAsmMacro(Macro);
1953 void AsmParser::undefineMacro(StringRef Name) {
1954 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1955 if (I != MacroMap.end()) {
1956 delete I->getValue();
1961 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1962 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1963 // this, although we should protect against infinite loops.
1964 if (ActiveMacros.size() == 20)
1965 return TokError("macros cannot be nested more than 20 levels deep");
1967 MCAsmMacroArguments A;
1968 if (parseMacroArguments(M, A))
1971 // Remove any trailing empty arguments. Do this after-the-fact as we have
1972 // to keep empty arguments in the middle of the list or positionality
1973 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1974 while (!A.empty() && A.back().empty())
1977 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1978 // to hold the macro body with substitutions.
1979 SmallString<256> Buf;
1980 StringRef Body = M->Body;
1981 raw_svector_ostream OS(Buf);
1983 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1986 // We include the .endmacro in the buffer as our cue to exit the macro
1988 OS << ".endmacro\n";
1990 MemoryBuffer *Instantiation =
1991 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1993 // Create the macro instantiation object and add to the current macro
1994 // instantiation stack.
1995 MacroInstantiation *MI = new MacroInstantiation(
1996 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
1997 ActiveMacros.push_back(MI);
1999 // Jump to the macro instantiation and prime the lexer.
2000 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2001 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2007 void AsmParser::handleMacroExit() {
2008 // Jump to the EndOfStatement we should return to, and consume it.
2009 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2012 // Pop the instantiation entry.
2013 delete ActiveMacros.back();
2014 ActiveMacros.pop_back();
2017 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2018 switch (Value->getKind()) {
2019 case MCExpr::Binary: {
2020 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2021 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2023 case MCExpr::Target:
2024 case MCExpr::Constant:
2026 case MCExpr::SymbolRef: {
2028 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2030 return isUsedIn(Sym, S.getVariableValue());
2034 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2037 llvm_unreachable("Unknown expr kind!");
2040 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2042 // FIXME: Use better location, we should use proper tokens.
2043 SMLoc EqualLoc = Lexer.getLoc();
2045 const MCExpr *Value;
2046 if (parseExpression(Value))
2049 // Note: we don't count b as used in "a = b". This is to allow
2053 if (Lexer.isNot(AsmToken::EndOfStatement))
2054 return TokError("unexpected token in assignment");
2056 // Error on assignment to '.'.
2058 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2059 "(use '.space' or '.org').)"));
2062 // Eat the end of statement marker.
2065 // Validate that the LHS is allowed to be a variable (either it has not been
2066 // used as a symbol, or it is an absolute symbol).
2067 MCSymbol *Sym = getContext().LookupSymbol(Name);
2069 // Diagnose assignment to a label.
2071 // FIXME: Diagnostics. Note the location of the definition as a label.
2072 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2073 if (isUsedIn(Sym, Value))
2074 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2075 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2076 ; // Allow redefinitions of undefined symbols only used in directives.
2077 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2078 ; // Allow redefinitions of variables that haven't yet been used.
2079 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2080 return Error(EqualLoc, "redefinition of '" + Name + "'");
2081 else if (!Sym->isVariable())
2082 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2083 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2084 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2087 // Don't count these checks as uses.
2088 Sym->setUsed(false);
2090 Sym = getContext().GetOrCreateSymbol(Name);
2092 // FIXME: Handle '.'.
2094 // Do the assignment.
2095 Out.EmitAssignment(Sym, Value);
2097 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2102 /// parseIdentifier:
2105 bool AsmParser::parseIdentifier(StringRef &Res) {
2106 // The assembler has relaxed rules for accepting identifiers, in particular we
2107 // allow things like '.globl $foo', which would normally be separate
2108 // tokens. At this level, we have already lexed so we cannot (currently)
2109 // handle this as a context dependent token, instead we detect adjacent tokens
2110 // and return the combined identifier.
2111 if (Lexer.is(AsmToken::Dollar)) {
2112 SMLoc DollarLoc = getLexer().getLoc();
2114 // Consume the dollar sign, and check for a following identifier.
2116 if (Lexer.isNot(AsmToken::Identifier))
2119 // We have a '$' followed by an identifier, make sure they are adjacent.
2120 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2123 // Construct the joined identifier and consume the token.
2125 StringRef(DollarLoc.getPointer(), getTok().getIdentifier().size() + 1);
2130 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2133 Res = getTok().getIdentifier();
2135 Lex(); // Consume the identifier token.
2140 /// parseDirectiveSet:
2141 /// ::= .equ identifier ',' expression
2142 /// ::= .equiv identifier ',' expression
2143 /// ::= .set identifier ',' expression
2144 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2147 if (parseIdentifier(Name))
2148 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2150 if (getLexer().isNot(AsmToken::Comma))
2151 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2154 return parseAssignment(Name, allow_redef, true);
2157 bool AsmParser::parseEscapedString(std::string &Data) {
2158 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2161 StringRef Str = getTok().getStringContents();
2162 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2163 if (Str[i] != '\\') {
2168 // Recognize escaped characters. Note that this escape semantics currently
2169 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2172 return TokError("unexpected backslash at end of string");
2174 // Recognize octal sequences.
2175 if ((unsigned)(Str[i] - '0') <= 7) {
2176 // Consume up to three octal characters.
2177 unsigned Value = Str[i] - '0';
2179 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2181 Value = Value * 8 + (Str[i] - '0');
2183 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2185 Value = Value * 8 + (Str[i] - '0');
2190 return TokError("invalid octal escape sequence (out of range)");
2192 Data += (unsigned char)Value;
2196 // Otherwise recognize individual escapes.
2199 // Just reject invalid escape sequences for now.
2200 return TokError("invalid escape sequence (unrecognized character)");
2202 case 'b': Data += '\b'; break;
2203 case 'f': Data += '\f'; break;
2204 case 'n': Data += '\n'; break;
2205 case 'r': Data += '\r'; break;
2206 case 't': Data += '\t'; break;
2207 case '"': Data += '"'; break;
2208 case '\\': Data += '\\'; break;
2215 /// parseDirectiveAscii:
2216 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2217 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2218 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2219 checkForValidSection();
2222 if (getLexer().isNot(AsmToken::String))
2223 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2226 if (parseEscapedString(Data))
2229 getStreamer().EmitBytes(Data);
2231 getStreamer().EmitBytes(StringRef("\0", 1));
2235 if (getLexer().is(AsmToken::EndOfStatement))
2238 if (getLexer().isNot(AsmToken::Comma))
2239 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2248 /// parseDirectiveValue
2249 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2250 bool AsmParser::parseDirectiveValue(unsigned Size) {
2251 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2252 checkForValidSection();
2255 const MCExpr *Value;
2256 SMLoc ExprLoc = getLexer().getLoc();
2257 if (parseExpression(Value))
2260 // Special case constant expressions to match code generator.
2261 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2262 assert(Size <= 8 && "Invalid size");
2263 uint64_t IntValue = MCE->getValue();
2264 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2265 return Error(ExprLoc, "literal value out of range for directive");
2266 getStreamer().EmitIntValue(IntValue, Size);
2268 getStreamer().EmitValue(Value, Size);
2270 if (getLexer().is(AsmToken::EndOfStatement))
2273 // FIXME: Improve diagnostic.
2274 if (getLexer().isNot(AsmToken::Comma))
2275 return TokError("unexpected token in directive");
2284 /// parseDirectiveRealValue
2285 /// ::= (.single | .double) [ expression (, expression)* ]
2286 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2287 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2288 checkForValidSection();
2291 // We don't truly support arithmetic on floating point expressions, so we
2292 // have to manually parse unary prefixes.
2294 if (getLexer().is(AsmToken::Minus)) {
2297 } else if (getLexer().is(AsmToken::Plus))
2300 if (getLexer().isNot(AsmToken::Integer) &&
2301 getLexer().isNot(AsmToken::Real) &&
2302 getLexer().isNot(AsmToken::Identifier))
2303 return TokError("unexpected token in directive");
2305 // Convert to an APFloat.
2306 APFloat Value(Semantics);
2307 StringRef IDVal = getTok().getString();
2308 if (getLexer().is(AsmToken::Identifier)) {
2309 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2310 Value = APFloat::getInf(Semantics);
2311 else if (!IDVal.compare_lower("nan"))
2312 Value = APFloat::getNaN(Semantics, false, ~0);
2314 return TokError("invalid floating point literal");
2315 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2316 APFloat::opInvalidOp)
2317 return TokError("invalid floating point literal");
2321 // Consume the numeric token.
2324 // Emit the value as an integer.
2325 APInt AsInt = Value.bitcastToAPInt();
2326 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2327 AsInt.getBitWidth() / 8);
2329 if (getLexer().is(AsmToken::EndOfStatement))
2332 if (getLexer().isNot(AsmToken::Comma))
2333 return TokError("unexpected token in directive");
2342 /// parseDirectiveZero
2343 /// ::= .zero expression
2344 bool AsmParser::parseDirectiveZero() {
2345 checkForValidSection();
2348 if (parseAbsoluteExpression(NumBytes))
2352 if (getLexer().is(AsmToken::Comma)) {
2354 if (parseAbsoluteExpression(Val))
2358 if (getLexer().isNot(AsmToken::EndOfStatement))
2359 return TokError("unexpected token in '.zero' directive");
2363 getStreamer().EmitFill(NumBytes, Val);
2368 /// parseDirectiveFill
2369 /// ::= .fill expression [ , expression [ , expression ] ]
2370 bool AsmParser::parseDirectiveFill() {
2371 checkForValidSection();
2374 if (parseAbsoluteExpression(NumValues))
2377 int64_t FillSize = 1;
2378 int64_t FillExpr = 0;
2380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2381 if (getLexer().isNot(AsmToken::Comma))
2382 return TokError("unexpected token in '.fill' directive");
2385 if (parseAbsoluteExpression(FillSize))
2388 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2389 if (getLexer().isNot(AsmToken::Comma))
2390 return TokError("unexpected token in '.fill' directive");
2393 if (parseAbsoluteExpression(FillExpr))
2396 if (getLexer().isNot(AsmToken::EndOfStatement))
2397 return TokError("unexpected token in '.fill' directive");
2403 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2404 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2406 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2407 getStreamer().EmitIntValue(FillExpr, FillSize);
2412 /// parseDirectiveOrg
2413 /// ::= .org expression [ , expression ]
2414 bool AsmParser::parseDirectiveOrg() {
2415 checkForValidSection();
2417 const MCExpr *Offset;
2418 SMLoc Loc = getTok().getLoc();
2419 if (parseExpression(Offset))
2422 // Parse optional fill expression.
2423 int64_t FillExpr = 0;
2424 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2425 if (getLexer().isNot(AsmToken::Comma))
2426 return TokError("unexpected token in '.org' directive");
2429 if (parseAbsoluteExpression(FillExpr))
2432 if (getLexer().isNot(AsmToken::EndOfStatement))
2433 return TokError("unexpected token in '.org' directive");
2438 // Only limited forms of relocatable expressions are accepted here, it
2439 // has to be relative to the current section. The streamer will return
2440 // 'true' if the expression wasn't evaluatable.
2441 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2442 return Error(Loc, "expected assembly-time absolute expression");
2447 /// parseDirectiveAlign
2448 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2449 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2450 checkForValidSection();
2452 SMLoc AlignmentLoc = getLexer().getLoc();
2454 if (parseAbsoluteExpression(Alignment))
2458 bool HasFillExpr = false;
2459 int64_t FillExpr = 0;
2460 int64_t MaxBytesToFill = 0;
2461 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2462 if (getLexer().isNot(AsmToken::Comma))
2463 return TokError("unexpected token in directive");
2466 // The fill expression can be omitted while specifying a maximum number of
2467 // alignment bytes, e.g:
2469 if (getLexer().isNot(AsmToken::Comma)) {
2471 if (parseAbsoluteExpression(FillExpr))
2475 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2476 if (getLexer().isNot(AsmToken::Comma))
2477 return TokError("unexpected token in directive");
2480 MaxBytesLoc = getLexer().getLoc();
2481 if (parseAbsoluteExpression(MaxBytesToFill))
2484 if (getLexer().isNot(AsmToken::EndOfStatement))
2485 return TokError("unexpected token in directive");
2494 // Compute alignment in bytes.
2496 // FIXME: Diagnose overflow.
2497 if (Alignment >= 32) {
2498 Error(AlignmentLoc, "invalid alignment value");
2502 Alignment = 1ULL << Alignment;
2504 // Reject alignments that aren't a power of two, for gas compatibility.
2505 if (!isPowerOf2_64(Alignment))
2506 Error(AlignmentLoc, "alignment must be a power of 2");
2509 // Diagnose non-sensical max bytes to align.
2510 if (MaxBytesLoc.isValid()) {
2511 if (MaxBytesToFill < 1) {
2512 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2513 "many bytes, ignoring maximum bytes expression");
2517 if (MaxBytesToFill >= Alignment) {
2518 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2524 // Check whether we should use optimal code alignment for this .align
2526 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2527 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2528 ValueSize == 1 && UseCodeAlign) {
2529 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2531 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2532 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2539 /// parseDirectiveFile
2540 /// ::= .file [number] filename
2541 /// ::= .file number directory filename
2542 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2543 // FIXME: I'm not sure what this is.
2544 int64_t FileNumber = -1;
2545 SMLoc FileNumberLoc = getLexer().getLoc();
2546 if (getLexer().is(AsmToken::Integer)) {
2547 FileNumber = getTok().getIntVal();
2551 return TokError("file number less than one");
2554 if (getLexer().isNot(AsmToken::String))
2555 return TokError("unexpected token in '.file' directive");
2557 // Usually the directory and filename together, otherwise just the directory.
2558 // Allow the strings to have escaped octal character sequence.
2559 std::string Path = getTok().getString();
2560 if (parseEscapedString(Path))
2564 StringRef Directory;
2566 std::string FilenameData;
2567 if (getLexer().is(AsmToken::String)) {
2568 if (FileNumber == -1)
2569 return TokError("explicit path specified, but no file number");
2570 if (parseEscapedString(FilenameData))
2572 Filename = FilenameData;
2579 if (getLexer().isNot(AsmToken::EndOfStatement))
2580 return TokError("unexpected token in '.file' directive");
2582 if (FileNumber == -1)
2583 getStreamer().EmitFileDirective(Filename);
2585 if (getContext().getGenDwarfForAssembly() == true)
2587 "input can't have .file dwarf directives when -g is "
2588 "used to generate dwarf debug info for assembly code");
2590 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2591 Error(FileNumberLoc, "file number already allocated");
2597 /// parseDirectiveLine
2598 /// ::= .line [number]
2599 bool AsmParser::parseDirectiveLine() {
2600 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2601 if (getLexer().isNot(AsmToken::Integer))
2602 return TokError("unexpected token in '.line' directive");
2604 int64_t LineNumber = getTok().getIntVal();
2608 // FIXME: Do something with the .line.
2611 if (getLexer().isNot(AsmToken::EndOfStatement))
2612 return TokError("unexpected token in '.line' directive");
2617 /// parseDirectiveLoc
2618 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2619 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2620 /// The first number is a file number, must have been previously assigned with
2621 /// a .file directive, the second number is the line number and optionally the
2622 /// third number is a column position (zero if not specified). The remaining
2623 /// optional items are .loc sub-directives.
2624 bool AsmParser::parseDirectiveLoc() {
2625 if (getLexer().isNot(AsmToken::Integer))
2626 return TokError("unexpected token in '.loc' directive");
2627 int64_t FileNumber = getTok().getIntVal();
2629 return TokError("file number less than one in '.loc' directive");
2630 if (!getContext().isValidDwarfFileNumber(FileNumber))
2631 return TokError("unassigned file number in '.loc' directive");
2634 int64_t LineNumber = 0;
2635 if (getLexer().is(AsmToken::Integer)) {
2636 LineNumber = getTok().getIntVal();
2638 return TokError("line number less than zero in '.loc' directive");
2642 int64_t ColumnPos = 0;
2643 if (getLexer().is(AsmToken::Integer)) {
2644 ColumnPos = getTok().getIntVal();
2646 return TokError("column position less than zero in '.loc' directive");
2650 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2652 int64_t Discriminator = 0;
2653 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2655 if (getLexer().is(AsmToken::EndOfStatement))
2659 SMLoc Loc = getTok().getLoc();
2660 if (parseIdentifier(Name))
2661 return TokError("unexpected token in '.loc' directive");
2663 if (Name == "basic_block")
2664 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2665 else if (Name == "prologue_end")
2666 Flags |= DWARF2_FLAG_PROLOGUE_END;
2667 else if (Name == "epilogue_begin")
2668 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2669 else if (Name == "is_stmt") {
2670 Loc = getTok().getLoc();
2671 const MCExpr *Value;
2672 if (parseExpression(Value))
2674 // The expression must be the constant 0 or 1.
2675 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2676 int Value = MCE->getValue();
2678 Flags &= ~DWARF2_FLAG_IS_STMT;
2679 else if (Value == 1)
2680 Flags |= DWARF2_FLAG_IS_STMT;
2682 return Error(Loc, "is_stmt value not 0 or 1");
2684 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2686 } else if (Name == "isa") {
2687 Loc = getTok().getLoc();
2688 const MCExpr *Value;
2689 if (parseExpression(Value))
2691 // The expression must be a constant greater or equal to 0.
2692 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2693 int Value = MCE->getValue();
2695 return Error(Loc, "isa number less than zero");
2698 return Error(Loc, "isa number not a constant value");
2700 } else if (Name == "discriminator") {
2701 if (parseAbsoluteExpression(Discriminator))
2704 return Error(Loc, "unknown sub-directive in '.loc' directive");
2707 if (getLexer().is(AsmToken::EndOfStatement))
2712 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2713 Isa, Discriminator, StringRef());
2718 /// parseDirectiveStabs
2719 /// ::= .stabs string, number, number, number
2720 bool AsmParser::parseDirectiveStabs() {
2721 return TokError("unsupported directive '.stabs'");
2724 /// parseDirectiveCFISections
2725 /// ::= .cfi_sections section [, section]
2726 bool AsmParser::parseDirectiveCFISections() {
2731 if (parseIdentifier(Name))
2732 return TokError("Expected an identifier");
2734 if (Name == ".eh_frame")
2736 else if (Name == ".debug_frame")
2739 if (getLexer().is(AsmToken::Comma)) {
2742 if (parseIdentifier(Name))
2743 return TokError("Expected an identifier");
2745 if (Name == ".eh_frame")
2747 else if (Name == ".debug_frame")
2751 getStreamer().EmitCFISections(EH, Debug);
2755 /// parseDirectiveCFIStartProc
2756 /// ::= .cfi_startproc
2757 bool AsmParser::parseDirectiveCFIStartProc() {
2758 getStreamer().EmitCFIStartProc();
2762 /// parseDirectiveCFIEndProc
2763 /// ::= .cfi_endproc
2764 bool AsmParser::parseDirectiveCFIEndProc() {
2765 getStreamer().EmitCFIEndProc();
2769 /// \brief parse register name or number.
2770 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2771 SMLoc DirectiveLoc) {
2774 if (getLexer().isNot(AsmToken::Integer)) {
2775 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2777 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2779 return parseAbsoluteExpression(Register);
2784 /// parseDirectiveCFIDefCfa
2785 /// ::= .cfi_def_cfa register, offset
2786 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2787 int64_t Register = 0;
2788 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2791 if (getLexer().isNot(AsmToken::Comma))
2792 return TokError("unexpected token in directive");
2796 if (parseAbsoluteExpression(Offset))
2799 getStreamer().EmitCFIDefCfa(Register, Offset);
2803 /// parseDirectiveCFIDefCfaOffset
2804 /// ::= .cfi_def_cfa_offset offset
2805 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2807 if (parseAbsoluteExpression(Offset))
2810 getStreamer().EmitCFIDefCfaOffset(Offset);
2814 /// parseDirectiveCFIRegister
2815 /// ::= .cfi_register register, register
2816 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2817 int64_t Register1 = 0;
2818 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2821 if (getLexer().isNot(AsmToken::Comma))
2822 return TokError("unexpected token in directive");
2825 int64_t Register2 = 0;
2826 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2829 getStreamer().EmitCFIRegister(Register1, Register2);
2833 /// parseDirectiveCFIWindowSave
2834 /// ::= .cfi_window_save
2835 bool AsmParser::parseDirectiveCFIWindowSave() {
2836 getStreamer().EmitCFIWindowSave();
2840 /// parseDirectiveCFIAdjustCfaOffset
2841 /// ::= .cfi_adjust_cfa_offset adjustment
2842 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2843 int64_t Adjustment = 0;
2844 if (parseAbsoluteExpression(Adjustment))
2847 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2851 /// parseDirectiveCFIDefCfaRegister
2852 /// ::= .cfi_def_cfa_register register
2853 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2854 int64_t Register = 0;
2855 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2858 getStreamer().EmitCFIDefCfaRegister(Register);
2862 /// parseDirectiveCFIOffset
2863 /// ::= .cfi_offset register, offset
2864 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2865 int64_t Register = 0;
2868 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2871 if (getLexer().isNot(AsmToken::Comma))
2872 return TokError("unexpected token in directive");
2875 if (parseAbsoluteExpression(Offset))
2878 getStreamer().EmitCFIOffset(Register, Offset);
2882 /// parseDirectiveCFIRelOffset
2883 /// ::= .cfi_rel_offset register, offset
2884 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2885 int64_t Register = 0;
2887 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2890 if (getLexer().isNot(AsmToken::Comma))
2891 return TokError("unexpected token in directive");
2895 if (parseAbsoluteExpression(Offset))
2898 getStreamer().EmitCFIRelOffset(Register, Offset);
2902 static bool isValidEncoding(int64_t Encoding) {
2903 if (Encoding & ~0xff)
2906 if (Encoding == dwarf::DW_EH_PE_omit)
2909 const unsigned Format = Encoding & 0xf;
2910 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2911 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2912 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2913 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2916 const unsigned Application = Encoding & 0x70;
2917 if (Application != dwarf::DW_EH_PE_absptr &&
2918 Application != dwarf::DW_EH_PE_pcrel)
2924 /// parseDirectiveCFIPersonalityOrLsda
2925 /// IsPersonality true for cfi_personality, false for cfi_lsda
2926 /// ::= .cfi_personality encoding, [symbol_name]
2927 /// ::= .cfi_lsda encoding, [symbol_name]
2928 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2929 int64_t Encoding = 0;
2930 if (parseAbsoluteExpression(Encoding))
2932 if (Encoding == dwarf::DW_EH_PE_omit)
2935 if (!isValidEncoding(Encoding))
2936 return TokError("unsupported encoding.");
2938 if (getLexer().isNot(AsmToken::Comma))
2939 return TokError("unexpected token in directive");
2943 if (parseIdentifier(Name))
2944 return TokError("expected identifier in directive");
2946 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2949 getStreamer().EmitCFIPersonality(Sym, Encoding);
2951 getStreamer().EmitCFILsda(Sym, Encoding);
2955 /// parseDirectiveCFIRememberState
2956 /// ::= .cfi_remember_state
2957 bool AsmParser::parseDirectiveCFIRememberState() {
2958 getStreamer().EmitCFIRememberState();
2962 /// parseDirectiveCFIRestoreState
2963 /// ::= .cfi_remember_state
2964 bool AsmParser::parseDirectiveCFIRestoreState() {
2965 getStreamer().EmitCFIRestoreState();
2969 /// parseDirectiveCFISameValue
2970 /// ::= .cfi_same_value register
2971 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2972 int64_t Register = 0;
2974 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2977 getStreamer().EmitCFISameValue(Register);
2981 /// parseDirectiveCFIRestore
2982 /// ::= .cfi_restore register
2983 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2984 int64_t Register = 0;
2985 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2988 getStreamer().EmitCFIRestore(Register);
2992 /// parseDirectiveCFIEscape
2993 /// ::= .cfi_escape expression[,...]
2994 bool AsmParser::parseDirectiveCFIEscape() {
2997 if (parseAbsoluteExpression(CurrValue))
3000 Values.push_back((uint8_t)CurrValue);
3002 while (getLexer().is(AsmToken::Comma)) {
3005 if (parseAbsoluteExpression(CurrValue))
3008 Values.push_back((uint8_t)CurrValue);
3011 getStreamer().EmitCFIEscape(Values);
3015 /// parseDirectiveCFISignalFrame
3016 /// ::= .cfi_signal_frame
3017 bool AsmParser::parseDirectiveCFISignalFrame() {
3018 if (getLexer().isNot(AsmToken::EndOfStatement))
3019 return Error(getLexer().getLoc(),
3020 "unexpected token in '.cfi_signal_frame'");
3022 getStreamer().EmitCFISignalFrame();
3026 /// parseDirectiveCFIUndefined
3027 /// ::= .cfi_undefined register
3028 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3029 int64_t Register = 0;
3031 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3034 getStreamer().EmitCFIUndefined(Register);
3038 /// parseDirectiveMacrosOnOff
3041 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3042 if (getLexer().isNot(AsmToken::EndOfStatement))
3043 return Error(getLexer().getLoc(),
3044 "unexpected token in '" + Directive + "' directive");
3046 setMacrosEnabled(Directive == ".macros_on");
3050 /// parseDirectiveMacro
3051 /// ::= .macro name [parameters]
3052 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3054 if (parseIdentifier(Name))
3055 return TokError("expected identifier in '.macro' directive");
3057 MCAsmMacroParameters Parameters;
3058 // Argument delimiter is initially unknown. It will be set by
3059 // parseMacroArgument()
3060 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3061 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3063 MCAsmMacroParameter Parameter;
3064 if (parseIdentifier(Parameter.first))
3065 return TokError("expected identifier in '.macro' directive");
3067 if (getLexer().is(AsmToken::Equal)) {
3069 if (parseMacroArgument(Parameter.second, ArgumentDelimiter))
3073 Parameters.push_back(Parameter);
3075 if (getLexer().is(AsmToken::Comma))
3077 else if (getLexer().is(AsmToken::EndOfStatement))
3082 // Eat the end of statement.
3085 AsmToken EndToken, StartToken = getTok();
3087 // Lex the macro definition.
3089 // Check whether we have reached the end of the file.
3090 if (getLexer().is(AsmToken::Eof))
3091 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3093 // Otherwise, check whether we have reach the .endmacro.
3094 if (getLexer().is(AsmToken::Identifier) &&
3095 (getTok().getIdentifier() == ".endm" ||
3096 getTok().getIdentifier() == ".endmacro")) {
3097 EndToken = getTok();
3099 if (getLexer().isNot(AsmToken::EndOfStatement))
3100 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3105 // Otherwise, scan til the end of the statement.
3106 eatToEndOfStatement();
3109 if (lookupMacro(Name)) {
3110 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3113 const char *BodyStart = StartToken.getLoc().getPointer();
3114 const char *BodyEnd = EndToken.getLoc().getPointer();
3115 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3116 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3117 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3121 /// checkForBadMacro
3123 /// With the support added for named parameters there may be code out there that
3124 /// is transitioning from positional parameters. In versions of gas that did
3125 /// not support named parameters they would be ignored on the macro defintion.
3126 /// But to support both styles of parameters this is not possible so if a macro
3127 /// defintion has named parameters but does not use them and has what appears
3128 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3129 /// warning that the positional parameter found in body which have no effect.
3130 /// Hoping the developer will either remove the named parameters from the macro
3131 /// definiton so the positional parameters get used if that was what was
3132 /// intended or change the macro to use the named parameters. It is possible
3133 /// this warning will trigger when the none of the named parameters are used
3134 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3135 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3137 MCAsmMacroParameters Parameters) {
3138 // If this macro is not defined with named parameters the warning we are
3139 // checking for here doesn't apply.
3140 unsigned NParameters = Parameters.size();
3141 if (NParameters == 0)
3144 bool NamedParametersFound = false;
3145 bool PositionalParametersFound = false;
3147 // Look at the body of the macro for use of both the named parameters and what
3148 // are likely to be positional parameters. This is what expandMacro() is
3149 // doing when it finds the parameters in the body.
3150 while (!Body.empty()) {
3151 // Scan for the next possible parameter.
3152 std::size_t End = Body.size(), Pos = 0;
3153 for (; Pos != End; ++Pos) {
3154 // Check for a substitution or escape.
3155 // This macro is defined with parameters, look for \foo, \bar, etc.
3156 if (Body[Pos] == '\\' && Pos + 1 != End)
3159 // This macro should have parameters, but look for $0, $1, ..., $n too.
3160 if (Body[Pos] != '$' || Pos + 1 == End)
3162 char Next = Body[Pos + 1];
3163 if (Next == '$' || Next == 'n' ||
3164 isdigit(static_cast<unsigned char>(Next)))
3168 // Check if we reached the end.
3172 if (Body[Pos] == '$') {
3173 switch (Body[Pos + 1]) {
3178 // $n => number of arguments
3180 PositionalParametersFound = true;
3183 // $[0-9] => argument
3185 PositionalParametersFound = true;
3191 unsigned I = Pos + 1;
3192 while (isIdentifierChar(Body[I]) && I + 1 != End)
3195 const char *Begin = Body.data() + Pos + 1;
3196 StringRef Argument(Begin, I - (Pos + 1));
3198 for (; Index < NParameters; ++Index)
3199 if (Parameters[Index].first == Argument)
3202 if (Index == NParameters) {
3203 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3209 NamedParametersFound = true;
3210 Pos += 1 + Argument.size();
3213 // Update the scan point.
3214 Body = Body.substr(Pos);
3217 if (!NamedParametersFound && PositionalParametersFound)
3218 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3219 "used in macro body, possible positional parameter "
3220 "found in body which will have no effect");
3223 /// parseDirectiveEndMacro
3226 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3227 if (getLexer().isNot(AsmToken::EndOfStatement))
3228 return TokError("unexpected token in '" + Directive + "' directive");
3230 // If we are inside a macro instantiation, terminate the current
3232 if (isInsideMacroInstantiation()) {
3237 // Otherwise, this .endmacro is a stray entry in the file; well formed
3238 // .endmacro directives are handled during the macro definition parsing.
3239 return TokError("unexpected '" + Directive + "' in file, "
3240 "no current macro definition");
3243 /// parseDirectivePurgeMacro
3245 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3247 if (parseIdentifier(Name))
3248 return TokError("expected identifier in '.purgem' directive");
3250 if (getLexer().isNot(AsmToken::EndOfStatement))
3251 return TokError("unexpected token in '.purgem' directive");
3253 if (!lookupMacro(Name))
3254 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3256 undefineMacro(Name);
3260 /// parseDirectiveBundleAlignMode
3261 /// ::= {.bundle_align_mode} expression
3262 bool AsmParser::parseDirectiveBundleAlignMode() {
3263 checkForValidSection();
3265 // Expect a single argument: an expression that evaluates to a constant
3266 // in the inclusive range 0-30.
3267 SMLoc ExprLoc = getLexer().getLoc();
3268 int64_t AlignSizePow2;
3269 if (parseAbsoluteExpression(AlignSizePow2))
3271 else if (getLexer().isNot(AsmToken::EndOfStatement))
3272 return TokError("unexpected token after expression in"
3273 " '.bundle_align_mode' directive");
3274 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3275 return Error(ExprLoc,
3276 "invalid bundle alignment size (expected between 0 and 30)");
3280 // Because of AlignSizePow2's verified range we can safely truncate it to
3282 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3286 /// parseDirectiveBundleLock
3287 /// ::= {.bundle_lock} [align_to_end]
3288 bool AsmParser::parseDirectiveBundleLock() {
3289 checkForValidSection();
3290 bool AlignToEnd = false;
3292 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3294 SMLoc Loc = getTok().getLoc();
3295 const char *kInvalidOptionError =
3296 "invalid option for '.bundle_lock' directive";
3298 if (parseIdentifier(Option))
3299 return Error(Loc, kInvalidOptionError);
3301 if (Option != "align_to_end")
3302 return Error(Loc, kInvalidOptionError);
3303 else if (getLexer().isNot(AsmToken::EndOfStatement))
3305 "unexpected token after '.bundle_lock' directive option");
3311 getStreamer().EmitBundleLock(AlignToEnd);
3315 /// parseDirectiveBundleLock
3316 /// ::= {.bundle_lock}
3317 bool AsmParser::parseDirectiveBundleUnlock() {
3318 checkForValidSection();
3320 if (getLexer().isNot(AsmToken::EndOfStatement))
3321 return TokError("unexpected token in '.bundle_unlock' directive");
3324 getStreamer().EmitBundleUnlock();
3328 /// parseDirectiveSpace
3329 /// ::= (.skip | .space) expression [ , expression ]
3330 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3331 checkForValidSection();
3334 if (parseAbsoluteExpression(NumBytes))
3337 int64_t FillExpr = 0;
3338 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3339 if (getLexer().isNot(AsmToken::Comma))
3340 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3343 if (parseAbsoluteExpression(FillExpr))
3346 if (getLexer().isNot(AsmToken::EndOfStatement))
3347 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3353 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3356 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3357 getStreamer().EmitFill(NumBytes, FillExpr);
3362 /// parseDirectiveLEB128
3363 /// ::= (.sleb128 | .uleb128) expression
3364 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3365 checkForValidSection();
3366 const MCExpr *Value;
3368 if (parseExpression(Value))
3371 if (getLexer().isNot(AsmToken::EndOfStatement))
3372 return TokError("unexpected token in directive");
3375 getStreamer().EmitSLEB128Value(Value);
3377 getStreamer().EmitULEB128Value(Value);
3382 /// parseDirectiveSymbolAttribute
3383 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3384 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3385 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3388 SMLoc Loc = getTok().getLoc();
3390 if (parseIdentifier(Name))
3391 return Error(Loc, "expected identifier in directive");
3393 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3395 // Assembler local symbols don't make any sense here. Complain loudly.
3396 if (Sym->isTemporary())
3397 return Error(Loc, "non-local symbol required in directive");
3399 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3400 return Error(Loc, "unable to emit symbol attribute");
3402 if (getLexer().is(AsmToken::EndOfStatement))
3405 if (getLexer().isNot(AsmToken::Comma))
3406 return TokError("unexpected token in directive");
3415 /// parseDirectiveComm
3416 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3417 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3418 checkForValidSection();
3420 SMLoc IDLoc = getLexer().getLoc();
3422 if (parseIdentifier(Name))
3423 return TokError("expected identifier in directive");
3425 // Handle the identifier as the key symbol.
3426 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3428 if (getLexer().isNot(AsmToken::Comma))
3429 return TokError("unexpected token in directive");
3433 SMLoc SizeLoc = getLexer().getLoc();
3434 if (parseAbsoluteExpression(Size))
3437 int64_t Pow2Alignment = 0;
3438 SMLoc Pow2AlignmentLoc;
3439 if (getLexer().is(AsmToken::Comma)) {
3441 Pow2AlignmentLoc = getLexer().getLoc();
3442 if (parseAbsoluteExpression(Pow2Alignment))
3445 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3446 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3447 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3449 // If this target takes alignments in bytes (not log) validate and convert.
3450 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3451 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3452 if (!isPowerOf2_64(Pow2Alignment))
3453 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3454 Pow2Alignment = Log2_64(Pow2Alignment);
3458 if (getLexer().isNot(AsmToken::EndOfStatement))
3459 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3463 // NOTE: a size of zero for a .comm should create a undefined symbol
3464 // but a size of .lcomm creates a bss symbol of size zero.
3466 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3467 "be less than zero");
3469 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3470 // may internally end up wanting an alignment in bytes.
3471 // FIXME: Diagnose overflow.
3472 if (Pow2Alignment < 0)
3473 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3474 "alignment, can't be less than zero");
3476 if (!Sym->isUndefined())
3477 return Error(IDLoc, "invalid symbol redefinition");
3479 // Create the Symbol as a common or local common with Size and Pow2Alignment
3481 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3485 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3489 /// parseDirectiveAbort
3490 /// ::= .abort [... message ...]
3491 bool AsmParser::parseDirectiveAbort() {
3492 // FIXME: Use loc from directive.
3493 SMLoc Loc = getLexer().getLoc();
3495 StringRef Str = parseStringToEndOfStatement();
3496 if (getLexer().isNot(AsmToken::EndOfStatement))
3497 return TokError("unexpected token in '.abort' directive");
3502 Error(Loc, ".abort detected. Assembly stopping.");
3504 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3505 // FIXME: Actually abort assembly here.
3510 /// parseDirectiveInclude
3511 /// ::= .include "filename"
3512 bool AsmParser::parseDirectiveInclude() {
3513 if (getLexer().isNot(AsmToken::String))
3514 return TokError("expected string in '.include' directive");
3516 // Allow the strings to have escaped octal character sequence.
3517 std::string Filename;
3518 if (parseEscapedString(Filename))
3520 SMLoc IncludeLoc = getLexer().getLoc();
3523 if (getLexer().isNot(AsmToken::EndOfStatement))
3524 return TokError("unexpected token in '.include' directive");
3526 // Attempt to switch the lexer to the included file before consuming the end
3527 // of statement to avoid losing it when we switch.
3528 if (enterIncludeFile(Filename)) {
3529 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3536 /// parseDirectiveIncbin
3537 /// ::= .incbin "filename"
3538 bool AsmParser::parseDirectiveIncbin() {
3539 if (getLexer().isNot(AsmToken::String))
3540 return TokError("expected string in '.incbin' directive");
3542 // Allow the strings to have escaped octal character sequence.
3543 std::string Filename;
3544 if (parseEscapedString(Filename))
3546 SMLoc IncbinLoc = getLexer().getLoc();
3549 if (getLexer().isNot(AsmToken::EndOfStatement))
3550 return TokError("unexpected token in '.incbin' directive");
3552 // Attempt to process the included file.
3553 if (processIncbinFile(Filename)) {
3554 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3561 /// parseDirectiveIf
3562 /// ::= .if expression
3563 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3564 TheCondStack.push_back(TheCondState);
3565 TheCondState.TheCond = AsmCond::IfCond;
3566 if (TheCondState.Ignore) {
3567 eatToEndOfStatement();
3570 if (parseAbsoluteExpression(ExprValue))
3573 if (getLexer().isNot(AsmToken::EndOfStatement))
3574 return TokError("unexpected token in '.if' directive");
3578 TheCondState.CondMet = ExprValue;
3579 TheCondState.Ignore = !TheCondState.CondMet;
3585 /// parseDirectiveIfb
3587 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3588 TheCondStack.push_back(TheCondState);
3589 TheCondState.TheCond = AsmCond::IfCond;
3591 if (TheCondState.Ignore) {
3592 eatToEndOfStatement();
3594 StringRef Str = parseStringToEndOfStatement();
3596 if (getLexer().isNot(AsmToken::EndOfStatement))
3597 return TokError("unexpected token in '.ifb' directive");
3601 TheCondState.CondMet = ExpectBlank == Str.empty();
3602 TheCondState.Ignore = !TheCondState.CondMet;
3608 /// parseDirectiveIfc
3609 /// ::= .ifc string1, string2
3610 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3611 TheCondStack.push_back(TheCondState);
3612 TheCondState.TheCond = AsmCond::IfCond;
3614 if (TheCondState.Ignore) {
3615 eatToEndOfStatement();
3617 StringRef Str1 = parseStringToComma();
3619 if (getLexer().isNot(AsmToken::Comma))
3620 return TokError("unexpected token in '.ifc' directive");
3624 StringRef Str2 = parseStringToEndOfStatement();
3626 if (getLexer().isNot(AsmToken::EndOfStatement))
3627 return TokError("unexpected token in '.ifc' directive");
3631 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3632 TheCondState.Ignore = !TheCondState.CondMet;
3638 /// parseDirectiveIfdef
3639 /// ::= .ifdef symbol
3640 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3642 TheCondStack.push_back(TheCondState);
3643 TheCondState.TheCond = AsmCond::IfCond;
3645 if (TheCondState.Ignore) {
3646 eatToEndOfStatement();
3648 if (parseIdentifier(Name))
3649 return TokError("expected identifier after '.ifdef'");
3653 MCSymbol *Sym = getContext().LookupSymbol(Name);
3656 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3658 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3659 TheCondState.Ignore = !TheCondState.CondMet;
3665 /// parseDirectiveElseIf
3666 /// ::= .elseif expression
3667 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3668 if (TheCondState.TheCond != AsmCond::IfCond &&
3669 TheCondState.TheCond != AsmCond::ElseIfCond)
3670 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3672 TheCondState.TheCond = AsmCond::ElseIfCond;
3674 bool LastIgnoreState = false;
3675 if (!TheCondStack.empty())
3676 LastIgnoreState = TheCondStack.back().Ignore;
3677 if (LastIgnoreState || TheCondState.CondMet) {
3678 TheCondState.Ignore = true;
3679 eatToEndOfStatement();
3682 if (parseAbsoluteExpression(ExprValue))
3685 if (getLexer().isNot(AsmToken::EndOfStatement))
3686 return TokError("unexpected token in '.elseif' directive");
3689 TheCondState.CondMet = ExprValue;
3690 TheCondState.Ignore = !TheCondState.CondMet;
3696 /// parseDirectiveElse
3698 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3699 if (getLexer().isNot(AsmToken::EndOfStatement))
3700 return TokError("unexpected token in '.else' directive");
3704 if (TheCondState.TheCond != AsmCond::IfCond &&
3705 TheCondState.TheCond != AsmCond::ElseIfCond)
3706 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3708 TheCondState.TheCond = AsmCond::ElseCond;
3709 bool LastIgnoreState = false;
3710 if (!TheCondStack.empty())
3711 LastIgnoreState = TheCondStack.back().Ignore;
3712 if (LastIgnoreState || TheCondState.CondMet)
3713 TheCondState.Ignore = true;
3715 TheCondState.Ignore = false;
3720 /// parseDirectiveEndIf
3722 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3723 if (getLexer().isNot(AsmToken::EndOfStatement))
3724 return TokError("unexpected token in '.endif' directive");
3728 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3729 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3731 if (!TheCondStack.empty()) {
3732 TheCondState = TheCondStack.back();
3733 TheCondStack.pop_back();
3739 void AsmParser::initializeDirectiveKindMap() {
3740 DirectiveKindMap[".set"] = DK_SET;
3741 DirectiveKindMap[".equ"] = DK_EQU;
3742 DirectiveKindMap[".equiv"] = DK_EQUIV;
3743 DirectiveKindMap[".ascii"] = DK_ASCII;
3744 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3745 DirectiveKindMap[".string"] = DK_STRING;
3746 DirectiveKindMap[".byte"] = DK_BYTE;
3747 DirectiveKindMap[".short"] = DK_SHORT;
3748 DirectiveKindMap[".value"] = DK_VALUE;
3749 DirectiveKindMap[".2byte"] = DK_2BYTE;
3750 DirectiveKindMap[".long"] = DK_LONG;
3751 DirectiveKindMap[".int"] = DK_INT;
3752 DirectiveKindMap[".4byte"] = DK_4BYTE;
3753 DirectiveKindMap[".quad"] = DK_QUAD;
3754 DirectiveKindMap[".8byte"] = DK_8BYTE;
3755 DirectiveKindMap[".single"] = DK_SINGLE;
3756 DirectiveKindMap[".float"] = DK_FLOAT;
3757 DirectiveKindMap[".double"] = DK_DOUBLE;
3758 DirectiveKindMap[".align"] = DK_ALIGN;
3759 DirectiveKindMap[".align32"] = DK_ALIGN32;
3760 DirectiveKindMap[".balign"] = DK_BALIGN;
3761 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3762 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3763 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3764 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3765 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3766 DirectiveKindMap[".org"] = DK_ORG;
3767 DirectiveKindMap[".fill"] = DK_FILL;
3768 DirectiveKindMap[".zero"] = DK_ZERO;
3769 DirectiveKindMap[".extern"] = DK_EXTERN;
3770 DirectiveKindMap[".globl"] = DK_GLOBL;
3771 DirectiveKindMap[".global"] = DK_GLOBAL;
3772 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3773 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3774 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3775 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3776 DirectiveKindMap[".reference"] = DK_REFERENCE;
3777 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3778 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3779 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3780 DirectiveKindMap[".comm"] = DK_COMM;
3781 DirectiveKindMap[".common"] = DK_COMMON;
3782 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3783 DirectiveKindMap[".abort"] = DK_ABORT;
3784 DirectiveKindMap[".include"] = DK_INCLUDE;
3785 DirectiveKindMap[".incbin"] = DK_INCBIN;
3786 DirectiveKindMap[".code16"] = DK_CODE16;
3787 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3788 DirectiveKindMap[".rept"] = DK_REPT;
3789 DirectiveKindMap[".irp"] = DK_IRP;
3790 DirectiveKindMap[".irpc"] = DK_IRPC;
3791 DirectiveKindMap[".endr"] = DK_ENDR;
3792 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3793 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3794 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3795 DirectiveKindMap[".if"] = DK_IF;
3796 DirectiveKindMap[".ifb"] = DK_IFB;
3797 DirectiveKindMap[".ifnb"] = DK_IFNB;
3798 DirectiveKindMap[".ifc"] = DK_IFC;
3799 DirectiveKindMap[".ifnc"] = DK_IFNC;
3800 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3801 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3802 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3803 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3804 DirectiveKindMap[".else"] = DK_ELSE;
3805 DirectiveKindMap[".endif"] = DK_ENDIF;
3806 DirectiveKindMap[".skip"] = DK_SKIP;
3807 DirectiveKindMap[".space"] = DK_SPACE;
3808 DirectiveKindMap[".file"] = DK_FILE;
3809 DirectiveKindMap[".line"] = DK_LINE;
3810 DirectiveKindMap[".loc"] = DK_LOC;
3811 DirectiveKindMap[".stabs"] = DK_STABS;
3812 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3813 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3814 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3815 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3816 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3817 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3818 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3819 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3820 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3821 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3822 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3823 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3824 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3825 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3826 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3827 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3828 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3829 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3830 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3831 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3832 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3833 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
3834 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3835 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3836 DirectiveKindMap[".macro"] = DK_MACRO;
3837 DirectiveKindMap[".endm"] = DK_ENDM;
3838 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3839 DirectiveKindMap[".purgem"] = DK_PURGEM;
3842 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
3843 AsmToken EndToken, StartToken = getTok();
3845 unsigned NestLevel = 0;
3847 // Check whether we have reached the end of the file.
3848 if (getLexer().is(AsmToken::Eof)) {
3849 Error(DirectiveLoc, "no matching '.endr' in definition");
3853 if (Lexer.is(AsmToken::Identifier) &&
3854 (getTok().getIdentifier() == ".rept")) {
3858 // Otherwise, check whether we have reached the .endr.
3859 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
3860 if (NestLevel == 0) {
3861 EndToken = getTok();
3863 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3864 TokError("unexpected token in '.endr' directive");
3872 // Otherwise, scan till the end of the statement.
3873 eatToEndOfStatement();
3876 const char *BodyStart = StartToken.getLoc().getPointer();
3877 const char *BodyEnd = EndToken.getLoc().getPointer();
3878 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3880 // We Are Anonymous.
3882 MCAsmMacroParameters Parameters;
3883 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3884 return &MacroLikeBodies.back();
3887 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3888 raw_svector_ostream &OS) {
3891 MemoryBuffer *Instantiation =
3892 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3894 // Create the macro instantiation object and add to the current macro
3895 // instantiation stack.
3896 MacroInstantiation *MI = new MacroInstantiation(
3897 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
3898 ActiveMacros.push_back(MI);
3900 // Jump to the macro instantiation and prime the lexer.
3901 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3902 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3906 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc) {
3908 if (parseAbsoluteExpression(Count))
3909 return TokError("unexpected token in '.rept' directive");
3912 return TokError("Count is negative");
3914 if (Lexer.isNot(AsmToken::EndOfStatement))
3915 return TokError("unexpected token in '.rept' directive");
3917 // Eat the end of statement.
3920 // Lex the rept definition.
3921 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
3925 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3926 // to hold the macro body with substitutions.
3927 SmallString<256> Buf;
3928 MCAsmMacroParameters Parameters;
3929 MCAsmMacroArguments A;
3930 raw_svector_ostream OS(Buf);
3932 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3935 instantiateMacroLikeBody(M, DirectiveLoc, OS);
3940 /// parseDirectiveIrp
3941 /// ::= .irp symbol,values
3942 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
3943 MCAsmMacroParameters Parameters;
3944 MCAsmMacroParameter Parameter;
3946 if (parseIdentifier(Parameter.first))
3947 return TokError("expected identifier in '.irp' directive");
3949 Parameters.push_back(Parameter);
3951 if (Lexer.isNot(AsmToken::Comma))
3952 return TokError("expected comma in '.irp' directive");
3956 MCAsmMacroArguments A;
3957 if (parseMacroArguments(0, A))
3960 // Eat the end of statement.
3963 // Lex the irp definition.
3964 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
3968 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3969 // to hold the macro body with substitutions.
3970 SmallString<256> Buf;
3971 raw_svector_ostream OS(Buf);
3973 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3974 MCAsmMacroArguments Args;
3977 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3981 instantiateMacroLikeBody(M, DirectiveLoc, OS);
3986 /// parseDirectiveIrpc
3987 /// ::= .irpc symbol,values
3988 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
3989 MCAsmMacroParameters Parameters;
3990 MCAsmMacroParameter Parameter;
3992 if (parseIdentifier(Parameter.first))
3993 return TokError("expected identifier in '.irpc' directive");
3995 Parameters.push_back(Parameter);
3997 if (Lexer.isNot(AsmToken::Comma))
3998 return TokError("expected comma in '.irpc' directive");
4002 MCAsmMacroArguments A;
4003 if (parseMacroArguments(0, A))
4006 if (A.size() != 1 || A.front().size() != 1)
4007 return TokError("unexpected token in '.irpc' directive");
4009 // Eat the end of statement.
4012 // Lex the irpc definition.
4013 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4017 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4018 // to hold the macro body with substitutions.
4019 SmallString<256> Buf;
4020 raw_svector_ostream OS(Buf);
4022 StringRef Values = A.front().front().getString();
4023 std::size_t I, End = Values.size();
4024 for (I = 0; I < End; ++I) {
4025 MCAsmMacroArgument Arg;
4026 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4028 MCAsmMacroArguments Args;
4029 Args.push_back(Arg);
4031 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4035 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4040 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4041 if (ActiveMacros.empty())
4042 return TokError("unmatched '.endr' directive");
4044 // The only .repl that should get here are the ones created by
4045 // instantiateMacroLikeBody.
4046 assert(getLexer().is(AsmToken::EndOfStatement));
4052 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4054 const MCExpr *Value;
4055 SMLoc ExprLoc = getLexer().getLoc();
4056 if (parseExpression(Value))
4058 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4060 return Error(ExprLoc, "unexpected expression in _emit");
4061 uint64_t IntValue = MCE->getValue();
4062 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4063 return Error(ExprLoc, "literal value out of range for directive");
4065 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4069 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4070 const MCExpr *Value;
4071 SMLoc ExprLoc = getLexer().getLoc();
4072 if (parseExpression(Value))
4074 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4076 return Error(ExprLoc, "unexpected expression in align");
4077 uint64_t IntValue = MCE->getValue();
4078 if (!isPowerOf2_64(IntValue))
4079 return Error(ExprLoc, "literal value not a power of two greater then zero");
4081 Info.AsmRewrites->push_back(
4082 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4086 // We are comparing pointers, but the pointers are relative to a single string.
4087 // Thus, this should always be deterministic.
4088 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4089 const AsmRewrite *AsmRewriteB) {
4090 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4092 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4095 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4096 // rewrite to the same location. Make sure the SizeDirective rewrite is
4097 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4098 // ensures the sort algorithm is stable.
4099 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4100 AsmRewritePrecedence[AsmRewriteB->Kind])
4103 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4104 AsmRewritePrecedence[AsmRewriteB->Kind])
4106 llvm_unreachable("Unstable rewrite sort.");
4109 bool AsmParser::parseMSInlineAsm(
4110 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4111 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4112 SmallVectorImpl<std::string> &Constraints,
4113 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4114 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4115 SmallVector<void *, 4> InputDecls;
4116 SmallVector<void *, 4> OutputDecls;
4117 SmallVector<bool, 4> InputDeclsAddressOf;
4118 SmallVector<bool, 4> OutputDeclsAddressOf;
4119 SmallVector<std::string, 4> InputConstraints;
4120 SmallVector<std::string, 4> OutputConstraints;
4121 SmallVector<unsigned, 4> ClobberRegs;
4123 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4128 // While we have input, parse each statement.
4129 unsigned InputIdx = 0;
4130 unsigned OutputIdx = 0;
4131 while (getLexer().isNot(AsmToken::Eof)) {
4132 ParseStatementInfo Info(&AsmStrRewrites);
4133 if (parseStatement(Info))
4136 if (Info.ParseError)
4139 if (Info.Opcode == ~0U)
4142 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4144 // Build the list of clobbers, outputs and inputs.
4145 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4146 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4149 if (Operand->isImm())
4152 // Register operand.
4153 if (Operand->isReg() && !Operand->needAddressOf()) {
4154 unsigned NumDefs = Desc.getNumDefs();
4156 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4157 ClobberRegs.push_back(Operand->getReg());
4161 // Expr/Input or Output.
4162 StringRef SymName = Operand->getSymName();
4163 if (SymName.empty())
4166 void *OpDecl = Operand->getOpDecl();
4170 bool isOutput = (i == 1) && Desc.mayStore();
4171 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4174 OutputDecls.push_back(OpDecl);
4175 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4176 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4177 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4179 InputDecls.push_back(OpDecl);
4180 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4181 InputConstraints.push_back(Operand->getConstraint().str());
4182 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4187 // Set the number of Outputs and Inputs.
4188 NumOutputs = OutputDecls.size();
4189 NumInputs = InputDecls.size();
4191 // Set the unique clobbers.
4192 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4193 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4195 Clobbers.assign(ClobberRegs.size(), std::string());
4196 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4197 raw_string_ostream OS(Clobbers[I]);
4198 IP->printRegName(OS, ClobberRegs[I]);
4201 // Merge the various outputs and inputs. Output are expected first.
4202 if (NumOutputs || NumInputs) {
4203 unsigned NumExprs = NumOutputs + NumInputs;
4204 OpDecls.resize(NumExprs);
4205 Constraints.resize(NumExprs);
4206 for (unsigned i = 0; i < NumOutputs; ++i) {
4207 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4208 Constraints[i] = OutputConstraints[i];
4210 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4211 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4212 Constraints[j] = InputConstraints[i];
4216 // Build the IR assembly string.
4217 std::string AsmStringIR;
4218 raw_string_ostream OS(AsmStringIR);
4219 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4220 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4221 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4222 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4223 E = AsmStrRewrites.end();
4225 AsmRewriteKind Kind = (*I).Kind;
4226 if (Kind == AOK_Delete)
4229 const char *Loc = (*I).Loc.getPointer();
4230 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4232 // Emit everything up to the immediate/expression.
4233 unsigned Len = Loc - AsmStart;
4235 OS << StringRef(AsmStart, Len);
4237 // Skip the original expression.
4238 if (Kind == AOK_Skip) {
4239 AsmStart = Loc + (*I).Len;
4243 unsigned AdditionalSkip = 0;
4244 // Rewrite expressions in $N notation.
4249 OS << "$$" << (*I).Val;
4255 OS << '$' << InputIdx++;
4258 OS << '$' << OutputIdx++;
4260 case AOK_SizeDirective:
4263 case 8: OS << "byte ptr "; break;
4264 case 16: OS << "word ptr "; break;
4265 case 32: OS << "dword ptr "; break;
4266 case 64: OS << "qword ptr "; break;
4267 case 80: OS << "xword ptr "; break;
4268 case 128: OS << "xmmword ptr "; break;
4269 case 256: OS << "ymmword ptr "; break;
4276 unsigned Val = (*I).Val;
4277 OS << ".align " << Val;
4279 // Skip the original immediate.
4280 assert(Val < 10 && "Expected alignment less then 2^10.");
4281 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4284 case AOK_DotOperator:
4289 // Skip the original expression.
4290 AsmStart = Loc + (*I).Len + AdditionalSkip;
4293 // Emit the remainder of the asm string.
4294 if (AsmStart != AsmEnd)
4295 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4297 AsmString = OS.str();
4301 /// \brief Create an MCAsmParser instance.
4302 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4303 MCStreamer &Out, const MCAsmInfo &MAI) {
4304 return new AsmParser(SM, C, Out, MAI);