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/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/AsmCond.h"
25 #include "llvm/MC/MCParser/AsmLexer.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCTargetAsmParser.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/raw_ostream.h"
46 FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
51 /// \brief Helper class for tracking macro definitions.
52 typedef std::vector<AsmToken> MacroArgument;
53 typedef std::vector<MacroArgument> MacroArguments;
54 typedef std::pair<StringRef, MacroArgument> MacroParameter;
55 typedef std::vector<MacroParameter> MacroParameters;
60 MacroParameters Parameters;
63 Macro(StringRef N, StringRef B, const MacroParameters &P) :
64 Name(N), Body(B), Parameters(P) {}
67 /// \brief Helper class for storing information about an active macro
69 struct MacroInstantiation {
70 /// The macro being instantiated.
71 const Macro *TheMacro;
73 /// The macro instantiation with substitutions.
74 MemoryBuffer *Instantiation;
76 /// The location of the instantiation.
77 SMLoc InstantiationLoc;
79 /// The location where parsing should resume upon instantiation completion.
83 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
87 /// \brief The concrete assembly parser instance.
88 class AsmParser : public MCAsmParser {
89 friend class GenericAsmParser;
91 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
92 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
99 SourceMgr::DiagHandlerTy SavedDiagHandler;
100 void *SavedDiagContext;
101 MCAsmParserExtension *GenericParser;
102 MCAsmParserExtension *PlatformParser;
104 /// This is the current buffer index we're lexing from as managed by the
105 /// SourceMgr object.
108 AsmCond TheCondState;
109 std::vector<AsmCond> TheCondStack;
111 /// DirectiveMap - This is a table handlers for directives. Each handler is
112 /// invoked after the directive identifier is read and is responsible for
113 /// parsing and validating the rest of the directive. The handler is passed
114 /// in the directive name and the location of the directive keyword.
115 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
117 /// MacroMap - Map of currently defined macros.
118 StringMap<Macro*> MacroMap;
120 /// ActiveMacros - Stack of active macro instantiations.
121 std::vector<MacroInstantiation*> ActiveMacros;
123 /// Boolean tracking whether macro substitution is enabled.
124 unsigned MacrosEnabled : 1;
126 /// Flag tracking whether any errors have been encountered.
127 unsigned HadError : 1;
129 /// The values from the last parsed cpp hash file line comment if any.
130 StringRef CppHashFilename;
131 int64_t CppHashLineNumber;
134 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
135 unsigned AssemblerDialect;
137 /// IsDarwin - is Darwin compatibility enabled?
140 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
141 bool ParsingInlineAsm;
143 /// ParsedOperands - The parsed operands from the last parsed statement.
144 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
146 /// Opcode - The opcode from the last parsed instruction. This is MS-style
147 /// inline asm specific.
151 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
152 const MCAsmInfo &MAI);
153 virtual ~AsmParser();
155 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
157 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
159 DirectiveHandler Handler) {
160 DirectiveMap[Directive] = std::make_pair(Object, Handler);
164 /// @name MCAsmParser Interface
167 virtual SourceMgr &getSourceManager() { return SrcMgr; }
168 virtual MCAsmLexer &getLexer() { return Lexer; }
169 virtual MCContext &getContext() { return Ctx; }
170 virtual MCStreamer &getStreamer() { return Out; }
171 virtual unsigned getAssemblerDialect() {
172 if (AssemblerDialect == ~0U)
173 return MAI.getAssemblerDialect();
175 return AssemblerDialect;
177 virtual void setAssemblerDialect(unsigned i) {
178 AssemblerDialect = i;
181 virtual bool Warning(SMLoc L, const Twine &Msg,
182 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
183 virtual bool Error(SMLoc L, const Twine &Msg,
184 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
186 virtual const AsmToken &Lex();
188 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
189 bool isParsingInlineAsm() { return ParsingInlineAsm; }
191 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
192 unsigned &NumOutputs, unsigned &NumInputs,
193 SmallVectorImpl<void *> &OpDecls,
194 SmallVectorImpl<std::string> &Constraints,
195 SmallVectorImpl<std::string> &Clobbers,
196 const MCInstrInfo *MII,
197 const MCInstPrinter *IP,
198 MCAsmParserSemaCallback &SI);
200 bool ParseExpression(const MCExpr *&Res);
201 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
202 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
203 virtual bool ParseAbsoluteExpression(int64_t &Res);
208 void CheckForValidSection();
210 bool ParseStatement();
211 void EatToEndOfLine();
212 bool ParseCppHashLineFilenameComment(const SMLoc &L);
214 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
215 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
216 const MacroParameters &Parameters,
217 const MacroArguments &A,
219 void HandleMacroExit();
221 void PrintMacroInstantiations();
222 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
223 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
224 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
226 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
228 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
229 bool EnterIncludeFile(const std::string &Filename);
230 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
231 /// This returns true on failure.
232 bool ProcessIncbinFile(const std::string &Filename);
234 /// \brief Reset the current lexer position to that given by \p Loc. The
235 /// current token is not set; clients should ensure Lex() is called
237 void JumpToLoc(SMLoc Loc);
239 virtual void EatToEndOfStatement();
241 bool ParseMacroArgument(MacroArgument &MA,
242 AsmToken::TokenKind &ArgumentDelimiter);
243 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
245 /// \brief Parse up to the end of statement and a return the contents from the
246 /// current token until the end of the statement; the current token on exit
247 /// will be either the EndOfStatement or EOF.
248 virtual StringRef ParseStringToEndOfStatement();
250 /// \brief Parse until the end of a statement or a comma is encountered,
251 /// return the contents from the current token up to the end or comma.
252 StringRef ParseStringToComma();
254 bool ParseAssignment(StringRef Name, bool allow_redef,
255 bool NoDeadStrip = false);
257 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
258 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
259 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
260 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
262 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
263 /// and set \p Res to the identifier contents.
264 virtual bool ParseIdentifier(StringRef &Res);
266 // Directive Parsing.
268 // ".ascii", ".asciiz", ".string"
269 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
270 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
271 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
272 bool ParseDirectiveFill(); // ".fill"
273 bool ParseDirectiveSpace(); // ".space"
274 bool ParseDirectiveZero(); // ".zero"
275 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
276 bool ParseDirectiveOrg(); // ".org"
277 // ".align{,32}", ".p2align{,w,l}"
278 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
280 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
281 /// accepts a single symbol (which should be a label or an external).
282 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
284 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
286 bool ParseDirectiveAbort(); // ".abort"
287 bool ParseDirectiveInclude(); // ".include"
288 bool ParseDirectiveIncbin(); // ".incbin"
290 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
291 // ".ifb" or ".ifnb", depending on ExpectBlank.
292 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
293 // ".ifc" or ".ifnc", depending on ExpectEqual.
294 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
295 // ".ifdef" or ".ifndef", depending on expect_defined
296 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
297 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
298 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
299 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
301 /// ParseEscapedString - Parse the current token as a string which may include
302 /// escaped characters and return the string contents.
303 bool ParseEscapedString(std::string &Data);
305 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
306 MCSymbolRefExpr::VariantKind Variant);
308 // Macro-like directives
309 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
310 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
311 raw_svector_ostream &OS);
312 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
313 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
314 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
315 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
317 // MS-style inline assembly parsing.
318 bool isInstruction() { return Opcode != (unsigned)~0x0; }
319 unsigned getOpcode() { return Opcode; }
322 /// \brief Generic implementations of directive handling, etc. which is shared
323 /// (or the default, at least) for all assembler parser.
324 class GenericAsmParser : public MCAsmParserExtension {
325 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
326 void AddDirectiveHandler(StringRef Directive) {
327 getParser().AddDirectiveHandler(this, Directive,
328 HandleDirective<GenericAsmParser, Handler>);
331 GenericAsmParser() {}
333 AsmParser &getParser() {
334 return (AsmParser&) this->MCAsmParserExtension::getParser();
337 virtual void Initialize(MCAsmParser &Parser) {
338 // Call the base implementation.
339 this->MCAsmParserExtension::Initialize(Parser);
341 // Debugging directives.
342 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
343 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
344 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
345 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
348 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
350 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
352 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
354 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
356 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
357 ".cfi_def_cfa_offset");
358 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
359 ".cfi_adjust_cfa_offset");
360 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
361 ".cfi_def_cfa_register");
362 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
364 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
367 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
369 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
371 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
373 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
375 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
377 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
379 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
381 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
384 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
386 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
388 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
389 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
391 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
393 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
394 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
397 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
399 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
400 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
401 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
402 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
403 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
404 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
405 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
406 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
407 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
408 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
409 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
410 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
411 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
412 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
413 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
414 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
415 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
416 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
417 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
418 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
420 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
421 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
422 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
423 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
425 bool ParseDirectiveLEB128(StringRef, SMLoc);
432 extern MCAsmParserExtension *createDarwinAsmParser();
433 extern MCAsmParserExtension *createELFAsmParser();
434 extern MCAsmParserExtension *createCOFFAsmParser();
438 enum { DEFAULT_ADDRSPACE = 0 };
440 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
441 MCStreamer &_Out, const MCAsmInfo &_MAI)
442 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
443 GenericParser(new GenericAsmParser), PlatformParser(0),
444 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
445 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false),
447 // Save the old handler.
448 SavedDiagHandler = SrcMgr.getDiagHandler();
449 SavedDiagContext = SrcMgr.getDiagContext();
450 // Set our own handler which calls the saved handler.
451 SrcMgr.setDiagHandler(DiagHandler, this);
452 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
454 // Initialize the generic parser.
455 GenericParser->Initialize(*this);
457 // Initialize the platform / file format parser.
459 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
461 if (_MAI.hasMicrosoftFastStdCallMangling()) {
462 PlatformParser = createCOFFAsmParser();
463 PlatformParser->Initialize(*this);
464 } else if (_MAI.hasSubsectionsViaSymbols()) {
465 PlatformParser = createDarwinAsmParser();
466 PlatformParser->Initialize(*this);
469 PlatformParser = createELFAsmParser();
470 PlatformParser->Initialize(*this);
474 AsmParser::~AsmParser() {
475 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
477 // Destroy any macros.
478 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
479 ie = MacroMap.end(); it != ie; ++it)
480 delete it->getValue();
482 delete PlatformParser;
483 delete GenericParser;
486 void AsmParser::PrintMacroInstantiations() {
487 // Print the active macro instantiation stack.
488 for (std::vector<MacroInstantiation*>::const_reverse_iterator
489 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
490 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
491 "while in macro instantiation");
494 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
495 if (FatalAssemblerWarnings)
496 return Error(L, Msg, Ranges);
497 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
498 PrintMacroInstantiations();
502 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
504 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
505 PrintMacroInstantiations();
509 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
510 std::string IncludedFile;
511 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
517 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
522 /// Process the specified .incbin file by seaching for it in the include paths
523 /// then just emitting the byte contents of the file to the streamer. This
524 /// returns true on failure.
525 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
526 std::string IncludedFile;
527 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
531 // Pick up the bytes from the file and emit them.
532 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
537 void AsmParser::JumpToLoc(SMLoc Loc) {
538 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
539 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
542 const AsmToken &AsmParser::Lex() {
543 const AsmToken *tok = &Lexer.Lex();
545 if (tok->is(AsmToken::Eof)) {
546 // If this is the end of an included file, pop the parent file off the
548 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
549 if (ParentIncludeLoc != SMLoc()) {
550 JumpToLoc(ParentIncludeLoc);
555 if (tok->is(AsmToken::Error))
556 Error(Lexer.getErrLoc(), Lexer.getErr());
561 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
562 // Create the initial section, if requested.
563 if (!NoInitialTextSection)
570 AsmCond StartingCondState = TheCondState;
572 // If we are generating dwarf for assembly source files save the initial text
573 // section and generate a .file directive.
574 if (getContext().getGenDwarfForAssembly()) {
575 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
576 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
577 getStreamer().EmitLabel(SectionStartSym);
578 getContext().setGenDwarfSectionStartSym(SectionStartSym);
579 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
580 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
583 // While we have input, parse each statement.
584 while (Lexer.isNot(AsmToken::Eof)) {
585 if (!ParseStatement()) continue;
587 // We had an error, validate that one was emitted and recover by skipping to
589 assert(HadError && "Parse statement returned an error, but none emitted!");
590 EatToEndOfStatement();
593 if (TheCondState.TheCond != StartingCondState.TheCond ||
594 TheCondState.Ignore != StartingCondState.Ignore)
595 return TokError("unmatched .ifs or .elses");
597 // Check to see there are no empty DwarfFile slots.
598 const std::vector<MCDwarfFile *> &MCDwarfFiles =
599 getContext().getMCDwarfFiles();
600 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
601 if (!MCDwarfFiles[i])
602 TokError("unassigned file number: " + Twine(i) + " for .file directives");
605 // Check to see that all assembler local symbols were actually defined.
606 // Targets that don't do subsections via symbols may not want this, though,
607 // so conservatively exclude them. Only do this if we're finalizing, though,
608 // as otherwise we won't necessarilly have seen everything yet.
609 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
610 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
611 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
614 MCSymbol *Sym = i->getValue();
615 // Variable symbols may not be marked as defined, so check those
616 // explicitly. If we know it's a variable, we have a definition for
617 // the purposes of this check.
618 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
619 // FIXME: We would really like to refer back to where the symbol was
620 // first referenced for a source location. We need to add something
621 // to track that. Currently, we just point to the end of the file.
622 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
623 "assembler local symbol '" + Sym->getName() +
629 // Finalize the output stream if there are no errors and if the client wants
631 if (!HadError && !NoFinalize)
637 void AsmParser::CheckForValidSection() {
638 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
639 TokError("expected section directive before assembly directive");
640 Out.SwitchSection(Ctx.getMachOSection(
642 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
643 0, SectionKind::getText()));
647 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
648 void AsmParser::EatToEndOfStatement() {
649 while (Lexer.isNot(AsmToken::EndOfStatement) &&
650 Lexer.isNot(AsmToken::Eof))
654 if (Lexer.is(AsmToken::EndOfStatement))
658 StringRef AsmParser::ParseStringToEndOfStatement() {
659 const char *Start = getTok().getLoc().getPointer();
661 while (Lexer.isNot(AsmToken::EndOfStatement) &&
662 Lexer.isNot(AsmToken::Eof))
665 const char *End = getTok().getLoc().getPointer();
666 return StringRef(Start, End - Start);
669 StringRef AsmParser::ParseStringToComma() {
670 const char *Start = getTok().getLoc().getPointer();
672 while (Lexer.isNot(AsmToken::EndOfStatement) &&
673 Lexer.isNot(AsmToken::Comma) &&
674 Lexer.isNot(AsmToken::Eof))
677 const char *End = getTok().getLoc().getPointer();
678 return StringRef(Start, End - Start);
681 /// ParseParenExpr - Parse a paren expression and return it.
682 /// NOTE: This assumes the leading '(' has already been consumed.
684 /// parenexpr ::= expr)
686 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
687 if (ParseExpression(Res)) return true;
688 if (Lexer.isNot(AsmToken::RParen))
689 return TokError("expected ')' in parentheses expression");
690 EndLoc = Lexer.getLoc();
695 /// ParseBracketExpr - Parse a bracket expression and return it.
696 /// NOTE: This assumes the leading '[' has already been consumed.
698 /// bracketexpr ::= expr]
700 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
701 if (ParseExpression(Res)) return true;
702 if (Lexer.isNot(AsmToken::RBrac))
703 return TokError("expected ']' in brackets expression");
704 EndLoc = Lexer.getLoc();
709 /// ParsePrimaryExpr - Parse a primary expression and return it.
710 /// primaryexpr ::= (parenexpr
711 /// primaryexpr ::= symbol
712 /// primaryexpr ::= number
713 /// primaryexpr ::= '.'
714 /// primaryexpr ::= ~,+,- primaryexpr
715 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
716 switch (Lexer.getKind()) {
718 return TokError("unknown token in expression");
719 // If we have an error assume that we've already handled it.
720 case AsmToken::Error:
722 case AsmToken::Exclaim:
723 Lex(); // Eat the operator.
724 if (ParsePrimaryExpr(Res, EndLoc))
726 Res = MCUnaryExpr::CreateLNot(Res, getContext());
728 case AsmToken::Dollar:
729 case AsmToken::String:
730 case AsmToken::Identifier: {
731 EndLoc = Lexer.getLoc();
733 StringRef Identifier;
734 if (ParseIdentifier(Identifier))
737 // This is a symbol reference.
738 std::pair<StringRef, StringRef> Split = Identifier.split('@');
739 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
741 // Lookup the symbol variant if used.
742 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
743 if (Split.first.size() != Identifier.size()) {
744 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
745 if (Variant == MCSymbolRefExpr::VK_Invalid) {
746 Variant = MCSymbolRefExpr::VK_None;
747 return TokError("invalid variant '" + Split.second + "'");
751 // If this is an absolute variable reference, substitute it now to preserve
752 // semantics in the face of reassignment.
753 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
755 return Error(EndLoc, "unexpected modifier on variable reference");
757 Res = Sym->getVariableValue();
761 // Otherwise create a symbol ref.
762 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
765 case AsmToken::Integer: {
766 SMLoc Loc = getTok().getLoc();
767 int64_t IntVal = getTok().getIntVal();
768 Res = MCConstantExpr::Create(IntVal, getContext());
769 EndLoc = Lexer.getLoc();
771 // Look for 'b' or 'f' following an Integer as a directional label
772 if (Lexer.getKind() == AsmToken::Identifier) {
773 StringRef IDVal = getTok().getString();
774 if (IDVal == "f" || IDVal == "b"){
775 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
776 IDVal == "f" ? 1 : 0);
777 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
779 if (IDVal == "b" && Sym->isUndefined())
780 return Error(Loc, "invalid reference to undefined symbol");
781 EndLoc = Lexer.getLoc();
782 Lex(); // Eat identifier.
787 case AsmToken::Real: {
788 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
789 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
790 Res = MCConstantExpr::Create(IntVal, getContext());
794 case AsmToken::Dot: {
795 // This is a '.' reference, which references the current PC. Emit a
796 // temporary label to the streamer and refer to it.
797 MCSymbol *Sym = Ctx.CreateTempSymbol();
799 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
800 EndLoc = Lexer.getLoc();
801 Lex(); // Eat identifier.
804 case AsmToken::LParen:
805 Lex(); // Eat the '('.
806 return ParseParenExpr(Res, EndLoc);
807 case AsmToken::LBrac:
808 if (!PlatformParser->HasBracketExpressions())
809 return TokError("brackets expression not supported on this target");
810 Lex(); // Eat the '['.
811 return ParseBracketExpr(Res, EndLoc);
812 case AsmToken::Minus:
813 Lex(); // Eat the operator.
814 if (ParsePrimaryExpr(Res, EndLoc))
816 Res = MCUnaryExpr::CreateMinus(Res, getContext());
819 Lex(); // Eat the operator.
820 if (ParsePrimaryExpr(Res, EndLoc))
822 Res = MCUnaryExpr::CreatePlus(Res, getContext());
824 case AsmToken::Tilde:
825 Lex(); // Eat the operator.
826 if (ParsePrimaryExpr(Res, EndLoc))
828 Res = MCUnaryExpr::CreateNot(Res, getContext());
833 bool AsmParser::ParseExpression(const MCExpr *&Res) {
835 return ParseExpression(Res, EndLoc);
839 AsmParser::ApplyModifierToExpr(const MCExpr *E,
840 MCSymbolRefExpr::VariantKind Variant) {
841 // Recurse over the given expression, rebuilding it to apply the given variant
842 // if there is exactly one symbol.
843 switch (E->getKind()) {
845 case MCExpr::Constant:
848 case MCExpr::SymbolRef: {
849 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
851 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
852 TokError("invalid variant on expression '" +
853 getTok().getIdentifier() + "' (already modified)");
857 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
860 case MCExpr::Unary: {
861 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
862 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
865 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
868 case MCExpr::Binary: {
869 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
870 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
871 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
876 if (!LHS) LHS = BE->getLHS();
877 if (!RHS) RHS = BE->getRHS();
879 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
883 llvm_unreachable("Invalid expression kind!");
886 /// ParseExpression - Parse an expression and return it.
888 /// expr ::= expr &&,|| expr -> lowest.
889 /// expr ::= expr |,^,&,! expr
890 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
891 /// expr ::= expr <<,>> expr
892 /// expr ::= expr +,- expr
893 /// expr ::= expr *,/,% expr -> highest.
894 /// expr ::= primaryexpr
896 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
897 // Parse the expression.
899 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
902 // As a special case, we support 'a op b @ modifier' by rewriting the
903 // expression to include the modifier. This is inefficient, but in general we
904 // expect users to use 'a@modifier op b'.
905 if (Lexer.getKind() == AsmToken::At) {
908 if (Lexer.isNot(AsmToken::Identifier))
909 return TokError("unexpected symbol modifier following '@'");
911 MCSymbolRefExpr::VariantKind Variant =
912 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
913 if (Variant == MCSymbolRefExpr::VK_Invalid)
914 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
916 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
918 return TokError("invalid modifier '" + getTok().getIdentifier() +
919 "' (no symbols present)");
926 // Try to constant fold it up front, if possible.
928 if (Res->EvaluateAsAbsolute(Value))
929 Res = MCConstantExpr::Create(Value, getContext());
934 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
936 return ParseParenExpr(Res, EndLoc) ||
937 ParseBinOpRHS(1, Res, EndLoc);
940 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
943 SMLoc StartLoc = Lexer.getLoc();
944 if (ParseExpression(Expr))
947 if (!Expr->EvaluateAsAbsolute(Res))
948 return Error(StartLoc, "expected absolute expression");
953 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
954 MCBinaryExpr::Opcode &Kind) {
957 return 0; // not a binop.
959 // Lowest Precedence: &&, ||
960 case AsmToken::AmpAmp:
961 Kind = MCBinaryExpr::LAnd;
963 case AsmToken::PipePipe:
964 Kind = MCBinaryExpr::LOr;
968 // Low Precedence: |, &, ^
970 // FIXME: gas seems to support '!' as an infix operator?
972 Kind = MCBinaryExpr::Or;
974 case AsmToken::Caret:
975 Kind = MCBinaryExpr::Xor;
978 Kind = MCBinaryExpr::And;
981 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
982 case AsmToken::EqualEqual:
983 Kind = MCBinaryExpr::EQ;
985 case AsmToken::ExclaimEqual:
986 case AsmToken::LessGreater:
987 Kind = MCBinaryExpr::NE;
990 Kind = MCBinaryExpr::LT;
992 case AsmToken::LessEqual:
993 Kind = MCBinaryExpr::LTE;
995 case AsmToken::Greater:
996 Kind = MCBinaryExpr::GT;
998 case AsmToken::GreaterEqual:
999 Kind = MCBinaryExpr::GTE;
1002 // Intermediate Precedence: <<, >>
1003 case AsmToken::LessLess:
1004 Kind = MCBinaryExpr::Shl;
1006 case AsmToken::GreaterGreater:
1007 Kind = MCBinaryExpr::Shr;
1010 // High Intermediate Precedence: +, -
1011 case AsmToken::Plus:
1012 Kind = MCBinaryExpr::Add;
1014 case AsmToken::Minus:
1015 Kind = MCBinaryExpr::Sub;
1018 // Highest Precedence: *, /, %
1019 case AsmToken::Star:
1020 Kind = MCBinaryExpr::Mul;
1022 case AsmToken::Slash:
1023 Kind = MCBinaryExpr::Div;
1025 case AsmToken::Percent:
1026 Kind = MCBinaryExpr::Mod;
1032 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1033 /// Res contains the LHS of the expression on input.
1034 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1037 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1038 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1040 // If the next token is lower precedence than we are allowed to eat, return
1041 // successfully with what we ate already.
1042 if (TokPrec < Precedence)
1047 // Eat the next primary expression.
1049 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1051 // If BinOp binds less tightly with RHS than the operator after RHS, let
1052 // the pending operator take RHS as its LHS.
1053 MCBinaryExpr::Opcode Dummy;
1054 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1055 if (TokPrec < NextTokPrec) {
1056 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1059 // Merge LHS and RHS according to operator.
1060 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1065 /// ::= EndOfStatement
1066 /// ::= Label* Directive ...Operands... EndOfStatement
1067 /// ::= Label* Identifier OperandList* EndOfStatement
1068 bool AsmParser::ParseStatement() {
1069 if (Lexer.is(AsmToken::EndOfStatement)) {
1075 // Statements always start with an identifier or are a full line comment.
1076 AsmToken ID = getTok();
1077 SMLoc IDLoc = ID.getLoc();
1079 int64_t LocalLabelVal = -1;
1080 // A full line comment is a '#' as the first token.
1081 if (Lexer.is(AsmToken::Hash))
1082 return ParseCppHashLineFilenameComment(IDLoc);
1084 // Allow an integer followed by a ':' as a directional local label.
1085 if (Lexer.is(AsmToken::Integer)) {
1086 LocalLabelVal = getTok().getIntVal();
1087 if (LocalLabelVal < 0) {
1088 if (!TheCondState.Ignore)
1089 return TokError("unexpected token at start of statement");
1093 IDVal = getTok().getString();
1094 Lex(); // Consume the integer token to be used as an identifier token.
1095 if (Lexer.getKind() != AsmToken::Colon) {
1096 if (!TheCondState.Ignore)
1097 return TokError("unexpected token at start of statement");
1101 } else if (Lexer.is(AsmToken::Dot)) {
1102 // Treat '.' as a valid identifier in this context.
1106 } else if (ParseIdentifier(IDVal)) {
1107 if (!TheCondState.Ignore)
1108 return TokError("unexpected token at start of statement");
1113 // Handle conditional assembly here before checking for skipping. We
1114 // have to do this so that .endif isn't skipped in a ".if 0" block for
1117 return ParseDirectiveIf(IDLoc);
1118 if (IDVal == ".ifb")
1119 return ParseDirectiveIfb(IDLoc, true);
1120 if (IDVal == ".ifnb")
1121 return ParseDirectiveIfb(IDLoc, false);
1122 if (IDVal == ".ifc")
1123 return ParseDirectiveIfc(IDLoc, true);
1124 if (IDVal == ".ifnc")
1125 return ParseDirectiveIfc(IDLoc, false);
1126 if (IDVal == ".ifdef")
1127 return ParseDirectiveIfdef(IDLoc, true);
1128 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1129 return ParseDirectiveIfdef(IDLoc, false);
1130 if (IDVal == ".elseif")
1131 return ParseDirectiveElseIf(IDLoc);
1132 if (IDVal == ".else")
1133 return ParseDirectiveElse(IDLoc);
1134 if (IDVal == ".endif")
1135 return ParseDirectiveEndIf(IDLoc);
1137 // If we are in a ".if 0" block, ignore this statement.
1138 if (TheCondState.Ignore) {
1139 EatToEndOfStatement();
1143 // FIXME: Recurse on local labels?
1145 // See what kind of statement we have.
1146 switch (Lexer.getKind()) {
1147 case AsmToken::Colon: {
1148 CheckForValidSection();
1150 // identifier ':' -> Label.
1153 // Diagnose attempt to use '.' as a label.
1155 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1157 // Diagnose attempt to use a variable as a label.
1159 // FIXME: Diagnostics. Note the location of the definition as a label.
1160 // FIXME: This doesn't diagnose assignment to a symbol which has been
1161 // implicitly marked as external.
1163 if (LocalLabelVal == -1)
1164 Sym = getContext().GetOrCreateSymbol(IDVal);
1166 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1167 if (!Sym->isUndefined() || Sym->isVariable())
1168 return Error(IDLoc, "invalid symbol redefinition");
1173 // If we are generating dwarf for assembly source files then gather the
1174 // info to make a dwarf label entry for this label if needed.
1175 if (getContext().getGenDwarfForAssembly())
1176 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1179 // Consume any end of statement token, if present, to avoid spurious
1180 // AddBlankLine calls().
1181 if (Lexer.is(AsmToken::EndOfStatement)) {
1183 if (Lexer.is(AsmToken::Eof))
1187 return ParseStatement();
1190 case AsmToken::Equal:
1191 // identifier '=' ... -> assignment statement
1194 return ParseAssignment(IDVal, true);
1196 default: // Normal instruction or directive.
1200 // If macros are enabled, check to see if this is a macro instantiation.
1202 if (const Macro *M = MacroMap.lookup(IDVal))
1203 return HandleMacroEntry(IDVal, IDLoc, M);
1205 // Otherwise, we have a normal instruction or directive.
1206 if (IDVal[0] == '.' && IDVal != ".") {
1208 // Target hook for parsing target specific directives.
1209 if (!getTargetParser().ParseDirective(ID))
1212 // Assembler features
1213 if (IDVal == ".set" || IDVal == ".equ")
1214 return ParseDirectiveSet(IDVal, true);
1215 if (IDVal == ".equiv")
1216 return ParseDirectiveSet(IDVal, false);
1220 if (IDVal == ".ascii")
1221 return ParseDirectiveAscii(IDVal, false);
1222 if (IDVal == ".asciz" || IDVal == ".string")
1223 return ParseDirectiveAscii(IDVal, true);
1225 if (IDVal == ".byte")
1226 return ParseDirectiveValue(1);
1227 if (IDVal == ".short")
1228 return ParseDirectiveValue(2);
1229 if (IDVal == ".value")
1230 return ParseDirectiveValue(2);
1231 if (IDVal == ".2byte")
1232 return ParseDirectiveValue(2);
1233 if (IDVal == ".long")
1234 return ParseDirectiveValue(4);
1235 if (IDVal == ".int")
1236 return ParseDirectiveValue(4);
1237 if (IDVal == ".4byte")
1238 return ParseDirectiveValue(4);
1239 if (IDVal == ".quad")
1240 return ParseDirectiveValue(8);
1241 if (IDVal == ".8byte")
1242 return ParseDirectiveValue(8);
1243 if (IDVal == ".single" || IDVal == ".float")
1244 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1245 if (IDVal == ".double")
1246 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1248 if (IDVal == ".align") {
1249 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1250 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1252 if (IDVal == ".align32") {
1253 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1254 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1256 if (IDVal == ".balign")
1257 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1258 if (IDVal == ".balignw")
1259 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1260 if (IDVal == ".balignl")
1261 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1262 if (IDVal == ".p2align")
1263 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1264 if (IDVal == ".p2alignw")
1265 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1266 if (IDVal == ".p2alignl")
1267 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1269 if (IDVal == ".org")
1270 return ParseDirectiveOrg();
1272 if (IDVal == ".fill")
1273 return ParseDirectiveFill();
1274 if (IDVal == ".space" || IDVal == ".skip")
1275 return ParseDirectiveSpace();
1276 if (IDVal == ".zero")
1277 return ParseDirectiveZero();
1279 // Symbol attribute directives
1281 if (IDVal == ".extern") {
1282 EatToEndOfStatement(); // .extern is the default, ignore it.
1285 if (IDVal == ".globl" || IDVal == ".global")
1286 return ParseDirectiveSymbolAttribute(MCSA_Global);
1287 if (IDVal == ".indirect_symbol")
1288 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1289 if (IDVal == ".lazy_reference")
1290 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1291 if (IDVal == ".no_dead_strip")
1292 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1293 if (IDVal == ".symbol_resolver")
1294 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1295 if (IDVal == ".private_extern")
1296 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1297 if (IDVal == ".reference")
1298 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1299 if (IDVal == ".weak_definition")
1300 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1301 if (IDVal == ".weak_reference")
1302 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1303 if (IDVal == ".weak_def_can_be_hidden")
1304 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1306 if (IDVal == ".comm" || IDVal == ".common")
1307 return ParseDirectiveComm(/*IsLocal=*/false);
1308 if (IDVal == ".lcomm")
1309 return ParseDirectiveComm(/*IsLocal=*/true);
1311 if (IDVal == ".abort")
1312 return ParseDirectiveAbort();
1313 if (IDVal == ".include")
1314 return ParseDirectiveInclude();
1315 if (IDVal == ".incbin")
1316 return ParseDirectiveIncbin();
1318 if (IDVal == ".code16" || IDVal == ".code16gcc")
1319 return TokError(Twine(IDVal) + " not supported yet");
1321 // Macro-like directives
1322 if (IDVal == ".rept")
1323 return ParseDirectiveRept(IDLoc);
1324 if (IDVal == ".irp")
1325 return ParseDirectiveIrp(IDLoc);
1326 if (IDVal == ".irpc")
1327 return ParseDirectiveIrpc(IDLoc);
1328 if (IDVal == ".endr")
1329 return ParseDirectiveEndr(IDLoc);
1331 // Look up the handler in the handler table.
1332 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1333 DirectiveMap.lookup(IDVal);
1335 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1338 return Error(IDLoc, "unknown directive");
1341 CheckForValidSection();
1343 // Canonicalize the opcode to lower case.
1344 SmallString<128> OpcodeStr;
1345 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1346 OpcodeStr.push_back(tolower(IDVal[i]));
1348 bool HadError = getTargetParser().ParseInstruction(OpcodeStr.str(), IDLoc,
1351 // Dump the parsed representation, if requested.
1352 if (getShowParsedOperands()) {
1353 SmallString<256> Str;
1354 raw_svector_ostream OS(Str);
1355 OS << "parsed instruction: [";
1356 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1359 ParsedOperands[i]->print(OS);
1363 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1366 // If we are generating dwarf for assembly source files and the current
1367 // section is the initial text section then generate a .loc directive for
1369 if (!HadError && getContext().getGenDwarfForAssembly() &&
1370 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1371 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1372 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1373 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1374 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1378 // If parsing succeeded, match the instruction.
1381 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Opcode,
1382 ParsedOperands, Out,
1387 // Free any parsed operands. If parsing ms-style inline assembly the operands
1388 // will be freed by the ParseMSInlineAsm() function.
1389 if (!ParsingInlineAsm) {
1390 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1391 delete ParsedOperands[i];
1392 ParsedOperands.clear();
1395 // Don't skip the rest of the line, the instruction parser is responsible for
1400 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1401 /// since they may not be able to be tokenized to get to the end of line token.
1402 void AsmParser::EatToEndOfLine() {
1403 if (!Lexer.is(AsmToken::EndOfStatement))
1404 Lexer.LexUntilEndOfLine();
1409 /// ParseCppHashLineFilenameComment as this:
1410 /// ::= # number "filename"
1411 /// or just as a full line comment if it doesn't have a number and a string.
1412 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1413 Lex(); // Eat the hash token.
1415 if (getLexer().isNot(AsmToken::Integer)) {
1416 // Consume the line since in cases it is not a well-formed line directive,
1417 // as if were simply a full line comment.
1422 int64_t LineNumber = getTok().getIntVal();
1425 if (getLexer().isNot(AsmToken::String)) {
1430 StringRef Filename = getTok().getString();
1431 // Get rid of the enclosing quotes.
1432 Filename = Filename.substr(1, Filename.size()-2);
1434 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1436 CppHashFilename = Filename;
1437 CppHashLineNumber = LineNumber;
1439 // Ignore any trailing characters, they're just comment.
1444 /// DiagHandler - will use the last parsed cpp hash line filename comment
1445 /// for the Filename and LineNo if any in the diagnostic.
1446 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1447 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1448 raw_ostream &OS = errs();
1450 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1451 const SMLoc &DiagLoc = Diag.getLoc();
1452 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1453 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1455 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1456 // before printing the message.
1457 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1458 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1459 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1460 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1463 // If we have not parsed a cpp hash line filename comment or the source
1464 // manager changed or buffer changed (like in a nested include) then just
1465 // print the normal diagnostic using its Filename and LineNo.
1466 if (!Parser->CppHashLineNumber ||
1467 &DiagSrcMgr != &Parser->SrcMgr ||
1468 DiagBuf != CppHashBuf) {
1469 if (Parser->SavedDiagHandler)
1470 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1476 // Use the CppHashFilename and calculate a line number based on the
1477 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1479 const std::string Filename = Parser->CppHashFilename;
1481 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1482 int CppHashLocLineNo =
1483 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1484 int LineNo = Parser->CppHashLineNumber - 1 +
1485 (DiagLocLineNo - CppHashLocLineNo);
1487 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1488 Filename, LineNo, Diag.getColumnNo(),
1489 Diag.getKind(), Diag.getMessage(),
1490 Diag.getLineContents(), Diag.getRanges());
1492 if (Parser->SavedDiagHandler)
1493 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1495 NewDiag.print(0, OS);
1498 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1499 // difference being that that function accepts '@' as part of identifiers and
1500 // we can't do that. AsmLexer.cpp should probably be changed to handle
1501 // '@' as a special case when needed.
1502 static bool isIdentifierChar(char c) {
1503 return isalnum(c) || c == '_' || c == '$' || c == '.';
1506 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1507 const MacroParameters &Parameters,
1508 const MacroArguments &A,
1510 unsigned NParameters = Parameters.size();
1511 if (NParameters != 0 && NParameters != A.size())
1512 return Error(L, "Wrong number of arguments");
1514 // A macro without parameters is handled differently on Darwin:
1515 // gas accepts no arguments and does no substitutions
1516 while (!Body.empty()) {
1517 // Scan for the next substitution.
1518 std::size_t End = Body.size(), Pos = 0;
1519 for (; Pos != End; ++Pos) {
1520 // Check for a substitution or escape.
1522 // This macro has no parameters, look for $0, $1, etc.
1523 if (Body[Pos] != '$' || Pos + 1 == End)
1526 char Next = Body[Pos + 1];
1527 if (Next == '$' || Next == 'n' || isdigit(Next))
1530 // This macro has parameters, look for \foo, \bar, etc.
1531 if (Body[Pos] == '\\' && Pos + 1 != End)
1537 OS << Body.slice(0, Pos);
1539 // Check if we reached the end.
1544 switch (Body[Pos+1]) {
1550 // $n => number of arguments
1555 // $[0-9] => argument
1557 // Missing arguments are ignored.
1558 unsigned Index = Body[Pos+1] - '0';
1559 if (Index >= A.size())
1562 // Otherwise substitute with the token values, with spaces eliminated.
1563 for (MacroArgument::const_iterator it = A[Index].begin(),
1564 ie = A[Index].end(); it != ie; ++it)
1565 OS << it->getString();
1571 unsigned I = Pos + 1;
1572 while (isIdentifierChar(Body[I]) && I + 1 != End)
1575 const char *Begin = Body.data() + Pos +1;
1576 StringRef Argument(Begin, I - (Pos +1));
1578 for (; Index < NParameters; ++Index)
1579 if (Parameters[Index].first == Argument)
1582 if (Index == NParameters) {
1583 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1586 OS << '\\' << Argument;
1590 for (MacroArgument::const_iterator it = A[Index].begin(),
1591 ie = A[Index].end(); it != ie; ++it)
1592 if (it->getKind() == AsmToken::String)
1593 OS << it->getStringContents();
1595 OS << it->getString();
1597 Pos += 1 + Argument.size();
1600 // Update the scan point.
1601 Body = Body.substr(Pos);
1607 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1609 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1613 static bool IsOperator(AsmToken::TokenKind kind)
1619 case AsmToken::Plus:
1620 case AsmToken::Minus:
1621 case AsmToken::Tilde:
1622 case AsmToken::Slash:
1623 case AsmToken::Star:
1625 case AsmToken::Equal:
1626 case AsmToken::EqualEqual:
1627 case AsmToken::Pipe:
1628 case AsmToken::PipePipe:
1629 case AsmToken::Caret:
1631 case AsmToken::AmpAmp:
1632 case AsmToken::Exclaim:
1633 case AsmToken::ExclaimEqual:
1634 case AsmToken::Percent:
1635 case AsmToken::Less:
1636 case AsmToken::LessEqual:
1637 case AsmToken::LessLess:
1638 case AsmToken::LessGreater:
1639 case AsmToken::Greater:
1640 case AsmToken::GreaterEqual:
1641 case AsmToken::GreaterGreater:
1646 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1647 /// This is used for both default macro parameter values and the
1648 /// arguments in macro invocations
1649 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1650 AsmToken::TokenKind &ArgumentDelimiter) {
1651 unsigned ParenLevel = 0;
1652 unsigned AddTokens = 0;
1654 // gas accepts arguments separated by whitespace, except on Darwin
1656 Lexer.setSkipSpace(false);
1659 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1660 Lexer.setSkipSpace(true);
1661 return TokError("unexpected token in macro instantiation");
1664 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1665 // Spaces and commas cannot be mixed to delimit parameters
1666 if (ArgumentDelimiter == AsmToken::Eof)
1667 ArgumentDelimiter = AsmToken::Comma;
1668 else if (ArgumentDelimiter != AsmToken::Comma) {
1669 Lexer.setSkipSpace(true);
1670 return TokError("expected ' ' for macro argument separator");
1675 if (Lexer.is(AsmToken::Space)) {
1676 Lex(); // Eat spaces
1678 // Spaces can delimit parameters, but could also be part an expression.
1679 // If the token after a space is an operator, add the token and the next
1680 // one into this argument
1681 if (ArgumentDelimiter == AsmToken::Space ||
1682 ArgumentDelimiter == AsmToken::Eof) {
1683 if (IsOperator(Lexer.getKind())) {
1684 // Check to see whether the token is used as an operator,
1685 // or part of an identifier
1686 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1687 if (*NextChar == ' ')
1691 if (!AddTokens && ParenLevel == 0) {
1692 if (ArgumentDelimiter == AsmToken::Eof &&
1693 !IsOperator(Lexer.getKind()))
1694 ArgumentDelimiter = AsmToken::Space;
1700 // HandleMacroEntry relies on not advancing the lexer here
1701 // to be able to fill in the remaining default parameter values
1702 if (Lexer.is(AsmToken::EndOfStatement))
1705 // Adjust the current parentheses level.
1706 if (Lexer.is(AsmToken::LParen))
1708 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1711 // Append the token to the current argument list.
1712 MA.push_back(getTok());
1718 Lexer.setSkipSpace(true);
1719 if (ParenLevel != 0)
1720 return TokError("unbalanced parentheses in macro argument");
1724 // Parse the macro instantiation arguments.
1725 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1726 const unsigned NParameters = M ? M->Parameters.size() : 0;
1727 // Argument delimiter is initially unknown. It will be set by
1728 // ParseMacroArgument()
1729 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1731 // Parse two kinds of macro invocations:
1732 // - macros defined without any parameters accept an arbitrary number of them
1733 // - macros defined with parameters accept at most that many of them
1734 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1738 if (ParseMacroArgument(MA, ArgumentDelimiter))
1741 if (!MA.empty() || !NParameters)
1743 else if (NParameters) {
1744 if (!M->Parameters[Parameter].second.empty())
1745 A.push_back(M->Parameters[Parameter].second);
1748 // At the end of the statement, fill in remaining arguments that have
1749 // default values. If there aren't any, then the next argument is
1750 // required but missing
1751 if (Lexer.is(AsmToken::EndOfStatement)) {
1752 if (NParameters && Parameter < NParameters - 1) {
1753 if (M->Parameters[Parameter + 1].second.empty())
1754 return TokError("macro argument '" +
1755 Twine(M->Parameters[Parameter + 1].first) +
1763 if (Lexer.is(AsmToken::Comma))
1766 return TokError("Too many arguments");
1769 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1771 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1772 // this, although we should protect against infinite loops.
1773 if (ActiveMacros.size() == 20)
1774 return TokError("macros cannot be nested more than 20 levels deep");
1777 if (ParseMacroArguments(M, A))
1780 // Remove any trailing empty arguments. Do this after-the-fact as we have
1781 // to keep empty arguments in the middle of the list or positionality
1782 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1783 while (!A.empty() && A.back().empty())
1786 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1787 // to hold the macro body with substitutions.
1788 SmallString<256> Buf;
1789 StringRef Body = M->Body;
1790 raw_svector_ostream OS(Buf);
1792 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1795 // We include the .endmacro in the buffer as our queue to exit the macro
1797 OS << ".endmacro\n";
1799 MemoryBuffer *Instantiation =
1800 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1802 // Create the macro instantiation object and add to the current macro
1803 // instantiation stack.
1804 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1807 ActiveMacros.push_back(MI);
1809 // Jump to the macro instantiation and prime the lexer.
1810 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1811 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1817 void AsmParser::HandleMacroExit() {
1818 // Jump to the EndOfStatement we should return to, and consume it.
1819 JumpToLoc(ActiveMacros.back()->ExitLoc);
1822 // Pop the instantiation entry.
1823 delete ActiveMacros.back();
1824 ActiveMacros.pop_back();
1827 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1828 switch (Value->getKind()) {
1829 case MCExpr::Binary: {
1830 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1831 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1834 case MCExpr::Target:
1835 case MCExpr::Constant:
1837 case MCExpr::SymbolRef: {
1838 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1840 return IsUsedIn(Sym, S.getVariableValue());
1844 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1847 llvm_unreachable("Unknown expr kind!");
1850 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1852 // FIXME: Use better location, we should use proper tokens.
1853 SMLoc EqualLoc = Lexer.getLoc();
1855 const MCExpr *Value;
1856 if (ParseExpression(Value))
1859 // Note: we don't count b as used in "a = b". This is to allow
1863 if (Lexer.isNot(AsmToken::EndOfStatement))
1864 return TokError("unexpected token in assignment");
1866 // Error on assignment to '.'.
1868 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1869 "(use '.space' or '.org').)"));
1872 // Eat the end of statement marker.
1875 // Validate that the LHS is allowed to be a variable (either it has not been
1876 // used as a symbol, or it is an absolute symbol).
1877 MCSymbol *Sym = getContext().LookupSymbol(Name);
1879 // Diagnose assignment to a label.
1881 // FIXME: Diagnostics. Note the location of the definition as a label.
1882 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1883 if (IsUsedIn(Sym, Value))
1884 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1885 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1886 ; // Allow redefinitions of undefined symbols only used in directives.
1887 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1888 ; // Allow redefinitions of variables that haven't yet been used.
1889 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1890 return Error(EqualLoc, "redefinition of '" + Name + "'");
1891 else if (!Sym->isVariable())
1892 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1893 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1894 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1897 // Don't count these checks as uses.
1898 Sym->setUsed(false);
1900 Sym = getContext().GetOrCreateSymbol(Name);
1902 // FIXME: Handle '.'.
1904 // Do the assignment.
1905 Out.EmitAssignment(Sym, Value);
1907 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1913 /// ParseIdentifier:
1916 bool AsmParser::ParseIdentifier(StringRef &Res) {
1917 // The assembler has relaxed rules for accepting identifiers, in particular we
1918 // allow things like '.globl $foo', which would normally be separate
1919 // tokens. At this level, we have already lexed so we cannot (currently)
1920 // handle this as a context dependent token, instead we detect adjacent tokens
1921 // and return the combined identifier.
1922 if (Lexer.is(AsmToken::Dollar)) {
1923 SMLoc DollarLoc = getLexer().getLoc();
1925 // Consume the dollar sign, and check for a following identifier.
1927 if (Lexer.isNot(AsmToken::Identifier))
1930 // We have a '$' followed by an identifier, make sure they are adjacent.
1931 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1934 // Construct the joined identifier and consume the token.
1935 Res = StringRef(DollarLoc.getPointer(),
1936 getTok().getIdentifier().size() + 1);
1941 if (Lexer.isNot(AsmToken::Identifier) &&
1942 Lexer.isNot(AsmToken::String))
1945 Res = getTok().getIdentifier();
1947 Lex(); // Consume the identifier token.
1952 /// ParseDirectiveSet:
1953 /// ::= .equ identifier ',' expression
1954 /// ::= .equiv identifier ',' expression
1955 /// ::= .set identifier ',' expression
1956 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1959 if (ParseIdentifier(Name))
1960 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1962 if (getLexer().isNot(AsmToken::Comma))
1963 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1966 return ParseAssignment(Name, allow_redef, true);
1969 bool AsmParser::ParseEscapedString(std::string &Data) {
1970 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1973 StringRef Str = getTok().getStringContents();
1974 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1975 if (Str[i] != '\\') {
1980 // Recognize escaped characters. Note that this escape semantics currently
1981 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1984 return TokError("unexpected backslash at end of string");
1986 // Recognize octal sequences.
1987 if ((unsigned) (Str[i] - '0') <= 7) {
1988 // Consume up to three octal characters.
1989 unsigned Value = Str[i] - '0';
1991 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1993 Value = Value * 8 + (Str[i] - '0');
1995 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1997 Value = Value * 8 + (Str[i] - '0');
2002 return TokError("invalid octal escape sequence (out of range)");
2004 Data += (unsigned char) Value;
2008 // Otherwise recognize individual escapes.
2011 // Just reject invalid escape sequences for now.
2012 return TokError("invalid escape sequence (unrecognized character)");
2014 case 'b': Data += '\b'; break;
2015 case 'f': Data += '\f'; break;
2016 case 'n': Data += '\n'; break;
2017 case 'r': Data += '\r'; break;
2018 case 't': Data += '\t'; break;
2019 case '"': Data += '"'; break;
2020 case '\\': Data += '\\'; break;
2027 /// ParseDirectiveAscii:
2028 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2029 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2030 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2031 CheckForValidSection();
2034 if (getLexer().isNot(AsmToken::String))
2035 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2038 if (ParseEscapedString(Data))
2041 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2043 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2047 if (getLexer().is(AsmToken::EndOfStatement))
2050 if (getLexer().isNot(AsmToken::Comma))
2051 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2060 /// ParseDirectiveValue
2061 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2062 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2063 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2064 CheckForValidSection();
2067 const MCExpr *Value;
2068 SMLoc ExprLoc = getLexer().getLoc();
2069 if (ParseExpression(Value))
2072 // Special case constant expressions to match code generator.
2073 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2074 assert(Size <= 8 && "Invalid size");
2075 uint64_t IntValue = MCE->getValue();
2076 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2077 return Error(ExprLoc, "literal value out of range for directive");
2078 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2080 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2082 if (getLexer().is(AsmToken::EndOfStatement))
2085 // FIXME: Improve diagnostic.
2086 if (getLexer().isNot(AsmToken::Comma))
2087 return TokError("unexpected token in directive");
2096 /// ParseDirectiveRealValue
2097 /// ::= (.single | .double) [ expression (, expression)* ]
2098 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2099 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2100 CheckForValidSection();
2103 // We don't truly support arithmetic on floating point expressions, so we
2104 // have to manually parse unary prefixes.
2106 if (getLexer().is(AsmToken::Minus)) {
2109 } else if (getLexer().is(AsmToken::Plus))
2112 if (getLexer().isNot(AsmToken::Integer) &&
2113 getLexer().isNot(AsmToken::Real) &&
2114 getLexer().isNot(AsmToken::Identifier))
2115 return TokError("unexpected token in directive");
2117 // Convert to an APFloat.
2118 APFloat Value(Semantics);
2119 StringRef IDVal = getTok().getString();
2120 if (getLexer().is(AsmToken::Identifier)) {
2121 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2122 Value = APFloat::getInf(Semantics);
2123 else if (!IDVal.compare_lower("nan"))
2124 Value = APFloat::getNaN(Semantics, false, ~0);
2126 return TokError("invalid floating point literal");
2127 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2128 APFloat::opInvalidOp)
2129 return TokError("invalid floating point literal");
2133 // Consume the numeric token.
2136 // Emit the value as an integer.
2137 APInt AsInt = Value.bitcastToAPInt();
2138 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2139 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2141 if (getLexer().is(AsmToken::EndOfStatement))
2144 if (getLexer().isNot(AsmToken::Comma))
2145 return TokError("unexpected token in directive");
2154 /// ParseDirectiveSpace
2155 /// ::= .space expression [ , expression ]
2156 bool AsmParser::ParseDirectiveSpace() {
2157 CheckForValidSection();
2160 if (ParseAbsoluteExpression(NumBytes))
2163 int64_t FillExpr = 0;
2164 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2165 if (getLexer().isNot(AsmToken::Comma))
2166 return TokError("unexpected token in '.space' directive");
2169 if (ParseAbsoluteExpression(FillExpr))
2172 if (getLexer().isNot(AsmToken::EndOfStatement))
2173 return TokError("unexpected token in '.space' directive");
2179 return TokError("invalid number of bytes in '.space' directive");
2181 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2182 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2187 /// ParseDirectiveZero
2188 /// ::= .zero expression
2189 bool AsmParser::ParseDirectiveZero() {
2190 CheckForValidSection();
2193 if (ParseAbsoluteExpression(NumBytes))
2197 if (getLexer().is(AsmToken::Comma)) {
2199 if (ParseAbsoluteExpression(Val))
2203 if (getLexer().isNot(AsmToken::EndOfStatement))
2204 return TokError("unexpected token in '.zero' directive");
2208 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2213 /// ParseDirectiveFill
2214 /// ::= .fill expression , expression , expression
2215 bool AsmParser::ParseDirectiveFill() {
2216 CheckForValidSection();
2219 if (ParseAbsoluteExpression(NumValues))
2222 if (getLexer().isNot(AsmToken::Comma))
2223 return TokError("unexpected token in '.fill' directive");
2227 if (ParseAbsoluteExpression(FillSize))
2230 if (getLexer().isNot(AsmToken::Comma))
2231 return TokError("unexpected token in '.fill' directive");
2235 if (ParseAbsoluteExpression(FillExpr))
2238 if (getLexer().isNot(AsmToken::EndOfStatement))
2239 return TokError("unexpected token in '.fill' directive");
2243 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2244 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2246 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2247 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2252 /// ParseDirectiveOrg
2253 /// ::= .org expression [ , expression ]
2254 bool AsmParser::ParseDirectiveOrg() {
2255 CheckForValidSection();
2257 const MCExpr *Offset;
2258 SMLoc Loc = getTok().getLoc();
2259 if (ParseExpression(Offset))
2262 // Parse optional fill expression.
2263 int64_t FillExpr = 0;
2264 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2265 if (getLexer().isNot(AsmToken::Comma))
2266 return TokError("unexpected token in '.org' directive");
2269 if (ParseAbsoluteExpression(FillExpr))
2272 if (getLexer().isNot(AsmToken::EndOfStatement))
2273 return TokError("unexpected token in '.org' directive");
2278 // Only limited forms of relocatable expressions are accepted here, it
2279 // has to be relative to the current section. The streamer will return
2280 // 'true' if the expression wasn't evaluatable.
2281 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2282 return Error(Loc, "expected assembly-time absolute expression");
2287 /// ParseDirectiveAlign
2288 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2289 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2290 CheckForValidSection();
2292 SMLoc AlignmentLoc = getLexer().getLoc();
2294 if (ParseAbsoluteExpression(Alignment))
2298 bool HasFillExpr = false;
2299 int64_t FillExpr = 0;
2300 int64_t MaxBytesToFill = 0;
2301 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2302 if (getLexer().isNot(AsmToken::Comma))
2303 return TokError("unexpected token in directive");
2306 // The fill expression can be omitted while specifying a maximum number of
2307 // alignment bytes, e.g:
2309 if (getLexer().isNot(AsmToken::Comma)) {
2311 if (ParseAbsoluteExpression(FillExpr))
2315 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2316 if (getLexer().isNot(AsmToken::Comma))
2317 return TokError("unexpected token in directive");
2320 MaxBytesLoc = getLexer().getLoc();
2321 if (ParseAbsoluteExpression(MaxBytesToFill))
2324 if (getLexer().isNot(AsmToken::EndOfStatement))
2325 return TokError("unexpected token in directive");
2334 // Compute alignment in bytes.
2336 // FIXME: Diagnose overflow.
2337 if (Alignment >= 32) {
2338 Error(AlignmentLoc, "invalid alignment value");
2342 Alignment = 1ULL << Alignment;
2345 // Diagnose non-sensical max bytes to align.
2346 if (MaxBytesLoc.isValid()) {
2347 if (MaxBytesToFill < 1) {
2348 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2349 "many bytes, ignoring maximum bytes expression");
2353 if (MaxBytesToFill >= Alignment) {
2354 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2360 // Check whether we should use optimal code alignment for this .align
2362 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2363 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2364 ValueSize == 1 && UseCodeAlign) {
2365 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2367 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2368 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2375 /// ParseDirectiveSymbolAttribute
2376 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2377 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2378 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2381 SMLoc Loc = getTok().getLoc();
2383 if (ParseIdentifier(Name))
2384 return Error(Loc, "expected identifier in directive");
2386 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2388 // Assembler local symbols don't make any sense here. Complain loudly.
2389 if (Sym->isTemporary())
2390 return Error(Loc, "non-local symbol required in directive");
2392 getStreamer().EmitSymbolAttribute(Sym, Attr);
2394 if (getLexer().is(AsmToken::EndOfStatement))
2397 if (getLexer().isNot(AsmToken::Comma))
2398 return TokError("unexpected token in directive");
2407 /// ParseDirectiveComm
2408 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2409 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2410 CheckForValidSection();
2412 SMLoc IDLoc = getLexer().getLoc();
2414 if (ParseIdentifier(Name))
2415 return TokError("expected identifier in directive");
2417 // Handle the identifier as the key symbol.
2418 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2420 if (getLexer().isNot(AsmToken::Comma))
2421 return TokError("unexpected token in directive");
2425 SMLoc SizeLoc = getLexer().getLoc();
2426 if (ParseAbsoluteExpression(Size))
2429 int64_t Pow2Alignment = 0;
2430 SMLoc Pow2AlignmentLoc;
2431 if (getLexer().is(AsmToken::Comma)) {
2433 Pow2AlignmentLoc = getLexer().getLoc();
2434 if (ParseAbsoluteExpression(Pow2Alignment))
2437 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2438 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2439 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2441 // If this target takes alignments in bytes (not log) validate and convert.
2442 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2443 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2444 if (!isPowerOf2_64(Pow2Alignment))
2445 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2446 Pow2Alignment = Log2_64(Pow2Alignment);
2450 if (getLexer().isNot(AsmToken::EndOfStatement))
2451 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2455 // NOTE: a size of zero for a .comm should create a undefined symbol
2456 // but a size of .lcomm creates a bss symbol of size zero.
2458 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2459 "be less than zero");
2461 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2462 // may internally end up wanting an alignment in bytes.
2463 // FIXME: Diagnose overflow.
2464 if (Pow2Alignment < 0)
2465 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2466 "alignment, can't be less than zero");
2468 if (!Sym->isUndefined())
2469 return Error(IDLoc, "invalid symbol redefinition");
2471 // Create the Symbol as a common or local common with Size and Pow2Alignment
2473 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2477 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2481 /// ParseDirectiveAbort
2482 /// ::= .abort [... message ...]
2483 bool AsmParser::ParseDirectiveAbort() {
2484 // FIXME: Use loc from directive.
2485 SMLoc Loc = getLexer().getLoc();
2487 StringRef Str = ParseStringToEndOfStatement();
2488 if (getLexer().isNot(AsmToken::EndOfStatement))
2489 return TokError("unexpected token in '.abort' directive");
2494 Error(Loc, ".abort detected. Assembly stopping.");
2496 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2497 // FIXME: Actually abort assembly here.
2502 /// ParseDirectiveInclude
2503 /// ::= .include "filename"
2504 bool AsmParser::ParseDirectiveInclude() {
2505 if (getLexer().isNot(AsmToken::String))
2506 return TokError("expected string in '.include' directive");
2508 std::string Filename = getTok().getString();
2509 SMLoc IncludeLoc = getLexer().getLoc();
2512 if (getLexer().isNot(AsmToken::EndOfStatement))
2513 return TokError("unexpected token in '.include' directive");
2515 // Strip the quotes.
2516 Filename = Filename.substr(1, Filename.size()-2);
2518 // Attempt to switch the lexer to the included file before consuming the end
2519 // of statement to avoid losing it when we switch.
2520 if (EnterIncludeFile(Filename)) {
2521 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2528 /// ParseDirectiveIncbin
2529 /// ::= .incbin "filename"
2530 bool AsmParser::ParseDirectiveIncbin() {
2531 if (getLexer().isNot(AsmToken::String))
2532 return TokError("expected string in '.incbin' directive");
2534 std::string Filename = getTok().getString();
2535 SMLoc IncbinLoc = getLexer().getLoc();
2538 if (getLexer().isNot(AsmToken::EndOfStatement))
2539 return TokError("unexpected token in '.incbin' directive");
2541 // Strip the quotes.
2542 Filename = Filename.substr(1, Filename.size()-2);
2544 // Attempt to process the included file.
2545 if (ProcessIncbinFile(Filename)) {
2546 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2553 /// ParseDirectiveIf
2554 /// ::= .if expression
2555 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2556 TheCondStack.push_back(TheCondState);
2557 TheCondState.TheCond = AsmCond::IfCond;
2558 if (TheCondState.Ignore) {
2559 EatToEndOfStatement();
2562 if (ParseAbsoluteExpression(ExprValue))
2565 if (getLexer().isNot(AsmToken::EndOfStatement))
2566 return TokError("unexpected token in '.if' directive");
2570 TheCondState.CondMet = ExprValue;
2571 TheCondState.Ignore = !TheCondState.CondMet;
2577 /// ParseDirectiveIfb
2579 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2580 TheCondStack.push_back(TheCondState);
2581 TheCondState.TheCond = AsmCond::IfCond;
2583 if (TheCondState.Ignore) {
2584 EatToEndOfStatement();
2586 StringRef Str = ParseStringToEndOfStatement();
2588 if (getLexer().isNot(AsmToken::EndOfStatement))
2589 return TokError("unexpected token in '.ifb' directive");
2593 TheCondState.CondMet = ExpectBlank == Str.empty();
2594 TheCondState.Ignore = !TheCondState.CondMet;
2600 /// ParseDirectiveIfc
2601 /// ::= .ifc string1, string2
2602 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2603 TheCondStack.push_back(TheCondState);
2604 TheCondState.TheCond = AsmCond::IfCond;
2606 if (TheCondState.Ignore) {
2607 EatToEndOfStatement();
2609 StringRef Str1 = ParseStringToComma();
2611 if (getLexer().isNot(AsmToken::Comma))
2612 return TokError("unexpected token in '.ifc' directive");
2616 StringRef Str2 = ParseStringToEndOfStatement();
2618 if (getLexer().isNot(AsmToken::EndOfStatement))
2619 return TokError("unexpected token in '.ifc' directive");
2623 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2624 TheCondState.Ignore = !TheCondState.CondMet;
2630 /// ParseDirectiveIfdef
2631 /// ::= .ifdef symbol
2632 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2634 TheCondStack.push_back(TheCondState);
2635 TheCondState.TheCond = AsmCond::IfCond;
2637 if (TheCondState.Ignore) {
2638 EatToEndOfStatement();
2640 if (ParseIdentifier(Name))
2641 return TokError("expected identifier after '.ifdef'");
2645 MCSymbol *Sym = getContext().LookupSymbol(Name);
2648 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2650 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2651 TheCondState.Ignore = !TheCondState.CondMet;
2657 /// ParseDirectiveElseIf
2658 /// ::= .elseif expression
2659 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2660 if (TheCondState.TheCond != AsmCond::IfCond &&
2661 TheCondState.TheCond != AsmCond::ElseIfCond)
2662 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2664 TheCondState.TheCond = AsmCond::ElseIfCond;
2666 bool LastIgnoreState = false;
2667 if (!TheCondStack.empty())
2668 LastIgnoreState = TheCondStack.back().Ignore;
2669 if (LastIgnoreState || TheCondState.CondMet) {
2670 TheCondState.Ignore = true;
2671 EatToEndOfStatement();
2675 if (ParseAbsoluteExpression(ExprValue))
2678 if (getLexer().isNot(AsmToken::EndOfStatement))
2679 return TokError("unexpected token in '.elseif' directive");
2682 TheCondState.CondMet = ExprValue;
2683 TheCondState.Ignore = !TheCondState.CondMet;
2689 /// ParseDirectiveElse
2691 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2692 if (getLexer().isNot(AsmToken::EndOfStatement))
2693 return TokError("unexpected token in '.else' directive");
2697 if (TheCondState.TheCond != AsmCond::IfCond &&
2698 TheCondState.TheCond != AsmCond::ElseIfCond)
2699 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2701 TheCondState.TheCond = AsmCond::ElseCond;
2702 bool LastIgnoreState = false;
2703 if (!TheCondStack.empty())
2704 LastIgnoreState = TheCondStack.back().Ignore;
2705 if (LastIgnoreState || TheCondState.CondMet)
2706 TheCondState.Ignore = true;
2708 TheCondState.Ignore = false;
2713 /// ParseDirectiveEndIf
2715 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2716 if (getLexer().isNot(AsmToken::EndOfStatement))
2717 return TokError("unexpected token in '.endif' directive");
2721 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2722 TheCondStack.empty())
2723 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2725 if (!TheCondStack.empty()) {
2726 TheCondState = TheCondStack.back();
2727 TheCondStack.pop_back();
2733 /// ParseDirectiveFile
2734 /// ::= .file [number] filename
2735 /// ::= .file number directory filename
2736 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2737 // FIXME: I'm not sure what this is.
2738 int64_t FileNumber = -1;
2739 SMLoc FileNumberLoc = getLexer().getLoc();
2740 if (getLexer().is(AsmToken::Integer)) {
2741 FileNumber = getTok().getIntVal();
2745 return TokError("file number less than one");
2748 if (getLexer().isNot(AsmToken::String))
2749 return TokError("unexpected token in '.file' directive");
2751 // Usually the directory and filename together, otherwise just the directory.
2752 StringRef Path = getTok().getString();
2753 Path = Path.substr(1, Path.size()-2);
2756 StringRef Directory;
2758 if (getLexer().is(AsmToken::String)) {
2759 if (FileNumber == -1)
2760 return TokError("explicit path specified, but no file number");
2761 Filename = getTok().getString();
2762 Filename = Filename.substr(1, Filename.size()-2);
2769 if (getLexer().isNot(AsmToken::EndOfStatement))
2770 return TokError("unexpected token in '.file' directive");
2772 if (FileNumber == -1)
2773 getStreamer().EmitFileDirective(Filename);
2775 if (getContext().getGenDwarfForAssembly() == true)
2776 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2777 "used to generate dwarf debug info for assembly code");
2779 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2780 Error(FileNumberLoc, "file number already allocated");
2786 /// ParseDirectiveLine
2787 /// ::= .line [number]
2788 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2789 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2790 if (getLexer().isNot(AsmToken::Integer))
2791 return TokError("unexpected token in '.line' directive");
2793 int64_t LineNumber = getTok().getIntVal();
2797 // FIXME: Do something with the .line.
2800 if (getLexer().isNot(AsmToken::EndOfStatement))
2801 return TokError("unexpected token in '.line' directive");
2807 /// ParseDirectiveLoc
2808 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2809 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2810 /// The first number is a file number, must have been previously assigned with
2811 /// a .file directive, the second number is the line number and optionally the
2812 /// third number is a column position (zero if not specified). The remaining
2813 /// optional items are .loc sub-directives.
2814 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2816 if (getLexer().isNot(AsmToken::Integer))
2817 return TokError("unexpected token in '.loc' directive");
2818 int64_t FileNumber = getTok().getIntVal();
2820 return TokError("file number less than one in '.loc' directive");
2821 if (!getContext().isValidDwarfFileNumber(FileNumber))
2822 return TokError("unassigned file number in '.loc' directive");
2825 int64_t LineNumber = 0;
2826 if (getLexer().is(AsmToken::Integer)) {
2827 LineNumber = getTok().getIntVal();
2829 return TokError("line number less than one in '.loc' directive");
2833 int64_t ColumnPos = 0;
2834 if (getLexer().is(AsmToken::Integer)) {
2835 ColumnPos = getTok().getIntVal();
2837 return TokError("column position less than zero in '.loc' directive");
2841 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2843 int64_t Discriminator = 0;
2844 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2846 if (getLexer().is(AsmToken::EndOfStatement))
2850 SMLoc Loc = getTok().getLoc();
2851 if (getParser().ParseIdentifier(Name))
2852 return TokError("unexpected token in '.loc' directive");
2854 if (Name == "basic_block")
2855 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2856 else if (Name == "prologue_end")
2857 Flags |= DWARF2_FLAG_PROLOGUE_END;
2858 else if (Name == "epilogue_begin")
2859 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2860 else if (Name == "is_stmt") {
2861 SMLoc Loc = getTok().getLoc();
2862 const MCExpr *Value;
2863 if (getParser().ParseExpression(Value))
2865 // The expression must be the constant 0 or 1.
2866 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2867 int Value = MCE->getValue();
2869 Flags &= ~DWARF2_FLAG_IS_STMT;
2870 else if (Value == 1)
2871 Flags |= DWARF2_FLAG_IS_STMT;
2873 return Error(Loc, "is_stmt value not 0 or 1");
2876 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2879 else if (Name == "isa") {
2880 SMLoc Loc = getTok().getLoc();
2881 const MCExpr *Value;
2882 if (getParser().ParseExpression(Value))
2884 // The expression must be a constant greater or equal to 0.
2885 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2886 int Value = MCE->getValue();
2888 return Error(Loc, "isa number less than zero");
2892 return Error(Loc, "isa number not a constant value");
2895 else if (Name == "discriminator") {
2896 if (getParser().ParseAbsoluteExpression(Discriminator))
2900 return Error(Loc, "unknown sub-directive in '.loc' directive");
2903 if (getLexer().is(AsmToken::EndOfStatement))
2908 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2909 Isa, Discriminator, StringRef());
2914 /// ParseDirectiveStabs
2915 /// ::= .stabs string, number, number, number
2916 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2917 SMLoc DirectiveLoc) {
2918 return TokError("unsupported directive '" + Directive + "'");
2921 /// ParseDirectiveCFISections
2922 /// ::= .cfi_sections section [, section]
2923 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2924 SMLoc DirectiveLoc) {
2929 if (getParser().ParseIdentifier(Name))
2930 return TokError("Expected an identifier");
2932 if (Name == ".eh_frame")
2934 else if (Name == ".debug_frame")
2937 if (getLexer().is(AsmToken::Comma)) {
2940 if (getParser().ParseIdentifier(Name))
2941 return TokError("Expected an identifier");
2943 if (Name == ".eh_frame")
2945 else if (Name == ".debug_frame")
2949 getStreamer().EmitCFISections(EH, Debug);
2954 /// ParseDirectiveCFIStartProc
2955 /// ::= .cfi_startproc
2956 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2957 SMLoc DirectiveLoc) {
2958 getStreamer().EmitCFIStartProc();
2962 /// ParseDirectiveCFIEndProc
2963 /// ::= .cfi_endproc
2964 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2965 getStreamer().EmitCFIEndProc();
2969 /// ParseRegisterOrRegisterNumber - parse register name or number.
2970 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2971 SMLoc DirectiveLoc) {
2974 if (getLexer().isNot(AsmToken::Integer)) {
2975 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2978 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2980 return getParser().ParseAbsoluteExpression(Register);
2985 /// ParseDirectiveCFIDefCfa
2986 /// ::= .cfi_def_cfa register, offset
2987 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2988 SMLoc DirectiveLoc) {
2989 int64_t Register = 0;
2990 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2993 if (getLexer().isNot(AsmToken::Comma))
2994 return TokError("unexpected token in directive");
2998 if (getParser().ParseAbsoluteExpression(Offset))
3001 getStreamer().EmitCFIDefCfa(Register, Offset);
3005 /// ParseDirectiveCFIDefCfaOffset
3006 /// ::= .cfi_def_cfa_offset offset
3007 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3008 SMLoc DirectiveLoc) {
3010 if (getParser().ParseAbsoluteExpression(Offset))
3013 getStreamer().EmitCFIDefCfaOffset(Offset);
3017 /// ParseDirectiveCFIAdjustCfaOffset
3018 /// ::= .cfi_adjust_cfa_offset adjustment
3019 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3020 SMLoc DirectiveLoc) {
3021 int64_t Adjustment = 0;
3022 if (getParser().ParseAbsoluteExpression(Adjustment))
3025 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3029 /// ParseDirectiveCFIDefCfaRegister
3030 /// ::= .cfi_def_cfa_register register
3031 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3032 SMLoc DirectiveLoc) {
3033 int64_t Register = 0;
3034 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3037 getStreamer().EmitCFIDefCfaRegister(Register);
3041 /// ParseDirectiveCFIOffset
3042 /// ::= .cfi_offset register, offset
3043 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3044 int64_t Register = 0;
3047 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3050 if (getLexer().isNot(AsmToken::Comma))
3051 return TokError("unexpected token in directive");
3054 if (getParser().ParseAbsoluteExpression(Offset))
3057 getStreamer().EmitCFIOffset(Register, Offset);
3061 /// ParseDirectiveCFIRelOffset
3062 /// ::= .cfi_rel_offset register, offset
3063 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3064 SMLoc DirectiveLoc) {
3065 int64_t Register = 0;
3067 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3070 if (getLexer().isNot(AsmToken::Comma))
3071 return TokError("unexpected token in directive");
3075 if (getParser().ParseAbsoluteExpression(Offset))
3078 getStreamer().EmitCFIRelOffset(Register, Offset);
3082 static bool isValidEncoding(int64_t Encoding) {
3083 if (Encoding & ~0xff)
3086 if (Encoding == dwarf::DW_EH_PE_omit)
3089 const unsigned Format = Encoding & 0xf;
3090 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3091 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3092 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3093 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3096 const unsigned Application = Encoding & 0x70;
3097 if (Application != dwarf::DW_EH_PE_absptr &&
3098 Application != dwarf::DW_EH_PE_pcrel)
3104 /// ParseDirectiveCFIPersonalityOrLsda
3105 /// ::= .cfi_personality encoding, [symbol_name]
3106 /// ::= .cfi_lsda encoding, [symbol_name]
3107 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3108 SMLoc DirectiveLoc) {
3109 int64_t Encoding = 0;
3110 if (getParser().ParseAbsoluteExpression(Encoding))
3112 if (Encoding == dwarf::DW_EH_PE_omit)
3115 if (!isValidEncoding(Encoding))
3116 return TokError("unsupported encoding.");
3118 if (getLexer().isNot(AsmToken::Comma))
3119 return TokError("unexpected token in directive");
3123 if (getParser().ParseIdentifier(Name))
3124 return TokError("expected identifier in directive");
3126 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3128 if (IDVal == ".cfi_personality")
3129 getStreamer().EmitCFIPersonality(Sym, Encoding);
3131 assert(IDVal == ".cfi_lsda");
3132 getStreamer().EmitCFILsda(Sym, Encoding);
3137 /// ParseDirectiveCFIRememberState
3138 /// ::= .cfi_remember_state
3139 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3140 SMLoc DirectiveLoc) {
3141 getStreamer().EmitCFIRememberState();
3145 /// ParseDirectiveCFIRestoreState
3146 /// ::= .cfi_remember_state
3147 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3148 SMLoc DirectiveLoc) {
3149 getStreamer().EmitCFIRestoreState();
3153 /// ParseDirectiveCFISameValue
3154 /// ::= .cfi_same_value register
3155 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3156 SMLoc DirectiveLoc) {
3157 int64_t Register = 0;
3159 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3162 getStreamer().EmitCFISameValue(Register);
3167 /// ParseDirectiveCFIRestore
3168 /// ::= .cfi_restore register
3169 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3170 SMLoc DirectiveLoc) {
3171 int64_t Register = 0;
3172 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3175 getStreamer().EmitCFIRestore(Register);
3180 /// ParseDirectiveCFIEscape
3181 /// ::= .cfi_escape expression[,...]
3182 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3183 SMLoc DirectiveLoc) {
3186 if (getParser().ParseAbsoluteExpression(CurrValue))
3189 Values.push_back((uint8_t)CurrValue);
3191 while (getLexer().is(AsmToken::Comma)) {
3194 if (getParser().ParseAbsoluteExpression(CurrValue))
3197 Values.push_back((uint8_t)CurrValue);
3200 getStreamer().EmitCFIEscape(Values);
3204 /// ParseDirectiveCFISignalFrame
3205 /// ::= .cfi_signal_frame
3206 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3207 SMLoc DirectiveLoc) {
3208 if (getLexer().isNot(AsmToken::EndOfStatement))
3209 return Error(getLexer().getLoc(),
3210 "unexpected token in '" + Directive + "' directive");
3212 getStreamer().EmitCFISignalFrame();
3217 /// ParseDirectiveMacrosOnOff
3220 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3221 SMLoc DirectiveLoc) {
3222 if (getLexer().isNot(AsmToken::EndOfStatement))
3223 return Error(getLexer().getLoc(),
3224 "unexpected token in '" + Directive + "' directive");
3226 getParser().MacrosEnabled = Directive == ".macros_on";
3231 /// ParseDirectiveMacro
3232 /// ::= .macro name [parameters]
3233 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3234 SMLoc DirectiveLoc) {
3236 if (getParser().ParseIdentifier(Name))
3237 return TokError("expected identifier in '.macro' directive");
3239 MacroParameters Parameters;
3240 // Argument delimiter is initially unknown. It will be set by
3241 // ParseMacroArgument()
3242 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3243 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3245 MacroParameter Parameter;
3246 if (getParser().ParseIdentifier(Parameter.first))
3247 return TokError("expected identifier in '.macro' directive");
3249 if (getLexer().is(AsmToken::Equal)) {
3251 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3255 Parameters.push_back(Parameter);
3257 if (getLexer().is(AsmToken::Comma))
3259 else if (getLexer().is(AsmToken::EndOfStatement))
3264 // Eat the end of statement.
3267 AsmToken EndToken, StartToken = getTok();
3269 // Lex the macro definition.
3271 // Check whether we have reached the end of the file.
3272 if (getLexer().is(AsmToken::Eof))
3273 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3275 // Otherwise, check whether we have reach the .endmacro.
3276 if (getLexer().is(AsmToken::Identifier) &&
3277 (getTok().getIdentifier() == ".endm" ||
3278 getTok().getIdentifier() == ".endmacro")) {
3279 EndToken = getTok();
3281 if (getLexer().isNot(AsmToken::EndOfStatement))
3282 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3287 // Otherwise, scan til the end of the statement.
3288 getParser().EatToEndOfStatement();
3291 if (getParser().MacroMap.lookup(Name)) {
3292 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3295 const char *BodyStart = StartToken.getLoc().getPointer();
3296 const char *BodyEnd = EndToken.getLoc().getPointer();
3297 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3298 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3302 /// ParseDirectiveEndMacro
3305 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3306 SMLoc DirectiveLoc) {
3307 if (getLexer().isNot(AsmToken::EndOfStatement))
3308 return TokError("unexpected token in '" + Directive + "' directive");
3310 // If we are inside a macro instantiation, terminate the current
3312 if (!getParser().ActiveMacros.empty()) {
3313 getParser().HandleMacroExit();
3317 // Otherwise, this .endmacro is a stray entry in the file; well formed
3318 // .endmacro directives are handled during the macro definition parsing.
3319 return TokError("unexpected '" + Directive + "' in file, "
3320 "no current macro definition");
3323 /// ParseDirectivePurgeMacro
3325 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3326 SMLoc DirectiveLoc) {
3328 if (getParser().ParseIdentifier(Name))
3329 return TokError("expected identifier in '.purgem' directive");
3331 if (getLexer().isNot(AsmToken::EndOfStatement))
3332 return TokError("unexpected token in '.purgem' directive");
3334 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3335 if (I == getParser().MacroMap.end())
3336 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3338 // Undefine the macro.
3339 delete I->getValue();
3340 getParser().MacroMap.erase(I);
3344 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3345 getParser().CheckForValidSection();
3347 const MCExpr *Value;
3349 if (getParser().ParseExpression(Value))
3352 if (getLexer().isNot(AsmToken::EndOfStatement))
3353 return TokError("unexpected token in directive");
3355 if (DirName[1] == 's')
3356 getStreamer().EmitSLEB128Value(Value);
3358 getStreamer().EmitULEB128Value(Value);
3363 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3364 AsmToken EndToken, StartToken = getTok();
3366 unsigned NestLevel = 0;
3368 // Check whether we have reached the end of the file.
3369 if (getLexer().is(AsmToken::Eof)) {
3370 Error(DirectiveLoc, "no matching '.endr' in definition");
3374 if (Lexer.is(AsmToken::Identifier) &&
3375 (getTok().getIdentifier() == ".rept")) {
3379 // Otherwise, check whether we have reached the .endr.
3380 if (Lexer.is(AsmToken::Identifier) &&
3381 getTok().getIdentifier() == ".endr") {
3382 if (NestLevel == 0) {
3383 EndToken = getTok();
3385 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3386 TokError("unexpected token in '.endr' directive");
3394 // Otherwise, scan till the end of the statement.
3395 EatToEndOfStatement();
3398 const char *BodyStart = StartToken.getLoc().getPointer();
3399 const char *BodyEnd = EndToken.getLoc().getPointer();
3400 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3402 // We Are Anonymous.
3404 MacroParameters Parameters;
3405 return new Macro(Name, Body, Parameters);
3408 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3409 raw_svector_ostream &OS) {
3412 MemoryBuffer *Instantiation =
3413 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3415 // Create the macro instantiation object and add to the current macro
3416 // instantiation stack.
3417 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3420 ActiveMacros.push_back(MI);
3422 // Jump to the macro instantiation and prime the lexer.
3423 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3424 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3428 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3430 if (ParseAbsoluteExpression(Count))
3431 return TokError("unexpected token in '.rept' directive");
3434 return TokError("Count is negative");
3436 if (Lexer.isNot(AsmToken::EndOfStatement))
3437 return TokError("unexpected token in '.rept' directive");
3439 // Eat the end of statement.
3442 // Lex the rept definition.
3443 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3447 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3448 // to hold the macro body with substitutions.
3449 SmallString<256> Buf;
3450 MacroParameters Parameters;
3452 raw_svector_ostream OS(Buf);
3454 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3457 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3462 /// ParseDirectiveIrp
3463 /// ::= .irp symbol,values
3464 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3465 MacroParameters Parameters;
3466 MacroParameter Parameter;
3468 if (ParseIdentifier(Parameter.first))
3469 return TokError("expected identifier in '.irp' directive");
3471 Parameters.push_back(Parameter);
3473 if (Lexer.isNot(AsmToken::Comma))
3474 return TokError("expected comma in '.irp' directive");
3479 if (ParseMacroArguments(0, A))
3482 // Eat the end of statement.
3485 // Lex the irp definition.
3486 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3490 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3491 // to hold the macro body with substitutions.
3492 SmallString<256> Buf;
3493 raw_svector_ostream OS(Buf);
3495 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3496 MacroArguments Args;
3499 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3503 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3508 /// ParseDirectiveIrpc
3509 /// ::= .irpc symbol,values
3510 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3511 MacroParameters Parameters;
3512 MacroParameter Parameter;
3514 if (ParseIdentifier(Parameter.first))
3515 return TokError("expected identifier in '.irpc' directive");
3517 Parameters.push_back(Parameter);
3519 if (Lexer.isNot(AsmToken::Comma))
3520 return TokError("expected comma in '.irpc' directive");
3525 if (ParseMacroArguments(0, A))
3528 if (A.size() != 1 || A.front().size() != 1)
3529 return TokError("unexpected token in '.irpc' directive");
3531 // Eat the end of statement.
3534 // Lex the irpc definition.
3535 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3539 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3540 // to hold the macro body with substitutions.
3541 SmallString<256> Buf;
3542 raw_svector_ostream OS(Buf);
3544 StringRef Values = A.front().front().getString();
3545 std::size_t I, End = Values.size();
3546 for (I = 0; I < End; ++I) {
3548 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3550 MacroArguments Args;
3551 Args.push_back(Arg);
3553 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3557 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3562 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3563 if (ActiveMacros.empty())
3564 return TokError("unmatched '.endr' directive");
3566 // The only .repl that should get here are the ones created by
3567 // InstantiateMacroLikeBody.
3568 assert(getLexer().is(AsmToken::EndOfStatement));
3575 enum AsmOpRewriteKind {
3581 struct AsmOpRewrite {
3582 AsmOpRewriteKind Kind;
3587 AsmOpRewrite(AsmOpRewriteKind kind, SMLoc loc, unsigned len)
3588 : Kind(kind), Loc(loc), Len(len) { }
3592 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3593 unsigned &NumOutputs, unsigned &NumInputs,
3594 SmallVectorImpl<void *> &OpDecls,
3595 SmallVectorImpl<std::string> &Constraints,
3596 SmallVectorImpl<std::string> &Clobbers,
3597 const MCInstrInfo *MII,
3598 const MCInstPrinter *IP,
3599 MCAsmParserSemaCallback &SI) {
3600 SmallVector<void*, 4> InputDecls;
3601 SmallVector<void*, 4> OutputDecls;
3602 SmallVector<std::string, 4> InputConstraints;
3603 SmallVector<std::string, 4> OutputConstraints;
3604 std::set<std::string> ClobberRegs;
3606 SmallVector<struct AsmOpRewrite, 4> AsmStrRewrites;
3611 // While we have input, parse each statement.
3612 unsigned InputIdx = 0;
3613 unsigned OutputIdx = 0;
3614 while (getLexer().isNot(AsmToken::Eof)) {
3615 if (ParseStatement()) return true;
3617 if (isInstruction()) {
3618 const MCInstrDesc &Desc = MII->get(getOpcode());
3620 // Build the list of clobbers, outputs and inputs.
3621 for (unsigned i = 1, e = ParsedOperands.size(); i != e; ++i) {
3622 MCParsedAsmOperand *Operand = ParsedOperands[i];
3625 if (Operand->isImm()) {
3626 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Imm,
3627 Operand->getStartLoc(),
3628 Operand->getNameLen()));
3632 // Register operand.
3633 if (Operand->isReg()) {
3634 unsigned NumDefs = Desc.getNumDefs();
3636 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3638 raw_string_ostream OS(Reg);
3639 IP->printRegName(OS, Operand->getReg());
3640 ClobberRegs.insert(StringRef(OS.str()));
3645 // Expr/Input or Output.
3647 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3650 bool isOutput = (i == 1) && Desc.mayStore();
3652 std::string Constraint = "=";
3654 OutputDecls.push_back(OpDecl);
3655 Constraint += Operand->getConstraint().str();
3656 OutputConstraints.push_back(Constraint);
3657 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Output,
3658 Operand->getStartLoc(),
3659 Operand->getNameLen()));
3661 InputDecls.push_back(OpDecl);
3662 InputConstraints.push_back(Operand->getConstraint().str());
3663 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Input,
3664 Operand->getStartLoc(),
3665 Operand->getNameLen()));
3669 // Free any parsed operands.
3670 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
3671 delete ParsedOperands[i];
3672 ParsedOperands.clear();
3676 // Set the number of Outputs and Inputs.
3677 NumOutputs = OutputDecls.size();
3678 NumInputs = InputDecls.size();
3680 // Set the unique clobbers.
3681 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3682 E = ClobberRegs.end(); I != E; ++I)
3683 Clobbers.push_back(*I);
3685 // Merge the various outputs and inputs. Output are expected first.
3686 if (NumOutputs || NumInputs) {
3687 unsigned NumExprs = NumOutputs + NumInputs;
3688 OpDecls.resize(NumExprs);
3689 Constraints.resize(NumExprs);
3690 for (unsigned i = 0; i < NumOutputs; ++i) {
3691 OpDecls[i] = OutputDecls[i];
3692 Constraints[i] = OutputConstraints[i];
3694 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3695 OpDecls[j] = InputDecls[i];
3696 Constraints[j] = InputConstraints[i];
3700 // Build the IR assembly string.
3701 std::string AsmStringIR;
3702 raw_string_ostream OS(AsmStringIR);
3703 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3704 for (SmallVectorImpl<struct AsmOpRewrite>::iterator
3705 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3706 const char *Loc = (*I).Loc.getPointer();
3708 // Emit everything up to the immediate/expression.
3709 OS << StringRef(Start, Loc - Start);
3711 // Rewrite expressions in $N notation.
3712 switch ((*I).Kind) {
3714 OS << Twine("$$") + StringRef(Loc, (*I).Len);
3726 // Skip the original expression.
3727 Start = Loc + (*I).Len;
3730 // Emit the remainder of the asm string.
3731 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3732 if (Start != AsmEnd)
3733 OS << StringRef(Start, AsmEnd - Start);
3735 AsmString = OS.str();
3739 /// \brief Create an MCAsmParser instance.
3740 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3741 MCContext &C, MCStreamer &Out,
3742 const MCAsmInfo &MAI) {
3743 return new AsmParser(SM, C, Out, MAI);