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/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 FatalAssemblerWarnings("fatal-assembler-warnings",
49 cl::desc("Consider warnings as error"));
51 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
55 /// \brief Helper types for tracking macro definitions.
56 typedef std::vector<AsmToken> MCAsmMacroArgument;
57 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
59 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
64 MCAsmMacroParameters Parameters;
67 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
68 Name(N), Body(B), Parameters(P) {}
70 MCAsmMacro(const MCAsmMacro& Other)
71 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
74 /// \brief Helper class for storing information about an active macro
76 struct MacroInstantiation {
77 /// The macro being instantiated.
78 const MCAsmMacro *TheMacro;
80 /// The macro instantiation with substitutions.
81 MemoryBuffer *Instantiation;
83 /// The location of the instantiation.
84 SMLoc InstantiationLoc;
86 /// The buffer where parsing should resume upon instantiation completion.
89 /// The location where parsing should resume upon instantiation completion.
93 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
97 struct ParseStatementInfo {
98 /// \brief The parsed operands from the last parsed statement.
99 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
101 /// \brief The opcode from the last parsed instruction.
104 /// \brief Was there an error parsing the inline assembly?
107 SmallVectorImpl<AsmRewrite> *AsmRewrites;
109 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
110 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
111 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
113 ~ParseStatementInfo() {
114 // Free any parsed operands.
115 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
116 delete ParsedOperands[i];
117 ParsedOperands.clear();
121 /// \brief The concrete assembly parser instance.
122 class AsmParser : public MCAsmParser {
123 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
124 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
129 const MCAsmInfo &MAI;
131 SourceMgr::DiagHandlerTy SavedDiagHandler;
132 void *SavedDiagContext;
133 MCAsmParserExtension *PlatformParser;
135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
139 AsmCond TheCondState;
140 std::vector<AsmCond> TheCondStack;
142 /// \brief maps directive names to handler methods in parser
143 /// extensions. Extensions register themselves in this map by calling
144 /// addDirectiveHandler.
145 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
147 /// \brief Map of currently defined macros.
148 StringMap<MCAsmMacro*> MacroMap;
150 /// \brief Stack of active macro instantiations.
151 std::vector<MacroInstantiation*> ActiveMacros;
153 /// \brief List of bodies of anonymous macros.
154 std::deque<MCAsmMacro> MacroLikeBodies;
156 /// Boolean tracking whether macro substitution is enabled.
157 unsigned MacrosEnabledFlag : 1;
159 /// Flag tracking whether any errors have been encountered.
160 unsigned HadError : 1;
162 /// The values from the last parsed cpp hash file line comment if any.
163 StringRef CppHashFilename;
164 int64_t CppHashLineNumber;
167 /// When generating dwarf for assembly source files we need to calculate the
168 /// logical line number based on the last parsed cpp hash file line comment
169 /// and current line. Since this is slow and messes up the SourceMgr's
170 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
171 SMLoc LastQueryIDLoc;
173 unsigned LastQueryLine;
175 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
176 unsigned AssemblerDialect;
178 /// \brief is Darwin compatibility enabled?
181 /// \brief Are we parsing ms-style inline assembly?
182 bool ParsingInlineAsm;
185 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
186 const MCAsmInfo &MAI);
187 virtual ~AsmParser();
189 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
191 virtual void addDirectiveHandler(StringRef Directive,
192 ExtensionDirectiveHandler Handler) {
193 ExtensionDirectiveMap[Directive] = Handler;
197 /// @name MCAsmParser Interface
200 virtual SourceMgr &getSourceManager() { return SrcMgr; }
201 virtual MCAsmLexer &getLexer() { return Lexer; }
202 virtual MCContext &getContext() { return Ctx; }
203 virtual MCStreamer &getStreamer() { return Out; }
204 virtual unsigned getAssemblerDialect() {
205 if (AssemblerDialect == ~0U)
206 return MAI.getAssemblerDialect();
208 return AssemblerDialect;
210 virtual void setAssemblerDialect(unsigned i) {
211 AssemblerDialect = i;
214 virtual bool Warning(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None);
216 virtual bool Error(SMLoc L, const Twine &Msg,
217 ArrayRef<SMRange> Ranges = None);
219 virtual const AsmToken &Lex();
221 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
222 bool isParsingInlineAsm() { return ParsingInlineAsm; }
224 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
225 unsigned &NumOutputs, unsigned &NumInputs,
226 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
227 SmallVectorImpl<std::string> &Constraints,
228 SmallVectorImpl<std::string> &Clobbers,
229 const MCInstrInfo *MII,
230 const MCInstPrinter *IP,
231 MCAsmParserSemaCallback &SI);
233 bool parseExpression(const MCExpr *&Res);
234 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
235 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
236 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
237 virtual bool parseAbsoluteExpression(int64_t &Res);
239 /// \brief Parse an identifier or string (as a quoted identifier)
240 /// and set \p Res to the identifier contents.
241 virtual bool parseIdentifier(StringRef &Res);
242 virtual void eatToEndOfStatement();
244 virtual void checkForValidSection();
249 bool parseStatement(ParseStatementInfo &Info);
250 void eatToEndOfLine();
251 bool parseCppHashLineFilenameComment(const SMLoc &L);
253 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
254 MCAsmMacroParameters Parameters);
255 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
256 const MCAsmMacroParameters &Parameters,
257 const MCAsmMacroArguments &A,
260 /// \brief Are macros enabled in the parser?
261 bool areMacrosEnabled() {return MacrosEnabledFlag;}
263 /// \brief Control a flag in the parser that enables or disables macros.
264 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
266 /// \brief Lookup a previously defined macro.
267 /// \param Name Macro name.
268 /// \returns Pointer to macro. NULL if no such macro was defined.
269 const MCAsmMacro* lookupMacro(StringRef Name);
271 /// \brief Define a new macro with the given name and information.
272 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
274 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
275 void undefineMacro(StringRef Name);
277 /// \brief Are we inside a macro instantiation?
278 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
280 /// \brief Handle entry to macro instantiation.
282 /// \param M The macro.
283 /// \param NameLoc Instantiation location.
284 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
286 /// \brief Handle exit from macro instantiation.
287 void handleMacroExit();
289 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
290 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
291 /// correct delimiter by the method.
292 bool parseMacroArgument(MCAsmMacroArgument &MA,
293 AsmToken::TokenKind &ArgumentDelimiter);
295 /// \brief Parse all macro arguments for a given macro.
296 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
298 void printMacroInstantiations();
299 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
300 ArrayRef<SMRange> Ranges = None) const {
301 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
303 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
305 /// \brief Enter the specified file. This returns true on failure.
306 bool enterIncludeFile(const std::string &Filename);
308 /// \brief Process the specified file for the .incbin directive.
309 /// This returns true on failure.
310 bool processIncbinFile(const std::string &Filename);
312 /// \brief Reset the current lexer position to that given by \p Loc. The
313 /// current token is not set; clients should ensure Lex() is called
316 /// \param InBuffer If not -1, should be the known buffer id that contains the
318 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
320 /// \brief Parse up to the end of statement and a return the contents from the
321 /// current token until the end of the statement; the current token on exit
322 /// will be either the EndOfStatement or EOF.
323 virtual StringRef parseStringToEndOfStatement();
325 /// \brief Parse until the end of a statement or a comma is encountered,
326 /// return the contents from the current token up to the end or comma.
327 StringRef parseStringToComma();
329 bool parseAssignment(StringRef Name, bool allow_redef,
330 bool NoDeadStrip = false);
332 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
334 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
338 // Generic (target and platform independent) directive parsing.
340 DK_NO_DIRECTIVE, // Placeholder
341 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
342 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
343 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
344 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
345 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
346 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
347 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
348 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
349 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
350 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
351 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
352 DK_ELSEIF, DK_ELSE, DK_ENDIF,
353 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
354 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
355 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
356 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
357 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
358 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
359 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
360 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
361 DK_SLEB128, DK_ULEB128
364 /// \brief Maps directive name --> DirectiveKind enum, for
365 /// directives parsed by this class.
366 StringMap<DirectiveKind> DirectiveKindMap;
368 // ".ascii", ".asciz", ".string"
369 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
370 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
371 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
372 bool parseDirectiveFill(); // ".fill"
373 bool parseDirectiveZero(); // ".zero"
374 // ".set", ".equ", ".equiv"
375 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
376 bool parseDirectiveOrg(); // ".org"
377 // ".align{,32}", ".p2align{,w,l}"
378 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
380 // ".file", ".line", ".loc", ".stabs"
381 bool parseDirectiveFile(SMLoc DirectiveLoc);
382 bool parseDirectiveLine();
383 bool parseDirectiveLoc();
384 bool parseDirectiveStabs();
387 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
388 bool parseDirectiveCFIWindowSave();
389 bool parseDirectiveCFISections();
390 bool parseDirectiveCFIStartProc();
391 bool parseDirectiveCFIEndProc();
392 bool parseDirectiveCFIDefCfaOffset();
393 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
394 bool parseDirectiveCFIAdjustCfaOffset();
395 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
399 bool parseDirectiveCFIRememberState();
400 bool parseDirectiveCFIRestoreState();
401 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIEscape();
404 bool parseDirectiveCFISignalFrame();
405 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
408 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
409 bool parseDirectiveEndMacro(StringRef Directive);
410 bool parseDirectiveMacro(SMLoc DirectiveLoc);
411 bool parseDirectiveMacrosOnOff(StringRef Directive);
413 // ".bundle_align_mode"
414 bool parseDirectiveBundleAlignMode();
416 bool parseDirectiveBundleLock();
418 bool parseDirectiveBundleUnlock();
421 bool parseDirectiveSpace(StringRef IDVal);
423 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
424 bool parseDirectiveLEB128(bool Signed);
426 /// \brief Parse a directive like ".globl" which
427 /// accepts a single symbol (which should be a label or an external).
428 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
430 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
432 bool parseDirectiveAbort(); // ".abort"
433 bool parseDirectiveInclude(); // ".include"
434 bool parseDirectiveIncbin(); // ".incbin"
436 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
437 // ".ifb" or ".ifnb", depending on ExpectBlank.
438 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
439 // ".ifc" or ".ifnc", depending on ExpectEqual.
440 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
441 // ".ifdef" or ".ifndef", depending on expect_defined
442 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
443 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
444 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
445 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
446 virtual bool parseEscapedString(std::string &Data);
448 const MCExpr *applyModifierToExpr(const MCExpr *E,
449 MCSymbolRefExpr::VariantKind Variant);
451 // Macro-like directives
452 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
453 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
454 raw_svector_ostream &OS);
455 bool parseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
456 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
457 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
458 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
460 // "_emit" or "__emit"
461 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
465 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
467 void initializeDirectiveKindMap();
473 extern MCAsmParserExtension *createDarwinAsmParser();
474 extern MCAsmParserExtension *createELFAsmParser();
475 extern MCAsmParserExtension *createCOFFAsmParser();
479 enum { DEFAULT_ADDRSPACE = 0 };
481 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
482 const MCAsmInfo &_MAI)
483 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
484 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
485 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
486 ParsingInlineAsm(false) {
487 // Save the old handler.
488 SavedDiagHandler = SrcMgr.getDiagHandler();
489 SavedDiagContext = SrcMgr.getDiagContext();
490 // Set our own handler which calls the saved handler.
491 SrcMgr.setDiagHandler(DiagHandler, this);
492 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
494 // Initialize the platform / file format parser.
495 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
496 case MCObjectFileInfo::IsCOFF:
497 PlatformParser = createCOFFAsmParser();
498 PlatformParser->Initialize(*this);
500 case MCObjectFileInfo::IsMachO:
501 PlatformParser = createDarwinAsmParser();
502 PlatformParser->Initialize(*this);
505 case MCObjectFileInfo::IsELF:
506 PlatformParser = createELFAsmParser();
507 PlatformParser->Initialize(*this);
511 initializeDirectiveKindMap();
514 AsmParser::~AsmParser() {
515 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
517 // Destroy any macros.
518 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
521 delete it->getValue();
523 delete PlatformParser;
526 void AsmParser::printMacroInstantiations() {
527 // Print the active macro instantiation stack.
528 for (std::vector<MacroInstantiation *>::const_reverse_iterator
529 it = ActiveMacros.rbegin(),
530 ie = ActiveMacros.rend();
532 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
533 "while in macro instantiation");
536 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
537 if (FatalAssemblerWarnings)
538 return Error(L, Msg, Ranges);
539 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
540 printMacroInstantiations();
544 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
546 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
547 printMacroInstantiations();
551 bool AsmParser::enterIncludeFile(const std::string &Filename) {
552 std::string IncludedFile;
553 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
559 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
564 /// Process the specified .incbin file by searching for it in the include paths
565 /// then just emitting the byte contents of the file to the streamer. This
566 /// returns true on failure.
567 bool AsmParser::processIncbinFile(const std::string &Filename) {
568 std::string IncludedFile;
569 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
573 // Pick up the bytes from the file and emit them.
574 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
578 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
579 if (InBuffer != -1) {
580 CurBuffer = InBuffer;
582 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
584 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
587 const AsmToken &AsmParser::Lex() {
588 const AsmToken *tok = &Lexer.Lex();
590 if (tok->is(AsmToken::Eof)) {
591 // If this is the end of an included file, pop the parent file off the
593 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
594 if (ParentIncludeLoc != SMLoc()) {
595 jumpToLoc(ParentIncludeLoc);
600 if (tok->is(AsmToken::Error))
601 Error(Lexer.getErrLoc(), Lexer.getErr());
606 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
607 // Create the initial section, if requested.
608 if (!NoInitialTextSection)
615 AsmCond StartingCondState = TheCondState;
617 // If we are generating dwarf for assembly source files save the initial text
618 // section and generate a .file directive.
619 if (getContext().getGenDwarfForAssembly()) {
620 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
621 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
622 getStreamer().EmitLabel(SectionStartSym);
623 getContext().setGenDwarfSectionStartSym(SectionStartSym);
624 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
626 getContext().getMainFileName());
629 // While we have input, parse each statement.
630 while (Lexer.isNot(AsmToken::Eof)) {
631 ParseStatementInfo Info;
632 if (!parseStatement(Info))
635 // We had an error, validate that one was emitted and recover by skipping to
637 assert(HadError && "Parse statement returned an error, but none emitted!");
638 eatToEndOfStatement();
641 if (TheCondState.TheCond != StartingCondState.TheCond ||
642 TheCondState.Ignore != StartingCondState.Ignore)
643 return TokError("unmatched .ifs or .elses");
645 // Check to see there are no empty DwarfFile slots.
646 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
647 getContext().getMCDwarfFiles();
648 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
649 if (!MCDwarfFiles[i])
650 TokError("unassigned file number: " + Twine(i) + " for .file directives");
653 // Check to see that all assembler local symbols were actually defined.
654 // Targets that don't do subsections via symbols may not want this, though,
655 // so conservatively exclude them. Only do this if we're finalizing, though,
656 // as otherwise we won't necessarilly have seen everything yet.
657 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
658 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
659 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
662 MCSymbol *Sym = i->getValue();
663 // Variable symbols may not be marked as defined, so check those
664 // explicitly. If we know it's a variable, we have a definition for
665 // the purposes of this check.
666 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
667 // FIXME: We would really like to refer back to where the symbol was
668 // first referenced for a source location. We need to add something
669 // to track that. Currently, we just point to the end of the file.
671 getLexer().getLoc(), SourceMgr::DK_Error,
672 "assembler local symbol '" + Sym->getName() + "' not defined");
676 // Finalize the output stream if there are no errors and if the client wants
678 if (!HadError && !NoFinalize)
684 void AsmParser::checkForValidSection() {
685 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
686 TokError("expected section directive before assembly directive");
687 Out.InitToTextSection();
691 /// \brief Throw away the rest of the line for testing purposes.
692 void AsmParser::eatToEndOfStatement() {
693 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
697 if (Lexer.is(AsmToken::EndOfStatement))
701 StringRef AsmParser::parseStringToEndOfStatement() {
702 const char *Start = getTok().getLoc().getPointer();
704 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
707 const char *End = getTok().getLoc().getPointer();
708 return StringRef(Start, End - Start);
711 StringRef AsmParser::parseStringToComma() {
712 const char *Start = getTok().getLoc().getPointer();
714 while (Lexer.isNot(AsmToken::EndOfStatement) &&
715 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
718 const char *End = getTok().getLoc().getPointer();
719 return StringRef(Start, End - Start);
722 /// \brief Parse a paren expression and return it.
723 /// NOTE: This assumes the leading '(' has already been consumed.
725 /// parenexpr ::= expr)
727 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
728 if (parseExpression(Res))
730 if (Lexer.isNot(AsmToken::RParen))
731 return TokError("expected ')' in parentheses expression");
732 EndLoc = Lexer.getTok().getEndLoc();
737 /// \brief Parse a bracket expression and return it.
738 /// NOTE: This assumes the leading '[' has already been consumed.
740 /// bracketexpr ::= expr]
742 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
743 if (parseExpression(Res))
745 if (Lexer.isNot(AsmToken::RBrac))
746 return TokError("expected ']' in brackets expression");
747 EndLoc = Lexer.getTok().getEndLoc();
752 /// \brief Parse a primary expression and return it.
753 /// primaryexpr ::= (parenexpr
754 /// primaryexpr ::= symbol
755 /// primaryexpr ::= number
756 /// primaryexpr ::= '.'
757 /// primaryexpr ::= ~,+,- primaryexpr
758 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
759 SMLoc FirstTokenLoc = getLexer().getLoc();
760 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
761 switch (FirstTokenKind) {
763 return TokError("unknown token in expression");
764 // If we have an error assume that we've already handled it.
765 case AsmToken::Error:
767 case AsmToken::Exclaim:
768 Lex(); // Eat the operator.
769 if (parsePrimaryExpr(Res, EndLoc))
771 Res = MCUnaryExpr::CreateLNot(Res, getContext());
773 case AsmToken::Dollar:
775 case AsmToken::String:
776 case AsmToken::Identifier: {
777 StringRef Identifier;
778 if (parseIdentifier(Identifier)) {
779 if (FirstTokenKind == AsmToken::Dollar) {
780 if (Lexer.getMAI().getDollarIsPC()) {
781 // This is a '$' reference, which references the current PC. Emit a
782 // temporary label to the streamer and refer to it.
783 MCSymbol *Sym = Ctx.CreateTempSymbol();
785 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
787 EndLoc = FirstTokenLoc;
790 return Error(FirstTokenLoc, "invalid token in expression");
794 // Parse symbol variant
795 std::pair<StringRef, StringRef> Split;
796 if (!MAI.useParensForSymbolVariant()) {
797 Split = Identifier.split('@');
798 } else if (Lexer.is(AsmToken::LParen)) {
799 Lexer.Lex(); // eat (
801 parseIdentifier(VName);
802 if (Lexer.isNot(AsmToken::RParen)) {
803 return Error(Lexer.getTok().getLoc(),
804 "unexpected token in variant, expected ')'");
806 Lexer.Lex(); // eat )
807 Split = std::make_pair(Identifier, VName);
810 EndLoc = SMLoc::getFromPointer(Identifier.end());
812 // This is a symbol reference.
813 StringRef SymbolName = Identifier;
814 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
816 // Lookup the symbol variant if used.
817 if (Split.second.size()) {
818 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
819 if (Variant != MCSymbolRefExpr::VK_Invalid) {
820 SymbolName = Split.first;
821 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
822 Variant = MCSymbolRefExpr::VK_None;
824 Variant = MCSymbolRefExpr::VK_None;
825 return TokError("invalid variant '" + Split.second + "'");
829 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
831 // If this is an absolute variable reference, substitute it now to preserve
832 // semantics in the face of reassignment.
833 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
835 return Error(EndLoc, "unexpected modifier on variable reference");
837 Res = Sym->getVariableValue();
841 // Otherwise create a symbol ref.
842 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
845 case AsmToken::Integer: {
846 SMLoc Loc = getTok().getLoc();
847 int64_t IntVal = getTok().getIntVal();
848 Res = MCConstantExpr::Create(IntVal, getContext());
849 EndLoc = Lexer.getTok().getEndLoc();
851 // Look for 'b' or 'f' following an Integer as a directional label
852 if (Lexer.getKind() == AsmToken::Identifier) {
853 StringRef IDVal = getTok().getString();
854 // Lookup the symbol variant if used.
855 std::pair<StringRef, StringRef> Split = IDVal.split('@');
856 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
857 if (Split.first.size() != IDVal.size()) {
858 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
859 if (Variant == MCSymbolRefExpr::VK_Invalid) {
860 Variant = MCSymbolRefExpr::VK_None;
861 return TokError("invalid variant '" + Split.second + "'");
865 if (IDVal == "f" || IDVal == "b") {
867 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
868 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
869 if (IDVal == "b" && Sym->isUndefined())
870 return Error(Loc, "invalid reference to undefined symbol");
871 EndLoc = Lexer.getTok().getEndLoc();
872 Lex(); // Eat identifier.
877 case AsmToken::Real: {
878 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
879 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
880 Res = MCConstantExpr::Create(IntVal, getContext());
881 EndLoc = Lexer.getTok().getEndLoc();
885 case AsmToken::Dot: {
886 // This is a '.' reference, which references the current PC. Emit a
887 // temporary label to the streamer and refer to it.
888 MCSymbol *Sym = Ctx.CreateTempSymbol();
890 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
891 EndLoc = Lexer.getTok().getEndLoc();
892 Lex(); // Eat identifier.
895 case AsmToken::LParen:
896 Lex(); // Eat the '('.
897 return parseParenExpr(Res, EndLoc);
898 case AsmToken::LBrac:
899 if (!PlatformParser->HasBracketExpressions())
900 return TokError("brackets expression not supported on this target");
901 Lex(); // Eat the '['.
902 return parseBracketExpr(Res, EndLoc);
903 case AsmToken::Minus:
904 Lex(); // Eat the operator.
905 if (parsePrimaryExpr(Res, EndLoc))
907 Res = MCUnaryExpr::CreateMinus(Res, getContext());
910 Lex(); // Eat the operator.
911 if (parsePrimaryExpr(Res, EndLoc))
913 Res = MCUnaryExpr::CreatePlus(Res, getContext());
915 case AsmToken::Tilde:
916 Lex(); // Eat the operator.
917 if (parsePrimaryExpr(Res, EndLoc))
919 Res = MCUnaryExpr::CreateNot(Res, getContext());
924 bool AsmParser::parseExpression(const MCExpr *&Res) {
926 return parseExpression(Res, EndLoc);
930 AsmParser::applyModifierToExpr(const MCExpr *E,
931 MCSymbolRefExpr::VariantKind Variant) {
932 // Ask the target implementation about this expression first.
933 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
936 // Recurse over the given expression, rebuilding it to apply the given variant
937 // if there is exactly one symbol.
938 switch (E->getKind()) {
940 case MCExpr::Constant:
943 case MCExpr::SymbolRef: {
944 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
946 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
947 TokError("invalid variant on expression '" + getTok().getIdentifier() +
948 "' (already modified)");
952 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
955 case MCExpr::Unary: {
956 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
957 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
960 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
963 case MCExpr::Binary: {
964 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
965 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
966 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
976 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
980 llvm_unreachable("Invalid expression kind!");
983 /// \brief Parse an expression and return it.
985 /// expr ::= expr &&,|| expr -> lowest.
986 /// expr ::= expr |,^,&,! expr
987 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
988 /// expr ::= expr <<,>> expr
989 /// expr ::= expr +,- expr
990 /// expr ::= expr *,/,% expr -> highest.
991 /// expr ::= primaryexpr
993 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
994 // Parse the expression.
996 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
999 // As a special case, we support 'a op b @ modifier' by rewriting the
1000 // expression to include the modifier. This is inefficient, but in general we
1001 // expect users to use 'a@modifier op b'.
1002 if (Lexer.getKind() == AsmToken::At) {
1005 if (Lexer.isNot(AsmToken::Identifier))
1006 return TokError("unexpected symbol modifier following '@'");
1008 MCSymbolRefExpr::VariantKind Variant =
1009 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1010 if (Variant == MCSymbolRefExpr::VK_Invalid)
1011 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1013 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1015 return TokError("invalid modifier '" + getTok().getIdentifier() +
1016 "' (no symbols present)");
1023 // Try to constant fold it up front, if possible.
1025 if (Res->EvaluateAsAbsolute(Value))
1026 Res = MCConstantExpr::Create(Value, getContext());
1031 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1033 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1036 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1039 SMLoc StartLoc = Lexer.getLoc();
1040 if (parseExpression(Expr))
1043 if (!Expr->EvaluateAsAbsolute(Res))
1044 return Error(StartLoc, "expected absolute expression");
1049 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1050 MCBinaryExpr::Opcode &Kind) {
1053 return 0; // not a binop.
1055 // Lowest Precedence: &&, ||
1056 case AsmToken::AmpAmp:
1057 Kind = MCBinaryExpr::LAnd;
1059 case AsmToken::PipePipe:
1060 Kind = MCBinaryExpr::LOr;
1063 // Low Precedence: |, &, ^
1065 // FIXME: gas seems to support '!' as an infix operator?
1066 case AsmToken::Pipe:
1067 Kind = MCBinaryExpr::Or;
1069 case AsmToken::Caret:
1070 Kind = MCBinaryExpr::Xor;
1073 Kind = MCBinaryExpr::And;
1076 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1077 case AsmToken::EqualEqual:
1078 Kind = MCBinaryExpr::EQ;
1080 case AsmToken::ExclaimEqual:
1081 case AsmToken::LessGreater:
1082 Kind = MCBinaryExpr::NE;
1084 case AsmToken::Less:
1085 Kind = MCBinaryExpr::LT;
1087 case AsmToken::LessEqual:
1088 Kind = MCBinaryExpr::LTE;
1090 case AsmToken::Greater:
1091 Kind = MCBinaryExpr::GT;
1093 case AsmToken::GreaterEqual:
1094 Kind = MCBinaryExpr::GTE;
1097 // Intermediate Precedence: <<, >>
1098 case AsmToken::LessLess:
1099 Kind = MCBinaryExpr::Shl;
1101 case AsmToken::GreaterGreater:
1102 Kind = MCBinaryExpr::Shr;
1105 // High Intermediate Precedence: +, -
1106 case AsmToken::Plus:
1107 Kind = MCBinaryExpr::Add;
1109 case AsmToken::Minus:
1110 Kind = MCBinaryExpr::Sub;
1113 // Highest Precedence: *, /, %
1114 case AsmToken::Star:
1115 Kind = MCBinaryExpr::Mul;
1117 case AsmToken::Slash:
1118 Kind = MCBinaryExpr::Div;
1120 case AsmToken::Percent:
1121 Kind = MCBinaryExpr::Mod;
1126 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1127 /// Res contains the LHS of the expression on input.
1128 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1131 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1132 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1134 // If the next token is lower precedence than we are allowed to eat, return
1135 // successfully with what we ate already.
1136 if (TokPrec < Precedence)
1141 // Eat the next primary expression.
1143 if (parsePrimaryExpr(RHS, EndLoc))
1146 // If BinOp binds less tightly with RHS than the operator after RHS, let
1147 // the pending operator take RHS as its LHS.
1148 MCBinaryExpr::Opcode Dummy;
1149 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1150 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1153 // Merge LHS and RHS according to operator.
1154 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1159 /// ::= EndOfStatement
1160 /// ::= Label* Directive ...Operands... EndOfStatement
1161 /// ::= Label* Identifier OperandList* EndOfStatement
1162 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1163 if (Lexer.is(AsmToken::EndOfStatement)) {
1169 // Statements always start with an identifier or are a full line comment.
1170 AsmToken ID = getTok();
1171 SMLoc IDLoc = ID.getLoc();
1173 int64_t LocalLabelVal = -1;
1174 // A full line comment is a '#' as the first token.
1175 if (Lexer.is(AsmToken::Hash))
1176 return parseCppHashLineFilenameComment(IDLoc);
1178 // Allow an integer followed by a ':' as a directional local label.
1179 if (Lexer.is(AsmToken::Integer)) {
1180 LocalLabelVal = getTok().getIntVal();
1181 if (LocalLabelVal < 0) {
1182 if (!TheCondState.Ignore)
1183 return TokError("unexpected token at start of statement");
1186 IDVal = getTok().getString();
1187 Lex(); // Consume the integer token to be used as an identifier token.
1188 if (Lexer.getKind() != AsmToken::Colon) {
1189 if (!TheCondState.Ignore)
1190 return TokError("unexpected token at start of statement");
1193 } else if (Lexer.is(AsmToken::Dot)) {
1194 // Treat '.' as a valid identifier in this context.
1197 } else if (parseIdentifier(IDVal)) {
1198 if (!TheCondState.Ignore)
1199 return TokError("unexpected token at start of statement");
1203 // Handle conditional assembly here before checking for skipping. We
1204 // have to do this so that .endif isn't skipped in a ".if 0" block for
1206 StringMap<DirectiveKind>::const_iterator DirKindIt =
1207 DirectiveKindMap.find(IDVal);
1208 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1210 : DirKindIt->getValue();
1215 return parseDirectiveIf(IDLoc);
1217 return parseDirectiveIfb(IDLoc, true);
1219 return parseDirectiveIfb(IDLoc, false);
1221 return parseDirectiveIfc(IDLoc, true);
1223 return parseDirectiveIfc(IDLoc, false);
1225 return parseDirectiveIfdef(IDLoc, true);
1228 return parseDirectiveIfdef(IDLoc, false);
1230 return parseDirectiveElseIf(IDLoc);
1232 return parseDirectiveElse(IDLoc);
1234 return parseDirectiveEndIf(IDLoc);
1237 // Ignore the statement if in the middle of inactive conditional
1239 if (TheCondState.Ignore) {
1240 eatToEndOfStatement();
1244 // FIXME: Recurse on local labels?
1246 // See what kind of statement we have.
1247 switch (Lexer.getKind()) {
1248 case AsmToken::Colon: {
1249 checkForValidSection();
1251 // identifier ':' -> Label.
1254 // Diagnose attempt to use '.' as a label.
1256 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1258 // Diagnose attempt to use a variable as a label.
1260 // FIXME: Diagnostics. Note the location of the definition as a label.
1261 // FIXME: This doesn't diagnose assignment to a symbol which has been
1262 // implicitly marked as external.
1264 if (LocalLabelVal == -1)
1265 Sym = getContext().GetOrCreateSymbol(IDVal);
1267 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1268 if (!Sym->isUndefined() || Sym->isVariable())
1269 return Error(IDLoc, "invalid symbol redefinition");
1272 if (!ParsingInlineAsm)
1275 // If we are generating dwarf for assembly source files then gather the
1276 // info to make a dwarf label entry for this label if needed.
1277 if (getContext().getGenDwarfForAssembly())
1278 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1281 getTargetParser().onLabelParsed(Sym);
1283 // Consume any end of statement token, if present, to avoid spurious
1284 // AddBlankLine calls().
1285 if (Lexer.is(AsmToken::EndOfStatement)) {
1287 if (Lexer.is(AsmToken::Eof))
1294 case AsmToken::Equal:
1295 // identifier '=' ... -> assignment statement
1298 return parseAssignment(IDVal, true);
1300 default: // Normal instruction or directive.
1304 // If macros are enabled, check to see if this is a macro instantiation.
1305 if (areMacrosEnabled())
1306 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1307 return handleMacroEntry(M, IDLoc);
1310 // Otherwise, we have a normal instruction or directive.
1312 // Directives start with "."
1313 if (IDVal[0] == '.' && IDVal != ".") {
1314 // There are several entities interested in parsing directives:
1316 // 1. The target-specific assembly parser. Some directives are target
1317 // specific or may potentially behave differently on certain targets.
1318 // 2. Asm parser extensions. For example, platform-specific parsers
1319 // (like the ELF parser) register themselves as extensions.
1320 // 3. The generic directive parser implemented by this class. These are
1321 // all the directives that behave in a target and platform independent
1322 // manner, or at least have a default behavior that's shared between
1323 // all targets and platforms.
1325 // First query the target-specific parser. It will return 'true' if it
1326 // isn't interested in this directive.
1327 if (!getTargetParser().ParseDirective(ID))
1330 // Next, check the extention directive map to see if any extension has
1331 // registered itself to parse this directive.
1332 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1333 ExtensionDirectiveMap.lookup(IDVal);
1335 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1337 // Finally, if no one else is interested in this directive, it must be
1338 // generic and familiar to this class.
1344 return parseDirectiveSet(IDVal, true);
1346 return parseDirectiveSet(IDVal, false);
1348 return parseDirectiveAscii(IDVal, false);
1351 return parseDirectiveAscii(IDVal, true);
1353 return parseDirectiveValue(1);
1357 return parseDirectiveValue(2);
1361 return parseDirectiveValue(4);
1364 return parseDirectiveValue(8);
1367 return parseDirectiveRealValue(APFloat::IEEEsingle);
1369 return parseDirectiveRealValue(APFloat::IEEEdouble);
1371 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1372 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1375 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1376 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1379 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1381 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1383 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1385 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1387 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1389 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1391 return parseDirectiveOrg();
1393 return parseDirectiveFill();
1395 return parseDirectiveZero();
1397 eatToEndOfStatement(); // .extern is the default, ignore it.
1401 return parseDirectiveSymbolAttribute(MCSA_Global);
1402 case DK_LAZY_REFERENCE:
1403 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1404 case DK_NO_DEAD_STRIP:
1405 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1406 case DK_SYMBOL_RESOLVER:
1407 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1408 case DK_PRIVATE_EXTERN:
1409 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1411 return parseDirectiveSymbolAttribute(MCSA_Reference);
1412 case DK_WEAK_DEFINITION:
1413 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1414 case DK_WEAK_REFERENCE:
1415 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1416 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1417 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1420 return parseDirectiveComm(/*IsLocal=*/false);
1422 return parseDirectiveComm(/*IsLocal=*/true);
1424 return parseDirectiveAbort();
1426 return parseDirectiveInclude();
1428 return parseDirectiveIncbin();
1431 return TokError(Twine(IDVal) + " not supported yet");
1433 return parseDirectiveRept(IDLoc);
1435 return parseDirectiveIrp(IDLoc);
1437 return parseDirectiveIrpc(IDLoc);
1439 return parseDirectiveEndr(IDLoc);
1440 case DK_BUNDLE_ALIGN_MODE:
1441 return parseDirectiveBundleAlignMode();
1442 case DK_BUNDLE_LOCK:
1443 return parseDirectiveBundleLock();
1444 case DK_BUNDLE_UNLOCK:
1445 return parseDirectiveBundleUnlock();
1447 return parseDirectiveLEB128(true);
1449 return parseDirectiveLEB128(false);
1452 return parseDirectiveSpace(IDVal);
1454 return parseDirectiveFile(IDLoc);
1456 return parseDirectiveLine();
1458 return parseDirectiveLoc();
1460 return parseDirectiveStabs();
1461 case DK_CFI_SECTIONS:
1462 return parseDirectiveCFISections();
1463 case DK_CFI_STARTPROC:
1464 return parseDirectiveCFIStartProc();
1465 case DK_CFI_ENDPROC:
1466 return parseDirectiveCFIEndProc();
1467 case DK_CFI_DEF_CFA:
1468 return parseDirectiveCFIDefCfa(IDLoc);
1469 case DK_CFI_DEF_CFA_OFFSET:
1470 return parseDirectiveCFIDefCfaOffset();
1471 case DK_CFI_ADJUST_CFA_OFFSET:
1472 return parseDirectiveCFIAdjustCfaOffset();
1473 case DK_CFI_DEF_CFA_REGISTER:
1474 return parseDirectiveCFIDefCfaRegister(IDLoc);
1476 return parseDirectiveCFIOffset(IDLoc);
1477 case DK_CFI_REL_OFFSET:
1478 return parseDirectiveCFIRelOffset(IDLoc);
1479 case DK_CFI_PERSONALITY:
1480 return parseDirectiveCFIPersonalityOrLsda(true);
1482 return parseDirectiveCFIPersonalityOrLsda(false);
1483 case DK_CFI_REMEMBER_STATE:
1484 return parseDirectiveCFIRememberState();
1485 case DK_CFI_RESTORE_STATE:
1486 return parseDirectiveCFIRestoreState();
1487 case DK_CFI_SAME_VALUE:
1488 return parseDirectiveCFISameValue(IDLoc);
1489 case DK_CFI_RESTORE:
1490 return parseDirectiveCFIRestore(IDLoc);
1492 return parseDirectiveCFIEscape();
1493 case DK_CFI_SIGNAL_FRAME:
1494 return parseDirectiveCFISignalFrame();
1495 case DK_CFI_UNDEFINED:
1496 return parseDirectiveCFIUndefined(IDLoc);
1497 case DK_CFI_REGISTER:
1498 return parseDirectiveCFIRegister(IDLoc);
1499 case DK_CFI_WINDOW_SAVE:
1500 return parseDirectiveCFIWindowSave();
1503 return parseDirectiveMacrosOnOff(IDVal);
1505 return parseDirectiveMacro(IDLoc);
1508 return parseDirectiveEndMacro(IDVal);
1510 return parseDirectivePurgeMacro(IDLoc);
1513 return Error(IDLoc, "unknown directive");
1516 // __asm _emit or __asm __emit
1517 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1518 IDVal == "_EMIT" || IDVal == "__EMIT"))
1519 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1522 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1523 return parseDirectiveMSAlign(IDLoc, Info);
1525 checkForValidSection();
1527 // Canonicalize the opcode to lower case.
1528 std::string OpcodeStr = IDVal.lower();
1529 ParseInstructionInfo IInfo(Info.AsmRewrites);
1530 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1531 Info.ParsedOperands);
1532 Info.ParseError = HadError;
1534 // Dump the parsed representation, if requested.
1535 if (getShowParsedOperands()) {
1536 SmallString<256> Str;
1537 raw_svector_ostream OS(Str);
1538 OS << "parsed instruction: [";
1539 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1542 Info.ParsedOperands[i]->print(OS);
1546 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1549 // If we are generating dwarf for assembly source files and the current
1550 // section is the initial text section then generate a .loc directive for
1552 if (!HadError && getContext().getGenDwarfForAssembly() &&
1553 getContext().getGenDwarfSection() ==
1554 getStreamer().getCurrentSection().first) {
1556 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1558 // If we previously parsed a cpp hash file line comment then make sure the
1559 // current Dwarf File is for the CppHashFilename if not then emit the
1560 // Dwarf File table for it and adjust the line number for the .loc.
1561 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1562 getContext().getMCDwarfFiles();
1563 if (CppHashFilename.size() != 0) {
1564 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1566 getStreamer().EmitDwarfFileDirective(
1567 getContext().nextGenDwarfFileNumber(), StringRef(),
1570 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1571 // cache with the different Loc from the call above we save the last
1572 // info we queried here with SrcMgr.FindLineNumber().
1573 unsigned CppHashLocLineNo;
1574 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1575 CppHashLocLineNo = LastQueryLine;
1577 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1578 LastQueryLine = CppHashLocLineNo;
1579 LastQueryIDLoc = CppHashLoc;
1580 LastQueryBuffer = CppHashBuf;
1582 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1585 getStreamer().EmitDwarfLocDirective(
1586 getContext().getGenDwarfFileNumber(), Line, 0,
1587 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1591 // If parsing succeeded, match the instruction.
1594 HadError = getTargetParser().MatchAndEmitInstruction(
1595 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1599 // Don't skip the rest of the line, the instruction parser is responsible for
1604 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1605 /// since they may not be able to be tokenized to get to the end of line token.
1606 void AsmParser::eatToEndOfLine() {
1607 if (!Lexer.is(AsmToken::EndOfStatement))
1608 Lexer.LexUntilEndOfLine();
1613 /// parseCppHashLineFilenameComment as this:
1614 /// ::= # number "filename"
1615 /// or just as a full line comment if it doesn't have a number and a string.
1616 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1617 Lex(); // Eat the hash token.
1619 if (getLexer().isNot(AsmToken::Integer)) {
1620 // Consume the line since in cases it is not a well-formed line directive,
1621 // as if were simply a full line comment.
1626 int64_t LineNumber = getTok().getIntVal();
1629 if (getLexer().isNot(AsmToken::String)) {
1634 StringRef Filename = getTok().getString();
1635 // Get rid of the enclosing quotes.
1636 Filename = Filename.substr(1, Filename.size() - 2);
1638 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1640 CppHashFilename = Filename;
1641 CppHashLineNumber = LineNumber;
1642 CppHashBuf = CurBuffer;
1644 // Ignore any trailing characters, they're just comment.
1649 /// \brief will use the last parsed cpp hash line filename comment
1650 /// for the Filename and LineNo if any in the diagnostic.
1651 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1652 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1653 raw_ostream &OS = errs();
1655 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1656 const SMLoc &DiagLoc = Diag.getLoc();
1657 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1658 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1660 // Like SourceMgr::printMessage() we need to print the include stack if any
1661 // before printing the message.
1662 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1663 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1664 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1665 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1668 // If we have not parsed a cpp hash line filename comment or the source
1669 // manager changed or buffer changed (like in a nested include) then just
1670 // print the normal diagnostic using its Filename and LineNo.
1671 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1672 DiagBuf != CppHashBuf) {
1673 if (Parser->SavedDiagHandler)
1674 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1680 // Use the CppHashFilename and calculate a line number based on the
1681 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1683 const std::string &Filename = Parser->CppHashFilename;
1685 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1686 int CppHashLocLineNo =
1687 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1689 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1691 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1692 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1693 Diag.getLineContents(), Diag.getRanges());
1695 if (Parser->SavedDiagHandler)
1696 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1698 NewDiag.print(0, OS);
1701 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1702 // difference being that that function accepts '@' as part of identifiers and
1703 // we can't do that. AsmLexer.cpp should probably be changed to handle
1704 // '@' as a special case when needed.
1705 static bool isIdentifierChar(char c) {
1706 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1710 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1711 const MCAsmMacroParameters &Parameters,
1712 const MCAsmMacroArguments &A, const SMLoc &L) {
1713 unsigned NParameters = Parameters.size();
1714 if (NParameters != 0 && NParameters != A.size())
1715 return Error(L, "Wrong number of arguments");
1717 // A macro without parameters is handled differently on Darwin:
1718 // gas accepts no arguments and does no substitutions
1719 while (!Body.empty()) {
1720 // Scan for the next substitution.
1721 std::size_t End = Body.size(), Pos = 0;
1722 for (; Pos != End; ++Pos) {
1723 // Check for a substitution or escape.
1725 // This macro has no parameters, look for $0, $1, etc.
1726 if (Body[Pos] != '$' || Pos + 1 == End)
1729 char Next = Body[Pos + 1];
1730 if (Next == '$' || Next == 'n' ||
1731 isdigit(static_cast<unsigned char>(Next)))
1734 // This macro has parameters, look for \foo, \bar, etc.
1735 if (Body[Pos] == '\\' && Pos + 1 != End)
1741 OS << Body.slice(0, Pos);
1743 // Check if we reached the end.
1748 switch (Body[Pos + 1]) {
1754 // $n => number of arguments
1759 // $[0-9] => argument
1761 // Missing arguments are ignored.
1762 unsigned Index = Body[Pos + 1] - '0';
1763 if (Index >= A.size())
1766 // Otherwise substitute with the token values, with spaces eliminated.
1767 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1768 ie = A[Index].end();
1770 OS << it->getString();
1776 unsigned I = Pos + 1;
1777 while (isIdentifierChar(Body[I]) && I + 1 != End)
1780 const char *Begin = Body.data() + Pos + 1;
1781 StringRef Argument(Begin, I - (Pos + 1));
1783 for (; Index < NParameters; ++Index)
1784 if (Parameters[Index].first == Argument)
1787 if (Index == NParameters) {
1788 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1791 OS << '\\' << Argument;
1795 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1796 ie = A[Index].end();
1798 if (it->getKind() == AsmToken::String)
1799 OS << it->getStringContents();
1801 OS << it->getString();
1803 Pos += 1 + Argument.size();
1806 // Update the scan point.
1807 Body = Body.substr(Pos);
1813 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1814 SMLoc EL, MemoryBuffer *I)
1815 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1818 static bool isOperator(AsmToken::TokenKind kind) {
1822 case AsmToken::Plus:
1823 case AsmToken::Minus:
1824 case AsmToken::Tilde:
1825 case AsmToken::Slash:
1826 case AsmToken::Star:
1828 case AsmToken::Equal:
1829 case AsmToken::EqualEqual:
1830 case AsmToken::Pipe:
1831 case AsmToken::PipePipe:
1832 case AsmToken::Caret:
1834 case AsmToken::AmpAmp:
1835 case AsmToken::Exclaim:
1836 case AsmToken::ExclaimEqual:
1837 case AsmToken::Percent:
1838 case AsmToken::Less:
1839 case AsmToken::LessEqual:
1840 case AsmToken::LessLess:
1841 case AsmToken::LessGreater:
1842 case AsmToken::Greater:
1843 case AsmToken::GreaterEqual:
1844 case AsmToken::GreaterGreater:
1849 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA,
1850 AsmToken::TokenKind &ArgumentDelimiter) {
1851 unsigned ParenLevel = 0;
1852 unsigned AddTokens = 0;
1854 // gas accepts arguments separated by whitespace, except on Darwin
1856 Lexer.setSkipSpace(false);
1859 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1860 Lexer.setSkipSpace(true);
1861 return TokError("unexpected token in macro instantiation");
1864 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1865 // Spaces and commas cannot be mixed to delimit parameters
1866 if (ArgumentDelimiter == AsmToken::Eof)
1867 ArgumentDelimiter = AsmToken::Comma;
1868 else if (ArgumentDelimiter != AsmToken::Comma) {
1869 Lexer.setSkipSpace(true);
1870 return TokError("expected ' ' for macro argument separator");
1875 if (Lexer.is(AsmToken::Space)) {
1876 Lex(); // Eat spaces
1878 // Spaces can delimit parameters, but could also be part an expression.
1879 // If the token after a space is an operator, add the token and the next
1880 // one into this argument
1881 if (ArgumentDelimiter == AsmToken::Space ||
1882 ArgumentDelimiter == AsmToken::Eof) {
1883 if (isOperator(Lexer.getKind())) {
1884 // Check to see whether the token is used as an operator,
1885 // or part of an identifier
1886 const char *NextChar = getTok().getEndLoc().getPointer();
1887 if (*NextChar == ' ')
1891 if (!AddTokens && ParenLevel == 0) {
1892 if (ArgumentDelimiter == AsmToken::Eof &&
1893 !isOperator(Lexer.getKind()))
1894 ArgumentDelimiter = AsmToken::Space;
1900 // handleMacroEntry relies on not advancing the lexer here
1901 // to be able to fill in the remaining default parameter values
1902 if (Lexer.is(AsmToken::EndOfStatement))
1905 // Adjust the current parentheses level.
1906 if (Lexer.is(AsmToken::LParen))
1908 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1911 // Append the token to the current argument list.
1912 MA.push_back(getTok());
1918 Lexer.setSkipSpace(true);
1919 if (ParenLevel != 0)
1920 return TokError("unbalanced parentheses in macro argument");
1924 // Parse the macro instantiation arguments.
1925 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1926 MCAsmMacroArguments &A) {
1927 const unsigned NParameters = M ? M->Parameters.size() : 0;
1928 // Argument delimiter is initially unknown. It will be set by
1929 // parseMacroArgument()
1930 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1932 // Parse two kinds of macro invocations:
1933 // - macros defined without any parameters accept an arbitrary number of them
1934 // - macros defined with parameters accept at most that many of them
1935 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1937 MCAsmMacroArgument MA;
1939 if (parseMacroArgument(MA, ArgumentDelimiter))
1942 if (!MA.empty() || !NParameters)
1944 else if (NParameters) {
1945 if (!M->Parameters[Parameter].second.empty())
1946 A.push_back(M->Parameters[Parameter].second);
1949 // At the end of the statement, fill in remaining arguments that have
1950 // default values. If there aren't any, then the next argument is
1951 // required but missing
1952 if (Lexer.is(AsmToken::EndOfStatement)) {
1953 if (NParameters && Parameter < NParameters - 1) {
1954 if (M->Parameters[Parameter + 1].second.empty())
1955 return TokError("macro argument '" +
1956 Twine(M->Parameters[Parameter + 1].first) +
1964 if (Lexer.is(AsmToken::Comma))
1967 return TokError("Too many arguments");
1970 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
1971 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1972 return (I == MacroMap.end()) ? NULL : I->getValue();
1975 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
1976 MacroMap[Name] = new MCAsmMacro(Macro);
1979 void AsmParser::undefineMacro(StringRef Name) {
1980 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1981 if (I != MacroMap.end()) {
1982 delete I->getValue();
1987 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1988 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1989 // this, although we should protect against infinite loops.
1990 if (ActiveMacros.size() == 20)
1991 return TokError("macros cannot be nested more than 20 levels deep");
1993 MCAsmMacroArguments A;
1994 if (parseMacroArguments(M, A))
1997 // Remove any trailing empty arguments. Do this after-the-fact as we have
1998 // to keep empty arguments in the middle of the list or positionality
1999 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
2000 while (!A.empty() && A.back().empty())
2003 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2004 // to hold the macro body with substitutions.
2005 SmallString<256> Buf;
2006 StringRef Body = M->Body;
2007 raw_svector_ostream OS(Buf);
2009 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2012 // We include the .endmacro in the buffer as our cue to exit the macro
2014 OS << ".endmacro\n";
2016 MemoryBuffer *Instantiation =
2017 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2019 // Create the macro instantiation object and add to the current macro
2020 // instantiation stack.
2021 MacroInstantiation *MI = new MacroInstantiation(
2022 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2023 ActiveMacros.push_back(MI);
2025 // Jump to the macro instantiation and prime the lexer.
2026 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2027 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2033 void AsmParser::handleMacroExit() {
2034 // Jump to the EndOfStatement we should return to, and consume it.
2035 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2038 // Pop the instantiation entry.
2039 delete ActiveMacros.back();
2040 ActiveMacros.pop_back();
2043 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2044 switch (Value->getKind()) {
2045 case MCExpr::Binary: {
2046 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2047 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2049 case MCExpr::Target:
2050 case MCExpr::Constant:
2052 case MCExpr::SymbolRef: {
2054 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2056 return isUsedIn(Sym, S.getVariableValue());
2060 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2063 llvm_unreachable("Unknown expr kind!");
2066 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2068 // FIXME: Use better location, we should use proper tokens.
2069 SMLoc EqualLoc = Lexer.getLoc();
2071 const MCExpr *Value;
2072 if (parseExpression(Value))
2075 // Note: we don't count b as used in "a = b". This is to allow
2079 if (Lexer.isNot(AsmToken::EndOfStatement))
2080 return TokError("unexpected token in assignment");
2082 // Error on assignment to '.'.
2084 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2085 "(use '.space' or '.org').)"));
2088 // Eat the end of statement marker.
2091 // Validate that the LHS is allowed to be a variable (either it has not been
2092 // used as a symbol, or it is an absolute symbol).
2093 MCSymbol *Sym = getContext().LookupSymbol(Name);
2095 // Diagnose assignment to a label.
2097 // FIXME: Diagnostics. Note the location of the definition as a label.
2098 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2099 if (isUsedIn(Sym, Value))
2100 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2101 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2102 ; // Allow redefinitions of undefined symbols only used in directives.
2103 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2104 ; // Allow redefinitions of variables that haven't yet been used.
2105 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2106 return Error(EqualLoc, "redefinition of '" + Name + "'");
2107 else if (!Sym->isVariable())
2108 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2109 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2110 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2113 // Don't count these checks as uses.
2114 Sym->setUsed(false);
2116 Sym = getContext().GetOrCreateSymbol(Name);
2118 // FIXME: Handle '.'.
2120 // Do the assignment.
2121 Out.EmitAssignment(Sym, Value);
2123 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2128 /// parseIdentifier:
2131 bool AsmParser::parseIdentifier(StringRef &Res) {
2132 // The assembler has relaxed rules for accepting identifiers, in particular we
2133 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2134 // separate tokens. At this level, we have already lexed so we cannot (currently)
2135 // handle this as a context dependent token, instead we detect adjacent tokens
2136 // and return the combined identifier.
2137 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2138 SMLoc PrefixLoc = getLexer().getLoc();
2140 // Consume the prefix character, and check for a following identifier.
2142 if (Lexer.isNot(AsmToken::Identifier))
2145 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2146 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2149 // Construct the joined identifier and consume the token.
2151 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2156 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2159 Res = getTok().getIdentifier();
2161 Lex(); // Consume the identifier token.
2166 /// parseDirectiveSet:
2167 /// ::= .equ identifier ',' expression
2168 /// ::= .equiv identifier ',' expression
2169 /// ::= .set identifier ',' expression
2170 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2173 if (parseIdentifier(Name))
2174 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2176 if (getLexer().isNot(AsmToken::Comma))
2177 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2180 return parseAssignment(Name, allow_redef, true);
2183 bool AsmParser::parseEscapedString(std::string &Data) {
2184 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2187 StringRef Str = getTok().getStringContents();
2188 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2189 if (Str[i] != '\\') {
2194 // Recognize escaped characters. Note that this escape semantics currently
2195 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2198 return TokError("unexpected backslash at end of string");
2200 // Recognize octal sequences.
2201 if ((unsigned)(Str[i] - '0') <= 7) {
2202 // Consume up to three octal characters.
2203 unsigned Value = Str[i] - '0';
2205 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2207 Value = Value * 8 + (Str[i] - '0');
2209 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2211 Value = Value * 8 + (Str[i] - '0');
2216 return TokError("invalid octal escape sequence (out of range)");
2218 Data += (unsigned char)Value;
2222 // Otherwise recognize individual escapes.
2225 // Just reject invalid escape sequences for now.
2226 return TokError("invalid escape sequence (unrecognized character)");
2228 case 'b': Data += '\b'; break;
2229 case 'f': Data += '\f'; break;
2230 case 'n': Data += '\n'; break;
2231 case 'r': Data += '\r'; break;
2232 case 't': Data += '\t'; break;
2233 case '"': Data += '"'; break;
2234 case '\\': Data += '\\'; break;
2241 /// parseDirectiveAscii:
2242 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2243 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2244 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2245 checkForValidSection();
2248 if (getLexer().isNot(AsmToken::String))
2249 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2252 if (parseEscapedString(Data))
2255 getStreamer().EmitBytes(Data);
2257 getStreamer().EmitBytes(StringRef("\0", 1));
2261 if (getLexer().is(AsmToken::EndOfStatement))
2264 if (getLexer().isNot(AsmToken::Comma))
2265 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2274 /// parseDirectiveValue
2275 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2276 bool AsmParser::parseDirectiveValue(unsigned Size) {
2277 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2278 checkForValidSection();
2281 const MCExpr *Value;
2282 SMLoc ExprLoc = getLexer().getLoc();
2283 if (parseExpression(Value))
2286 // Special case constant expressions to match code generator.
2287 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2288 assert(Size <= 8 && "Invalid size");
2289 uint64_t IntValue = MCE->getValue();
2290 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2291 return Error(ExprLoc, "literal value out of range for directive");
2292 getStreamer().EmitIntValue(IntValue, Size);
2294 getStreamer().EmitValue(Value, Size);
2296 if (getLexer().is(AsmToken::EndOfStatement))
2299 // FIXME: Improve diagnostic.
2300 if (getLexer().isNot(AsmToken::Comma))
2301 return TokError("unexpected token in directive");
2310 /// parseDirectiveRealValue
2311 /// ::= (.single | .double) [ expression (, expression)* ]
2312 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2313 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2314 checkForValidSection();
2317 // We don't truly support arithmetic on floating point expressions, so we
2318 // have to manually parse unary prefixes.
2320 if (getLexer().is(AsmToken::Minus)) {
2323 } else if (getLexer().is(AsmToken::Plus))
2326 if (getLexer().isNot(AsmToken::Integer) &&
2327 getLexer().isNot(AsmToken::Real) &&
2328 getLexer().isNot(AsmToken::Identifier))
2329 return TokError("unexpected token in directive");
2331 // Convert to an APFloat.
2332 APFloat Value(Semantics);
2333 StringRef IDVal = getTok().getString();
2334 if (getLexer().is(AsmToken::Identifier)) {
2335 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2336 Value = APFloat::getInf(Semantics);
2337 else if (!IDVal.compare_lower("nan"))
2338 Value = APFloat::getNaN(Semantics, false, ~0);
2340 return TokError("invalid floating point literal");
2341 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2342 APFloat::opInvalidOp)
2343 return TokError("invalid floating point literal");
2347 // Consume the numeric token.
2350 // Emit the value as an integer.
2351 APInt AsInt = Value.bitcastToAPInt();
2352 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2353 AsInt.getBitWidth() / 8);
2355 if (getLexer().is(AsmToken::EndOfStatement))
2358 if (getLexer().isNot(AsmToken::Comma))
2359 return TokError("unexpected token in directive");
2368 /// parseDirectiveZero
2369 /// ::= .zero expression
2370 bool AsmParser::parseDirectiveZero() {
2371 checkForValidSection();
2374 if (parseAbsoluteExpression(NumBytes))
2378 if (getLexer().is(AsmToken::Comma)) {
2380 if (parseAbsoluteExpression(Val))
2384 if (getLexer().isNot(AsmToken::EndOfStatement))
2385 return TokError("unexpected token in '.zero' directive");
2389 getStreamer().EmitFill(NumBytes, Val);
2394 /// parseDirectiveFill
2395 /// ::= .fill expression [ , expression [ , expression ] ]
2396 bool AsmParser::parseDirectiveFill() {
2397 checkForValidSection();
2400 if (parseAbsoluteExpression(NumValues))
2403 int64_t FillSize = 1;
2404 int64_t FillExpr = 0;
2406 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2407 if (getLexer().isNot(AsmToken::Comma))
2408 return TokError("unexpected token in '.fill' directive");
2411 if (parseAbsoluteExpression(FillSize))
2414 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2415 if (getLexer().isNot(AsmToken::Comma))
2416 return TokError("unexpected token in '.fill' directive");
2419 if (parseAbsoluteExpression(FillExpr))
2422 if (getLexer().isNot(AsmToken::EndOfStatement))
2423 return TokError("unexpected token in '.fill' directive");
2429 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2430 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2432 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2433 getStreamer().EmitIntValue(FillExpr, FillSize);
2438 /// parseDirectiveOrg
2439 /// ::= .org expression [ , expression ]
2440 bool AsmParser::parseDirectiveOrg() {
2441 checkForValidSection();
2443 const MCExpr *Offset;
2444 SMLoc Loc = getTok().getLoc();
2445 if (parseExpression(Offset))
2448 // Parse optional fill expression.
2449 int64_t FillExpr = 0;
2450 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2451 if (getLexer().isNot(AsmToken::Comma))
2452 return TokError("unexpected token in '.org' directive");
2455 if (parseAbsoluteExpression(FillExpr))
2458 if (getLexer().isNot(AsmToken::EndOfStatement))
2459 return TokError("unexpected token in '.org' directive");
2464 // Only limited forms of relocatable expressions are accepted here, it
2465 // has to be relative to the current section. The streamer will return
2466 // 'true' if the expression wasn't evaluatable.
2467 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2468 return Error(Loc, "expected assembly-time absolute expression");
2473 /// parseDirectiveAlign
2474 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2475 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2476 checkForValidSection();
2478 SMLoc AlignmentLoc = getLexer().getLoc();
2480 if (parseAbsoluteExpression(Alignment))
2484 bool HasFillExpr = false;
2485 int64_t FillExpr = 0;
2486 int64_t MaxBytesToFill = 0;
2487 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2488 if (getLexer().isNot(AsmToken::Comma))
2489 return TokError("unexpected token in directive");
2492 // The fill expression can be omitted while specifying a maximum number of
2493 // alignment bytes, e.g:
2495 if (getLexer().isNot(AsmToken::Comma)) {
2497 if (parseAbsoluteExpression(FillExpr))
2501 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2502 if (getLexer().isNot(AsmToken::Comma))
2503 return TokError("unexpected token in directive");
2506 MaxBytesLoc = getLexer().getLoc();
2507 if (parseAbsoluteExpression(MaxBytesToFill))
2510 if (getLexer().isNot(AsmToken::EndOfStatement))
2511 return TokError("unexpected token in directive");
2520 // Compute alignment in bytes.
2522 // FIXME: Diagnose overflow.
2523 if (Alignment >= 32) {
2524 Error(AlignmentLoc, "invalid alignment value");
2528 Alignment = 1ULL << Alignment;
2530 // Reject alignments that aren't a power of two, for gas compatibility.
2531 if (!isPowerOf2_64(Alignment))
2532 Error(AlignmentLoc, "alignment must be a power of 2");
2535 // Diagnose non-sensical max bytes to align.
2536 if (MaxBytesLoc.isValid()) {
2537 if (MaxBytesToFill < 1) {
2538 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2539 "many bytes, ignoring maximum bytes expression");
2543 if (MaxBytesToFill >= Alignment) {
2544 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2550 // Check whether we should use optimal code alignment for this .align
2552 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2553 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2554 ValueSize == 1 && UseCodeAlign) {
2555 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2557 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2558 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2565 /// parseDirectiveFile
2566 /// ::= .file [number] filename
2567 /// ::= .file number directory filename
2568 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2569 // FIXME: I'm not sure what this is.
2570 int64_t FileNumber = -1;
2571 SMLoc FileNumberLoc = getLexer().getLoc();
2572 if (getLexer().is(AsmToken::Integer)) {
2573 FileNumber = getTok().getIntVal();
2577 return TokError("file number less than one");
2580 if (getLexer().isNot(AsmToken::String))
2581 return TokError("unexpected token in '.file' directive");
2583 // Usually the directory and filename together, otherwise just the directory.
2584 // Allow the strings to have escaped octal character sequence.
2585 std::string Path = getTok().getString();
2586 if (parseEscapedString(Path))
2590 StringRef Directory;
2592 std::string FilenameData;
2593 if (getLexer().is(AsmToken::String)) {
2594 if (FileNumber == -1)
2595 return TokError("explicit path specified, but no file number");
2596 if (parseEscapedString(FilenameData))
2598 Filename = FilenameData;
2605 if (getLexer().isNot(AsmToken::EndOfStatement))
2606 return TokError("unexpected token in '.file' directive");
2608 if (FileNumber == -1)
2609 getStreamer().EmitFileDirective(Filename);
2611 if (getContext().getGenDwarfForAssembly() == true)
2613 "input can't have .file dwarf directives when -g is "
2614 "used to generate dwarf debug info for assembly code");
2616 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2617 Error(FileNumberLoc, "file number already allocated");
2623 /// parseDirectiveLine
2624 /// ::= .line [number]
2625 bool AsmParser::parseDirectiveLine() {
2626 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2627 if (getLexer().isNot(AsmToken::Integer))
2628 return TokError("unexpected token in '.line' directive");
2630 int64_t LineNumber = getTok().getIntVal();
2634 // FIXME: Do something with the .line.
2637 if (getLexer().isNot(AsmToken::EndOfStatement))
2638 return TokError("unexpected token in '.line' directive");
2643 /// parseDirectiveLoc
2644 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2645 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2646 /// The first number is a file number, must have been previously assigned with
2647 /// a .file directive, the second number is the line number and optionally the
2648 /// third number is a column position (zero if not specified). The remaining
2649 /// optional items are .loc sub-directives.
2650 bool AsmParser::parseDirectiveLoc() {
2651 if (getLexer().isNot(AsmToken::Integer))
2652 return TokError("unexpected token in '.loc' directive");
2653 int64_t FileNumber = getTok().getIntVal();
2655 return TokError("file number less than one in '.loc' directive");
2656 if (!getContext().isValidDwarfFileNumber(FileNumber))
2657 return TokError("unassigned file number in '.loc' directive");
2660 int64_t LineNumber = 0;
2661 if (getLexer().is(AsmToken::Integer)) {
2662 LineNumber = getTok().getIntVal();
2664 return TokError("line number less than zero in '.loc' directive");
2668 int64_t ColumnPos = 0;
2669 if (getLexer().is(AsmToken::Integer)) {
2670 ColumnPos = getTok().getIntVal();
2672 return TokError("column position less than zero in '.loc' directive");
2676 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2678 int64_t Discriminator = 0;
2679 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2681 if (getLexer().is(AsmToken::EndOfStatement))
2685 SMLoc Loc = getTok().getLoc();
2686 if (parseIdentifier(Name))
2687 return TokError("unexpected token in '.loc' directive");
2689 if (Name == "basic_block")
2690 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2691 else if (Name == "prologue_end")
2692 Flags |= DWARF2_FLAG_PROLOGUE_END;
2693 else if (Name == "epilogue_begin")
2694 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2695 else if (Name == "is_stmt") {
2696 Loc = getTok().getLoc();
2697 const MCExpr *Value;
2698 if (parseExpression(Value))
2700 // The expression must be the constant 0 or 1.
2701 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2702 int Value = MCE->getValue();
2704 Flags &= ~DWARF2_FLAG_IS_STMT;
2705 else if (Value == 1)
2706 Flags |= DWARF2_FLAG_IS_STMT;
2708 return Error(Loc, "is_stmt value not 0 or 1");
2710 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2712 } else if (Name == "isa") {
2713 Loc = getTok().getLoc();
2714 const MCExpr *Value;
2715 if (parseExpression(Value))
2717 // The expression must be a constant greater or equal to 0.
2718 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2719 int Value = MCE->getValue();
2721 return Error(Loc, "isa number less than zero");
2724 return Error(Loc, "isa number not a constant value");
2726 } else if (Name == "discriminator") {
2727 if (parseAbsoluteExpression(Discriminator))
2730 return Error(Loc, "unknown sub-directive in '.loc' directive");
2733 if (getLexer().is(AsmToken::EndOfStatement))
2738 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2739 Isa, Discriminator, StringRef());
2744 /// parseDirectiveStabs
2745 /// ::= .stabs string, number, number, number
2746 bool AsmParser::parseDirectiveStabs() {
2747 return TokError("unsupported directive '.stabs'");
2750 /// parseDirectiveCFISections
2751 /// ::= .cfi_sections section [, section]
2752 bool AsmParser::parseDirectiveCFISections() {
2757 if (parseIdentifier(Name))
2758 return TokError("Expected an identifier");
2760 if (Name == ".eh_frame")
2762 else if (Name == ".debug_frame")
2765 if (getLexer().is(AsmToken::Comma)) {
2768 if (parseIdentifier(Name))
2769 return TokError("Expected an identifier");
2771 if (Name == ".eh_frame")
2773 else if (Name == ".debug_frame")
2777 getStreamer().EmitCFISections(EH, Debug);
2781 /// parseDirectiveCFIStartProc
2782 /// ::= .cfi_startproc
2783 bool AsmParser::parseDirectiveCFIStartProc() {
2784 getStreamer().EmitCFIStartProc();
2788 /// parseDirectiveCFIEndProc
2789 /// ::= .cfi_endproc
2790 bool AsmParser::parseDirectiveCFIEndProc() {
2791 getStreamer().EmitCFIEndProc();
2795 /// \brief parse register name or number.
2796 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2797 SMLoc DirectiveLoc) {
2800 if (getLexer().isNot(AsmToken::Integer)) {
2801 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2803 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2805 return parseAbsoluteExpression(Register);
2810 /// parseDirectiveCFIDefCfa
2811 /// ::= .cfi_def_cfa register, offset
2812 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2813 int64_t Register = 0;
2814 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2817 if (getLexer().isNot(AsmToken::Comma))
2818 return TokError("unexpected token in directive");
2822 if (parseAbsoluteExpression(Offset))
2825 getStreamer().EmitCFIDefCfa(Register, Offset);
2829 /// parseDirectiveCFIDefCfaOffset
2830 /// ::= .cfi_def_cfa_offset offset
2831 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2833 if (parseAbsoluteExpression(Offset))
2836 getStreamer().EmitCFIDefCfaOffset(Offset);
2840 /// parseDirectiveCFIRegister
2841 /// ::= .cfi_register register, register
2842 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2843 int64_t Register1 = 0;
2844 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2847 if (getLexer().isNot(AsmToken::Comma))
2848 return TokError("unexpected token in directive");
2851 int64_t Register2 = 0;
2852 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2855 getStreamer().EmitCFIRegister(Register1, Register2);
2859 /// parseDirectiveCFIWindowSave
2860 /// ::= .cfi_window_save
2861 bool AsmParser::parseDirectiveCFIWindowSave() {
2862 getStreamer().EmitCFIWindowSave();
2866 /// parseDirectiveCFIAdjustCfaOffset
2867 /// ::= .cfi_adjust_cfa_offset adjustment
2868 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2869 int64_t Adjustment = 0;
2870 if (parseAbsoluteExpression(Adjustment))
2873 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2877 /// parseDirectiveCFIDefCfaRegister
2878 /// ::= .cfi_def_cfa_register register
2879 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2880 int64_t Register = 0;
2881 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2884 getStreamer().EmitCFIDefCfaRegister(Register);
2888 /// parseDirectiveCFIOffset
2889 /// ::= .cfi_offset register, offset
2890 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2891 int64_t Register = 0;
2894 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2897 if (getLexer().isNot(AsmToken::Comma))
2898 return TokError("unexpected token in directive");
2901 if (parseAbsoluteExpression(Offset))
2904 getStreamer().EmitCFIOffset(Register, Offset);
2908 /// parseDirectiveCFIRelOffset
2909 /// ::= .cfi_rel_offset register, offset
2910 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2911 int64_t Register = 0;
2913 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2916 if (getLexer().isNot(AsmToken::Comma))
2917 return TokError("unexpected token in directive");
2921 if (parseAbsoluteExpression(Offset))
2924 getStreamer().EmitCFIRelOffset(Register, Offset);
2928 static bool isValidEncoding(int64_t Encoding) {
2929 if (Encoding & ~0xff)
2932 if (Encoding == dwarf::DW_EH_PE_omit)
2935 const unsigned Format = Encoding & 0xf;
2936 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2937 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2938 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2939 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2942 const unsigned Application = Encoding & 0x70;
2943 if (Application != dwarf::DW_EH_PE_absptr &&
2944 Application != dwarf::DW_EH_PE_pcrel)
2950 /// parseDirectiveCFIPersonalityOrLsda
2951 /// IsPersonality true for cfi_personality, false for cfi_lsda
2952 /// ::= .cfi_personality encoding, [symbol_name]
2953 /// ::= .cfi_lsda encoding, [symbol_name]
2954 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2955 int64_t Encoding = 0;
2956 if (parseAbsoluteExpression(Encoding))
2958 if (Encoding == dwarf::DW_EH_PE_omit)
2961 if (!isValidEncoding(Encoding))
2962 return TokError("unsupported encoding.");
2964 if (getLexer().isNot(AsmToken::Comma))
2965 return TokError("unexpected token in directive");
2969 if (parseIdentifier(Name))
2970 return TokError("expected identifier in directive");
2972 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2975 getStreamer().EmitCFIPersonality(Sym, Encoding);
2977 getStreamer().EmitCFILsda(Sym, Encoding);
2981 /// parseDirectiveCFIRememberState
2982 /// ::= .cfi_remember_state
2983 bool AsmParser::parseDirectiveCFIRememberState() {
2984 getStreamer().EmitCFIRememberState();
2988 /// parseDirectiveCFIRestoreState
2989 /// ::= .cfi_remember_state
2990 bool AsmParser::parseDirectiveCFIRestoreState() {
2991 getStreamer().EmitCFIRestoreState();
2995 /// parseDirectiveCFISameValue
2996 /// ::= .cfi_same_value register
2997 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2998 int64_t Register = 0;
3000 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3003 getStreamer().EmitCFISameValue(Register);
3007 /// parseDirectiveCFIRestore
3008 /// ::= .cfi_restore register
3009 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3010 int64_t Register = 0;
3011 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3014 getStreamer().EmitCFIRestore(Register);
3018 /// parseDirectiveCFIEscape
3019 /// ::= .cfi_escape expression[,...]
3020 bool AsmParser::parseDirectiveCFIEscape() {
3023 if (parseAbsoluteExpression(CurrValue))
3026 Values.push_back((uint8_t)CurrValue);
3028 while (getLexer().is(AsmToken::Comma)) {
3031 if (parseAbsoluteExpression(CurrValue))
3034 Values.push_back((uint8_t)CurrValue);
3037 getStreamer().EmitCFIEscape(Values);
3041 /// parseDirectiveCFISignalFrame
3042 /// ::= .cfi_signal_frame
3043 bool AsmParser::parseDirectiveCFISignalFrame() {
3044 if (getLexer().isNot(AsmToken::EndOfStatement))
3045 return Error(getLexer().getLoc(),
3046 "unexpected token in '.cfi_signal_frame'");
3048 getStreamer().EmitCFISignalFrame();
3052 /// parseDirectiveCFIUndefined
3053 /// ::= .cfi_undefined register
3054 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3055 int64_t Register = 0;
3057 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3060 getStreamer().EmitCFIUndefined(Register);
3064 /// parseDirectiveMacrosOnOff
3067 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3068 if (getLexer().isNot(AsmToken::EndOfStatement))
3069 return Error(getLexer().getLoc(),
3070 "unexpected token in '" + Directive + "' directive");
3072 setMacrosEnabled(Directive == ".macros_on");
3076 /// parseDirectiveMacro
3077 /// ::= .macro name [parameters]
3078 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3080 if (parseIdentifier(Name))
3081 return TokError("expected identifier in '.macro' directive");
3083 MCAsmMacroParameters Parameters;
3084 // Argument delimiter is initially unknown. It will be set by
3085 // parseMacroArgument()
3086 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3087 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3089 MCAsmMacroParameter Parameter;
3090 if (parseIdentifier(Parameter.first))
3091 return TokError("expected identifier in '.macro' directive");
3093 if (getLexer().is(AsmToken::Equal)) {
3095 if (parseMacroArgument(Parameter.second, ArgumentDelimiter))
3099 Parameters.push_back(Parameter);
3101 if (getLexer().is(AsmToken::Comma))
3103 else if (getLexer().is(AsmToken::EndOfStatement))
3108 // Eat the end of statement.
3111 AsmToken EndToken, StartToken = getTok();
3113 // Lex the macro definition.
3115 // Check whether we have reached the end of the file.
3116 if (getLexer().is(AsmToken::Eof))
3117 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3119 // Otherwise, check whether we have reach the .endmacro.
3120 if (getLexer().is(AsmToken::Identifier) &&
3121 (getTok().getIdentifier() == ".endm" ||
3122 getTok().getIdentifier() == ".endmacro")) {
3123 EndToken = getTok();
3125 if (getLexer().isNot(AsmToken::EndOfStatement))
3126 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3131 // Otherwise, scan til the end of the statement.
3132 eatToEndOfStatement();
3135 if (lookupMacro(Name)) {
3136 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3139 const char *BodyStart = StartToken.getLoc().getPointer();
3140 const char *BodyEnd = EndToken.getLoc().getPointer();
3141 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3142 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3143 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3147 /// checkForBadMacro
3149 /// With the support added for named parameters there may be code out there that
3150 /// is transitioning from positional parameters. In versions of gas that did
3151 /// not support named parameters they would be ignored on the macro defintion.
3152 /// But to support both styles of parameters this is not possible so if a macro
3153 /// defintion has named parameters but does not use them and has what appears
3154 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3155 /// warning that the positional parameter found in body which have no effect.
3156 /// Hoping the developer will either remove the named parameters from the macro
3157 /// definiton so the positional parameters get used if that was what was
3158 /// intended or change the macro to use the named parameters. It is possible
3159 /// this warning will trigger when the none of the named parameters are used
3160 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3161 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3163 MCAsmMacroParameters Parameters) {
3164 // If this macro is not defined with named parameters the warning we are
3165 // checking for here doesn't apply.
3166 unsigned NParameters = Parameters.size();
3167 if (NParameters == 0)
3170 bool NamedParametersFound = false;
3171 bool PositionalParametersFound = false;
3173 // Look at the body of the macro for use of both the named parameters and what
3174 // are likely to be positional parameters. This is what expandMacro() is
3175 // doing when it finds the parameters in the body.
3176 while (!Body.empty()) {
3177 // Scan for the next possible parameter.
3178 std::size_t End = Body.size(), Pos = 0;
3179 for (; Pos != End; ++Pos) {
3180 // Check for a substitution or escape.
3181 // This macro is defined with parameters, look for \foo, \bar, etc.
3182 if (Body[Pos] == '\\' && Pos + 1 != End)
3185 // This macro should have parameters, but look for $0, $1, ..., $n too.
3186 if (Body[Pos] != '$' || Pos + 1 == End)
3188 char Next = Body[Pos + 1];
3189 if (Next == '$' || Next == 'n' ||
3190 isdigit(static_cast<unsigned char>(Next)))
3194 // Check if we reached the end.
3198 if (Body[Pos] == '$') {
3199 switch (Body[Pos + 1]) {
3204 // $n => number of arguments
3206 PositionalParametersFound = true;
3209 // $[0-9] => argument
3211 PositionalParametersFound = true;
3217 unsigned I = Pos + 1;
3218 while (isIdentifierChar(Body[I]) && I + 1 != End)
3221 const char *Begin = Body.data() + Pos + 1;
3222 StringRef Argument(Begin, I - (Pos + 1));
3224 for (; Index < NParameters; ++Index)
3225 if (Parameters[Index].first == Argument)
3228 if (Index == NParameters) {
3229 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3235 NamedParametersFound = true;
3236 Pos += 1 + Argument.size();
3239 // Update the scan point.
3240 Body = Body.substr(Pos);
3243 if (!NamedParametersFound && PositionalParametersFound)
3244 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3245 "used in macro body, possible positional parameter "
3246 "found in body which will have no effect");
3249 /// parseDirectiveEndMacro
3252 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3253 if (getLexer().isNot(AsmToken::EndOfStatement))
3254 return TokError("unexpected token in '" + Directive + "' directive");
3256 // If we are inside a macro instantiation, terminate the current
3258 if (isInsideMacroInstantiation()) {
3263 // Otherwise, this .endmacro is a stray entry in the file; well formed
3264 // .endmacro directives are handled during the macro definition parsing.
3265 return TokError("unexpected '" + Directive + "' in file, "
3266 "no current macro definition");
3269 /// parseDirectivePurgeMacro
3271 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3273 if (parseIdentifier(Name))
3274 return TokError("expected identifier in '.purgem' directive");
3276 if (getLexer().isNot(AsmToken::EndOfStatement))
3277 return TokError("unexpected token in '.purgem' directive");
3279 if (!lookupMacro(Name))
3280 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3282 undefineMacro(Name);
3286 /// parseDirectiveBundleAlignMode
3287 /// ::= {.bundle_align_mode} expression
3288 bool AsmParser::parseDirectiveBundleAlignMode() {
3289 checkForValidSection();
3291 // Expect a single argument: an expression that evaluates to a constant
3292 // in the inclusive range 0-30.
3293 SMLoc ExprLoc = getLexer().getLoc();
3294 int64_t AlignSizePow2;
3295 if (parseAbsoluteExpression(AlignSizePow2))
3297 else if (getLexer().isNot(AsmToken::EndOfStatement))
3298 return TokError("unexpected token after expression in"
3299 " '.bundle_align_mode' directive");
3300 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3301 return Error(ExprLoc,
3302 "invalid bundle alignment size (expected between 0 and 30)");
3306 // Because of AlignSizePow2's verified range we can safely truncate it to
3308 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3312 /// parseDirectiveBundleLock
3313 /// ::= {.bundle_lock} [align_to_end]
3314 bool AsmParser::parseDirectiveBundleLock() {
3315 checkForValidSection();
3316 bool AlignToEnd = false;
3318 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3320 SMLoc Loc = getTok().getLoc();
3321 const char *kInvalidOptionError =
3322 "invalid option for '.bundle_lock' directive";
3324 if (parseIdentifier(Option))
3325 return Error(Loc, kInvalidOptionError);
3327 if (Option != "align_to_end")
3328 return Error(Loc, kInvalidOptionError);
3329 else if (getLexer().isNot(AsmToken::EndOfStatement))
3331 "unexpected token after '.bundle_lock' directive option");
3337 getStreamer().EmitBundleLock(AlignToEnd);
3341 /// parseDirectiveBundleLock
3342 /// ::= {.bundle_lock}
3343 bool AsmParser::parseDirectiveBundleUnlock() {
3344 checkForValidSection();
3346 if (getLexer().isNot(AsmToken::EndOfStatement))
3347 return TokError("unexpected token in '.bundle_unlock' directive");
3350 getStreamer().EmitBundleUnlock();
3354 /// parseDirectiveSpace
3355 /// ::= (.skip | .space) expression [ , expression ]
3356 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3357 checkForValidSection();
3360 if (parseAbsoluteExpression(NumBytes))
3363 int64_t FillExpr = 0;
3364 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3365 if (getLexer().isNot(AsmToken::Comma))
3366 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3369 if (parseAbsoluteExpression(FillExpr))
3372 if (getLexer().isNot(AsmToken::EndOfStatement))
3373 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3379 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3382 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3383 getStreamer().EmitFill(NumBytes, FillExpr);
3388 /// parseDirectiveLEB128
3389 /// ::= (.sleb128 | .uleb128) expression
3390 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3391 checkForValidSection();
3392 const MCExpr *Value;
3394 if (parseExpression(Value))
3397 if (getLexer().isNot(AsmToken::EndOfStatement))
3398 return TokError("unexpected token in directive");
3401 getStreamer().EmitSLEB128Value(Value);
3403 getStreamer().EmitULEB128Value(Value);
3408 /// parseDirectiveSymbolAttribute
3409 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3410 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3411 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3414 SMLoc Loc = getTok().getLoc();
3416 if (parseIdentifier(Name))
3417 return Error(Loc, "expected identifier in directive");
3419 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3421 // Assembler local symbols don't make any sense here. Complain loudly.
3422 if (Sym->isTemporary())
3423 return Error(Loc, "non-local symbol required in directive");
3425 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3426 return Error(Loc, "unable to emit symbol attribute");
3428 if (getLexer().is(AsmToken::EndOfStatement))
3431 if (getLexer().isNot(AsmToken::Comma))
3432 return TokError("unexpected token in directive");
3441 /// parseDirectiveComm
3442 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3443 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3444 checkForValidSection();
3446 SMLoc IDLoc = getLexer().getLoc();
3448 if (parseIdentifier(Name))
3449 return TokError("expected identifier in directive");
3451 // Handle the identifier as the key symbol.
3452 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3454 if (getLexer().isNot(AsmToken::Comma))
3455 return TokError("unexpected token in directive");
3459 SMLoc SizeLoc = getLexer().getLoc();
3460 if (parseAbsoluteExpression(Size))
3463 int64_t Pow2Alignment = 0;
3464 SMLoc Pow2AlignmentLoc;
3465 if (getLexer().is(AsmToken::Comma)) {
3467 Pow2AlignmentLoc = getLexer().getLoc();
3468 if (parseAbsoluteExpression(Pow2Alignment))
3471 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3472 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3473 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3475 // If this target takes alignments in bytes (not log) validate and convert.
3476 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3477 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3478 if (!isPowerOf2_64(Pow2Alignment))
3479 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3480 Pow2Alignment = Log2_64(Pow2Alignment);
3484 if (getLexer().isNot(AsmToken::EndOfStatement))
3485 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3489 // NOTE: a size of zero for a .comm should create a undefined symbol
3490 // but a size of .lcomm creates a bss symbol of size zero.
3492 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3493 "be less than zero");
3495 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3496 // may internally end up wanting an alignment in bytes.
3497 // FIXME: Diagnose overflow.
3498 if (Pow2Alignment < 0)
3499 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3500 "alignment, can't be less than zero");
3502 if (!Sym->isUndefined())
3503 return Error(IDLoc, "invalid symbol redefinition");
3505 // Create the Symbol as a common or local common with Size and Pow2Alignment
3507 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3511 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3515 /// parseDirectiveAbort
3516 /// ::= .abort [... message ...]
3517 bool AsmParser::parseDirectiveAbort() {
3518 // FIXME: Use loc from directive.
3519 SMLoc Loc = getLexer().getLoc();
3521 StringRef Str = parseStringToEndOfStatement();
3522 if (getLexer().isNot(AsmToken::EndOfStatement))
3523 return TokError("unexpected token in '.abort' directive");
3528 Error(Loc, ".abort detected. Assembly stopping.");
3530 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3531 // FIXME: Actually abort assembly here.
3536 /// parseDirectiveInclude
3537 /// ::= .include "filename"
3538 bool AsmParser::parseDirectiveInclude() {
3539 if (getLexer().isNot(AsmToken::String))
3540 return TokError("expected string in '.include' directive");
3542 // Allow the strings to have escaped octal character sequence.
3543 std::string Filename;
3544 if (parseEscapedString(Filename))
3546 SMLoc IncludeLoc = getLexer().getLoc();
3549 if (getLexer().isNot(AsmToken::EndOfStatement))
3550 return TokError("unexpected token in '.include' directive");
3552 // Attempt to switch the lexer to the included file before consuming the end
3553 // of statement to avoid losing it when we switch.
3554 if (enterIncludeFile(Filename)) {
3555 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3562 /// parseDirectiveIncbin
3563 /// ::= .incbin "filename"
3564 bool AsmParser::parseDirectiveIncbin() {
3565 if (getLexer().isNot(AsmToken::String))
3566 return TokError("expected string in '.incbin' directive");
3568 // Allow the strings to have escaped octal character sequence.
3569 std::string Filename;
3570 if (parseEscapedString(Filename))
3572 SMLoc IncbinLoc = getLexer().getLoc();
3575 if (getLexer().isNot(AsmToken::EndOfStatement))
3576 return TokError("unexpected token in '.incbin' directive");
3578 // Attempt to process the included file.
3579 if (processIncbinFile(Filename)) {
3580 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3587 /// parseDirectiveIf
3588 /// ::= .if expression
3589 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3590 TheCondStack.push_back(TheCondState);
3591 TheCondState.TheCond = AsmCond::IfCond;
3592 if (TheCondState.Ignore) {
3593 eatToEndOfStatement();
3596 if (parseAbsoluteExpression(ExprValue))
3599 if (getLexer().isNot(AsmToken::EndOfStatement))
3600 return TokError("unexpected token in '.if' directive");
3604 TheCondState.CondMet = ExprValue;
3605 TheCondState.Ignore = !TheCondState.CondMet;
3611 /// parseDirectiveIfb
3613 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3614 TheCondStack.push_back(TheCondState);
3615 TheCondState.TheCond = AsmCond::IfCond;
3617 if (TheCondState.Ignore) {
3618 eatToEndOfStatement();
3620 StringRef Str = parseStringToEndOfStatement();
3622 if (getLexer().isNot(AsmToken::EndOfStatement))
3623 return TokError("unexpected token in '.ifb' directive");
3627 TheCondState.CondMet = ExpectBlank == Str.empty();
3628 TheCondState.Ignore = !TheCondState.CondMet;
3634 /// parseDirectiveIfc
3635 /// ::= .ifc string1, string2
3636 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3637 TheCondStack.push_back(TheCondState);
3638 TheCondState.TheCond = AsmCond::IfCond;
3640 if (TheCondState.Ignore) {
3641 eatToEndOfStatement();
3643 StringRef Str1 = parseStringToComma();
3645 if (getLexer().isNot(AsmToken::Comma))
3646 return TokError("unexpected token in '.ifc' directive");
3650 StringRef Str2 = parseStringToEndOfStatement();
3652 if (getLexer().isNot(AsmToken::EndOfStatement))
3653 return TokError("unexpected token in '.ifc' directive");
3657 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3658 TheCondState.Ignore = !TheCondState.CondMet;
3664 /// parseDirectiveIfdef
3665 /// ::= .ifdef symbol
3666 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3668 TheCondStack.push_back(TheCondState);
3669 TheCondState.TheCond = AsmCond::IfCond;
3671 if (TheCondState.Ignore) {
3672 eatToEndOfStatement();
3674 if (parseIdentifier(Name))
3675 return TokError("expected identifier after '.ifdef'");
3679 MCSymbol *Sym = getContext().LookupSymbol(Name);
3682 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3684 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3685 TheCondState.Ignore = !TheCondState.CondMet;
3691 /// parseDirectiveElseIf
3692 /// ::= .elseif expression
3693 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3694 if (TheCondState.TheCond != AsmCond::IfCond &&
3695 TheCondState.TheCond != AsmCond::ElseIfCond)
3696 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3698 TheCondState.TheCond = AsmCond::ElseIfCond;
3700 bool LastIgnoreState = false;
3701 if (!TheCondStack.empty())
3702 LastIgnoreState = TheCondStack.back().Ignore;
3703 if (LastIgnoreState || TheCondState.CondMet) {
3704 TheCondState.Ignore = true;
3705 eatToEndOfStatement();
3708 if (parseAbsoluteExpression(ExprValue))
3711 if (getLexer().isNot(AsmToken::EndOfStatement))
3712 return TokError("unexpected token in '.elseif' directive");
3715 TheCondState.CondMet = ExprValue;
3716 TheCondState.Ignore = !TheCondState.CondMet;
3722 /// parseDirectiveElse
3724 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3725 if (getLexer().isNot(AsmToken::EndOfStatement))
3726 return TokError("unexpected token in '.else' directive");
3730 if (TheCondState.TheCond != AsmCond::IfCond &&
3731 TheCondState.TheCond != AsmCond::ElseIfCond)
3732 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3734 TheCondState.TheCond = AsmCond::ElseCond;
3735 bool LastIgnoreState = false;
3736 if (!TheCondStack.empty())
3737 LastIgnoreState = TheCondStack.back().Ignore;
3738 if (LastIgnoreState || TheCondState.CondMet)
3739 TheCondState.Ignore = true;
3741 TheCondState.Ignore = false;
3746 /// parseDirectiveEndIf
3748 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3749 if (getLexer().isNot(AsmToken::EndOfStatement))
3750 return TokError("unexpected token in '.endif' directive");
3754 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3755 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3757 if (!TheCondStack.empty()) {
3758 TheCondState = TheCondStack.back();
3759 TheCondStack.pop_back();
3765 void AsmParser::initializeDirectiveKindMap() {
3766 DirectiveKindMap[".set"] = DK_SET;
3767 DirectiveKindMap[".equ"] = DK_EQU;
3768 DirectiveKindMap[".equiv"] = DK_EQUIV;
3769 DirectiveKindMap[".ascii"] = DK_ASCII;
3770 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3771 DirectiveKindMap[".string"] = DK_STRING;
3772 DirectiveKindMap[".byte"] = DK_BYTE;
3773 DirectiveKindMap[".short"] = DK_SHORT;
3774 DirectiveKindMap[".value"] = DK_VALUE;
3775 DirectiveKindMap[".2byte"] = DK_2BYTE;
3776 DirectiveKindMap[".long"] = DK_LONG;
3777 DirectiveKindMap[".int"] = DK_INT;
3778 DirectiveKindMap[".4byte"] = DK_4BYTE;
3779 DirectiveKindMap[".quad"] = DK_QUAD;
3780 DirectiveKindMap[".8byte"] = DK_8BYTE;
3781 DirectiveKindMap[".single"] = DK_SINGLE;
3782 DirectiveKindMap[".float"] = DK_FLOAT;
3783 DirectiveKindMap[".double"] = DK_DOUBLE;
3784 DirectiveKindMap[".align"] = DK_ALIGN;
3785 DirectiveKindMap[".align32"] = DK_ALIGN32;
3786 DirectiveKindMap[".balign"] = DK_BALIGN;
3787 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3788 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3789 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3790 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3791 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3792 DirectiveKindMap[".org"] = DK_ORG;
3793 DirectiveKindMap[".fill"] = DK_FILL;
3794 DirectiveKindMap[".zero"] = DK_ZERO;
3795 DirectiveKindMap[".extern"] = DK_EXTERN;
3796 DirectiveKindMap[".globl"] = DK_GLOBL;
3797 DirectiveKindMap[".global"] = DK_GLOBAL;
3798 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3799 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3800 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3801 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3802 DirectiveKindMap[".reference"] = DK_REFERENCE;
3803 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3804 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3805 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3806 DirectiveKindMap[".comm"] = DK_COMM;
3807 DirectiveKindMap[".common"] = DK_COMMON;
3808 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3809 DirectiveKindMap[".abort"] = DK_ABORT;
3810 DirectiveKindMap[".include"] = DK_INCLUDE;
3811 DirectiveKindMap[".incbin"] = DK_INCBIN;
3812 DirectiveKindMap[".code16"] = DK_CODE16;
3813 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3814 DirectiveKindMap[".rept"] = DK_REPT;
3815 DirectiveKindMap[".irp"] = DK_IRP;
3816 DirectiveKindMap[".irpc"] = DK_IRPC;
3817 DirectiveKindMap[".endr"] = DK_ENDR;
3818 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3819 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3820 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3821 DirectiveKindMap[".if"] = DK_IF;
3822 DirectiveKindMap[".ifb"] = DK_IFB;
3823 DirectiveKindMap[".ifnb"] = DK_IFNB;
3824 DirectiveKindMap[".ifc"] = DK_IFC;
3825 DirectiveKindMap[".ifnc"] = DK_IFNC;
3826 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3827 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3828 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3829 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3830 DirectiveKindMap[".else"] = DK_ELSE;
3831 DirectiveKindMap[".endif"] = DK_ENDIF;
3832 DirectiveKindMap[".skip"] = DK_SKIP;
3833 DirectiveKindMap[".space"] = DK_SPACE;
3834 DirectiveKindMap[".file"] = DK_FILE;
3835 DirectiveKindMap[".line"] = DK_LINE;
3836 DirectiveKindMap[".loc"] = DK_LOC;
3837 DirectiveKindMap[".stabs"] = DK_STABS;
3838 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3839 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3840 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3841 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3842 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3843 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3844 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3845 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3846 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3847 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3848 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3849 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3850 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3851 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3852 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3853 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3854 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3855 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3856 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3857 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3858 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3859 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
3860 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3861 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3862 DirectiveKindMap[".macro"] = DK_MACRO;
3863 DirectiveKindMap[".endm"] = DK_ENDM;
3864 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3865 DirectiveKindMap[".purgem"] = DK_PURGEM;
3868 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
3869 AsmToken EndToken, StartToken = getTok();
3871 unsigned NestLevel = 0;
3873 // Check whether we have reached the end of the file.
3874 if (getLexer().is(AsmToken::Eof)) {
3875 Error(DirectiveLoc, "no matching '.endr' in definition");
3879 if (Lexer.is(AsmToken::Identifier) &&
3880 (getTok().getIdentifier() == ".rept")) {
3884 // Otherwise, check whether we have reached the .endr.
3885 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
3886 if (NestLevel == 0) {
3887 EndToken = getTok();
3889 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3890 TokError("unexpected token in '.endr' directive");
3898 // Otherwise, scan till the end of the statement.
3899 eatToEndOfStatement();
3902 const char *BodyStart = StartToken.getLoc().getPointer();
3903 const char *BodyEnd = EndToken.getLoc().getPointer();
3904 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3906 // We Are Anonymous.
3908 MCAsmMacroParameters Parameters;
3909 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3910 return &MacroLikeBodies.back();
3913 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3914 raw_svector_ostream &OS) {
3917 MemoryBuffer *Instantiation =
3918 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3920 // Create the macro instantiation object and add to the current macro
3921 // instantiation stack.
3922 MacroInstantiation *MI = new MacroInstantiation(
3923 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
3924 ActiveMacros.push_back(MI);
3926 // Jump to the macro instantiation and prime the lexer.
3927 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3928 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3932 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc) {
3934 if (parseAbsoluteExpression(Count))
3935 return TokError("unexpected token in '.rept' directive");
3938 return TokError("Count is negative");
3940 if (Lexer.isNot(AsmToken::EndOfStatement))
3941 return TokError("unexpected token in '.rept' directive");
3943 // Eat the end of statement.
3946 // Lex the rept definition.
3947 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
3951 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3952 // to hold the macro body with substitutions.
3953 SmallString<256> Buf;
3954 MCAsmMacroParameters Parameters;
3955 MCAsmMacroArguments A;
3956 raw_svector_ostream OS(Buf);
3958 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3961 instantiateMacroLikeBody(M, DirectiveLoc, OS);
3966 /// parseDirectiveIrp
3967 /// ::= .irp symbol,values
3968 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
3969 MCAsmMacroParameters Parameters;
3970 MCAsmMacroParameter Parameter;
3972 if (parseIdentifier(Parameter.first))
3973 return TokError("expected identifier in '.irp' directive");
3975 Parameters.push_back(Parameter);
3977 if (Lexer.isNot(AsmToken::Comma))
3978 return TokError("expected comma in '.irp' directive");
3982 MCAsmMacroArguments A;
3983 if (parseMacroArguments(0, A))
3986 // Eat the end of statement.
3989 // Lex the irp definition.
3990 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
3994 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3995 // to hold the macro body with substitutions.
3996 SmallString<256> Buf;
3997 raw_svector_ostream OS(Buf);
3999 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4000 MCAsmMacroArguments Args;
4003 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4007 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4012 /// parseDirectiveIrpc
4013 /// ::= .irpc symbol,values
4014 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4015 MCAsmMacroParameters Parameters;
4016 MCAsmMacroParameter Parameter;
4018 if (parseIdentifier(Parameter.first))
4019 return TokError("expected identifier in '.irpc' directive");
4021 Parameters.push_back(Parameter);
4023 if (Lexer.isNot(AsmToken::Comma))
4024 return TokError("expected comma in '.irpc' directive");
4028 MCAsmMacroArguments A;
4029 if (parseMacroArguments(0, A))
4032 if (A.size() != 1 || A.front().size() != 1)
4033 return TokError("unexpected token in '.irpc' directive");
4035 // Eat the end of statement.
4038 // Lex the irpc definition.
4039 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4043 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4044 // to hold the macro body with substitutions.
4045 SmallString<256> Buf;
4046 raw_svector_ostream OS(Buf);
4048 StringRef Values = A.front().front().getString();
4049 std::size_t I, End = Values.size();
4050 for (I = 0; I < End; ++I) {
4051 MCAsmMacroArgument Arg;
4052 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4054 MCAsmMacroArguments Args;
4055 Args.push_back(Arg);
4057 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4061 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4066 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4067 if (ActiveMacros.empty())
4068 return TokError("unmatched '.endr' directive");
4070 // The only .repl that should get here are the ones created by
4071 // instantiateMacroLikeBody.
4072 assert(getLexer().is(AsmToken::EndOfStatement));
4078 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4080 const MCExpr *Value;
4081 SMLoc ExprLoc = getLexer().getLoc();
4082 if (parseExpression(Value))
4084 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4086 return Error(ExprLoc, "unexpected expression in _emit");
4087 uint64_t IntValue = MCE->getValue();
4088 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4089 return Error(ExprLoc, "literal value out of range for directive");
4091 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4095 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4096 const MCExpr *Value;
4097 SMLoc ExprLoc = getLexer().getLoc();
4098 if (parseExpression(Value))
4100 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4102 return Error(ExprLoc, "unexpected expression in align");
4103 uint64_t IntValue = MCE->getValue();
4104 if (!isPowerOf2_64(IntValue))
4105 return Error(ExprLoc, "literal value not a power of two greater then zero");
4107 Info.AsmRewrites->push_back(
4108 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4112 // We are comparing pointers, but the pointers are relative to a single string.
4113 // Thus, this should always be deterministic.
4114 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4115 const AsmRewrite *AsmRewriteB) {
4116 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4118 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4121 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4122 // rewrite to the same location. Make sure the SizeDirective rewrite is
4123 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4124 // ensures the sort algorithm is stable.
4125 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4126 AsmRewritePrecedence[AsmRewriteB->Kind])
4129 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4130 AsmRewritePrecedence[AsmRewriteB->Kind])
4132 llvm_unreachable("Unstable rewrite sort.");
4135 bool AsmParser::parseMSInlineAsm(
4136 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4137 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4138 SmallVectorImpl<std::string> &Constraints,
4139 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4140 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4141 SmallVector<void *, 4> InputDecls;
4142 SmallVector<void *, 4> OutputDecls;
4143 SmallVector<bool, 4> InputDeclsAddressOf;
4144 SmallVector<bool, 4> OutputDeclsAddressOf;
4145 SmallVector<std::string, 4> InputConstraints;
4146 SmallVector<std::string, 4> OutputConstraints;
4147 SmallVector<unsigned, 4> ClobberRegs;
4149 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4154 // While we have input, parse each statement.
4155 unsigned InputIdx = 0;
4156 unsigned OutputIdx = 0;
4157 while (getLexer().isNot(AsmToken::Eof)) {
4158 ParseStatementInfo Info(&AsmStrRewrites);
4159 if (parseStatement(Info))
4162 if (Info.ParseError)
4165 if (Info.Opcode == ~0U)
4168 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4170 // Build the list of clobbers, outputs and inputs.
4171 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4172 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4175 if (Operand->isImm())
4178 // Register operand.
4179 if (Operand->isReg() && !Operand->needAddressOf()) {
4180 unsigned NumDefs = Desc.getNumDefs();
4182 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4183 ClobberRegs.push_back(Operand->getReg());
4187 // Expr/Input or Output.
4188 StringRef SymName = Operand->getSymName();
4189 if (SymName.empty())
4192 void *OpDecl = Operand->getOpDecl();
4196 bool isOutput = (i == 1) && Desc.mayStore();
4197 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4200 OutputDecls.push_back(OpDecl);
4201 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4202 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4203 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4205 InputDecls.push_back(OpDecl);
4206 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4207 InputConstraints.push_back(Operand->getConstraint().str());
4208 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4212 // Consider implicit defs to be clobbers. Think of cpuid and push.
4213 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4214 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4215 ClobberRegs.push_back(ImpDefs[I]);
4218 // Set the number of Outputs and Inputs.
4219 NumOutputs = OutputDecls.size();
4220 NumInputs = InputDecls.size();
4222 // Set the unique clobbers.
4223 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4224 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4226 Clobbers.assign(ClobberRegs.size(), std::string());
4227 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4228 raw_string_ostream OS(Clobbers[I]);
4229 IP->printRegName(OS, ClobberRegs[I]);
4232 // Merge the various outputs and inputs. Output are expected first.
4233 if (NumOutputs || NumInputs) {
4234 unsigned NumExprs = NumOutputs + NumInputs;
4235 OpDecls.resize(NumExprs);
4236 Constraints.resize(NumExprs);
4237 for (unsigned i = 0; i < NumOutputs; ++i) {
4238 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4239 Constraints[i] = OutputConstraints[i];
4241 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4242 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4243 Constraints[j] = InputConstraints[i];
4247 // Build the IR assembly string.
4248 std::string AsmStringIR;
4249 raw_string_ostream OS(AsmStringIR);
4250 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4251 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4252 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4253 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4254 E = AsmStrRewrites.end();
4256 AsmRewriteKind Kind = (*I).Kind;
4257 if (Kind == AOK_Delete)
4260 const char *Loc = (*I).Loc.getPointer();
4261 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4263 // Emit everything up to the immediate/expression.
4264 unsigned Len = Loc - AsmStart;
4266 OS << StringRef(AsmStart, Len);
4268 // Skip the original expression.
4269 if (Kind == AOK_Skip) {
4270 AsmStart = Loc + (*I).Len;
4274 unsigned AdditionalSkip = 0;
4275 // Rewrite expressions in $N notation.
4280 OS << "$$" << (*I).Val;
4286 OS << '$' << InputIdx++;
4289 OS << '$' << OutputIdx++;
4291 case AOK_SizeDirective:
4294 case 8: OS << "byte ptr "; break;
4295 case 16: OS << "word ptr "; break;
4296 case 32: OS << "dword ptr "; break;
4297 case 64: OS << "qword ptr "; break;
4298 case 80: OS << "xword ptr "; break;
4299 case 128: OS << "xmmword ptr "; break;
4300 case 256: OS << "ymmword ptr "; break;
4307 unsigned Val = (*I).Val;
4308 OS << ".align " << Val;
4310 // Skip the original immediate.
4311 assert(Val < 10 && "Expected alignment less then 2^10.");
4312 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4315 case AOK_DotOperator:
4320 // Skip the original expression.
4321 AsmStart = Loc + (*I).Len + AdditionalSkip;
4324 // Emit the remainder of the asm string.
4325 if (AsmStart != AsmEnd)
4326 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4328 AsmString = OS.str();
4332 /// \brief Create an MCAsmParser instance.
4333 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4334 MCStreamer &Out, const MCAsmInfo &MAI) {
4335 return new AsmParser(SM, C, Out, MAI);