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/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCParser/AsmCond.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCTargetAsmParser.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/raw_ostream.h"
42 FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
47 /// \brief Helper class for tracking macro definitions.
51 std::vector<StringRef> Parameters;
54 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
58 /// \brief Helper class for storing information about an active macro
60 struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
70 /// The location where parsing should resume upon instantiation completion.
74 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
78 /// \brief The concrete assembly parser instance.
79 class AsmParser : public MCAsmParser {
80 friend class GenericAsmParser;
82 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
90 SourceMgr::DiagHandlerTy SavedDiagHandler;
91 void *SavedDiagContext;
92 MCAsmParserExtension *GenericParser;
93 MCAsmParserExtension *PlatformParser;
95 /// This is the current buffer index we're lexing from as managed by the
100 std::vector<AsmCond> TheCondStack;
102 /// DirectiveMap - This is a table handlers for directives. Each handler is
103 /// invoked after the directive identifier is read and is responsible for
104 /// parsing and validating the rest of the directive. The handler is passed
105 /// in the directive name and the location of the directive keyword.
106 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
108 /// MacroMap - Map of currently defined macros.
109 StringMap<Macro*> MacroMap;
111 /// ActiveMacros - Stack of active macro instantiations.
112 std::vector<MacroInstantiation*> ActiveMacros;
114 /// Boolean tracking whether macro substitution is enabled.
115 unsigned MacrosEnabled : 1;
117 /// Flag tracking whether any errors have been encountered.
118 unsigned HadError : 1;
120 /// The values from the last parsed cpp hash file line comment if any.
121 StringRef CppHashFilename;
122 int64_t CppHashLineNumber;
126 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
127 const MCAsmInfo &MAI);
130 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
132 void AddDirectiveHandler(MCAsmParserExtension *Object,
134 DirectiveHandler Handler) {
135 DirectiveMap[Directive] = std::make_pair(Object, Handler);
139 /// @name MCAsmParser Interface
142 virtual SourceMgr &getSourceManager() { return SrcMgr; }
143 virtual MCAsmLexer &getLexer() { return Lexer; }
144 virtual MCContext &getContext() { return Ctx; }
145 virtual MCStreamer &getStreamer() { return Out; }
147 virtual bool Warning(SMLoc L, const Twine &Msg,
148 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
149 virtual bool Error(SMLoc L, const Twine &Msg,
150 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
152 const AsmToken &Lex();
154 bool ParseExpression(const MCExpr *&Res);
155 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
156 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
157 virtual bool ParseAbsoluteExpression(int64_t &Res);
162 void CheckForValidSection();
164 bool ParseStatement();
165 void EatToEndOfLine();
166 bool ParseCppHashLineFilenameComment(const SMLoc &L);
168 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
169 bool expandMacro(SmallString<256> &Buf, StringRef Body,
170 const std::vector<StringRef> &Parameters,
171 const std::vector<std::vector<AsmToken> > &A,
173 void HandleMacroExit();
175 void PrintMacroInstantiations();
176 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
177 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
178 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
180 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
182 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
183 bool EnterIncludeFile(const std::string &Filename);
184 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
185 /// This returns true on failure.
186 bool ProcessIncbinFile(const std::string &Filename);
188 /// \brief Reset the current lexer position to that given by \arg Loc. The
189 /// current token is not set; clients should ensure Lex() is called
191 void JumpToLoc(SMLoc Loc);
193 void EatToEndOfStatement();
195 /// \brief Parse up to the end of statement and a return the contents from the
196 /// current token until the end of the statement; the current token on exit
197 /// will be either the EndOfStatement or EOF.
198 StringRef ParseStringToEndOfStatement();
200 bool ParseAssignment(StringRef Name, bool allow_redef);
202 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
203 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
204 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
205 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
207 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
208 /// and set \arg Res to the identifier contents.
209 bool ParseIdentifier(StringRef &Res);
211 // Directive Parsing.
213 // ".ascii", ".asciiz", ".string"
214 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
215 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
216 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
217 bool ParseDirectiveFill(); // ".fill"
218 bool ParseDirectiveSpace(); // ".space"
219 bool ParseDirectiveZero(); // ".zero"
220 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
221 bool ParseDirectiveOrg(); // ".org"
222 // ".align{,32}", ".p2align{,w,l}"
223 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
225 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
226 /// accepts a single symbol (which should be a label or an external).
227 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
229 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
231 bool ParseDirectiveAbort(); // ".abort"
232 bool ParseDirectiveInclude(); // ".include"
233 bool ParseDirectiveIncbin(); // ".incbin"
235 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
236 // ".ifdef" or ".ifndef", depending on expect_defined
237 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
238 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
239 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
240 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
242 /// ParseEscapedString - Parse the current token as a string which may include
243 /// escaped characters and return the string contents.
244 bool ParseEscapedString(std::string &Data);
246 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
247 MCSymbolRefExpr::VariantKind Variant);
250 /// \brief Generic implementations of directive handling, etc. which is shared
251 /// (or the default, at least) for all assembler parser.
252 class GenericAsmParser : public MCAsmParserExtension {
253 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
254 void AddDirectiveHandler(StringRef Directive) {
255 getParser().AddDirectiveHandler(this, Directive,
256 HandleDirective<GenericAsmParser, Handler>);
259 GenericAsmParser() {}
261 AsmParser &getParser() {
262 return (AsmParser&) this->MCAsmParserExtension::getParser();
265 virtual void Initialize(MCAsmParser &Parser) {
266 // Call the base implementation.
267 this->MCAsmParserExtension::Initialize(Parser);
269 // Debugging directives.
270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
278 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
280 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
282 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
285 ".cfi_def_cfa_offset");
286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
287 ".cfi_adjust_cfa_offset");
288 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
289 ".cfi_def_cfa_register");
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
295 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
297 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
299 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
301 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
303 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
305 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
307 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
310 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
312 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
314 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
315 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
316 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
318 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
319 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
322 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
324 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
325 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
326 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
327 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
328 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
329 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
330 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
331 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
332 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
333 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
334 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
335 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
336 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
337 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
338 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
339 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
340 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
341 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
342 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
344 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
345 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
346 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
348 bool ParseDirectiveLEB128(StringRef, SMLoc);
355 extern MCAsmParserExtension *createDarwinAsmParser();
356 extern MCAsmParserExtension *createELFAsmParser();
357 extern MCAsmParserExtension *createCOFFAsmParser();
361 enum { DEFAULT_ADDRSPACE = 0 };
363 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
364 MCStreamer &_Out, const MCAsmInfo &_MAI)
365 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
366 GenericParser(new GenericAsmParser), PlatformParser(0),
367 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0) {
368 // Save the old handler.
369 SavedDiagHandler = SrcMgr.getDiagHandler();
370 SavedDiagContext = SrcMgr.getDiagContext();
371 // Set our own handler which calls the saved handler.
372 SrcMgr.setDiagHandler(DiagHandler, this);
373 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
375 // Initialize the generic parser.
376 GenericParser->Initialize(*this);
378 // Initialize the platform / file format parser.
380 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
382 if (_MAI.hasMicrosoftFastStdCallMangling()) {
383 PlatformParser = createCOFFAsmParser();
384 PlatformParser->Initialize(*this);
385 } else if (_MAI.hasSubsectionsViaSymbols()) {
386 PlatformParser = createDarwinAsmParser();
387 PlatformParser->Initialize(*this);
389 PlatformParser = createELFAsmParser();
390 PlatformParser->Initialize(*this);
394 AsmParser::~AsmParser() {
395 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
397 // Destroy any macros.
398 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
399 ie = MacroMap.end(); it != ie; ++it)
400 delete it->getValue();
402 delete PlatformParser;
403 delete GenericParser;
406 void AsmParser::PrintMacroInstantiations() {
407 // Print the active macro instantiation stack.
408 for (std::vector<MacroInstantiation*>::const_reverse_iterator
409 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
410 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
411 "while in macro instantiation");
414 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
415 if (FatalAssemblerWarnings)
416 return Error(L, Msg, Ranges);
417 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
418 PrintMacroInstantiations();
422 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
424 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
425 PrintMacroInstantiations();
429 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
430 std::string IncludedFile;
431 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
437 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
442 /// Process the specified .incbin file by seaching for it in the include paths
443 /// then just emiting the byte contents of the file to the streamer. This
444 /// returns true on failure.
445 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
446 std::string IncludedFile;
447 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
451 // Pick up the bytes from the file and emit them.
452 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
457 void AsmParser::JumpToLoc(SMLoc Loc) {
458 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
459 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
462 const AsmToken &AsmParser::Lex() {
463 const AsmToken *tok = &Lexer.Lex();
465 if (tok->is(AsmToken::Eof)) {
466 // If this is the end of an included file, pop the parent file off the
468 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
469 if (ParentIncludeLoc != SMLoc()) {
470 JumpToLoc(ParentIncludeLoc);
475 if (tok->is(AsmToken::Error))
476 Error(Lexer.getErrLoc(), Lexer.getErr());
481 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
482 // Create the initial section, if requested.
483 if (!NoInitialTextSection)
490 AsmCond StartingCondState = TheCondState;
492 // If we are generating dwarf for assembly source files save the initial text
493 // section and generate a .file directive.
494 if (getContext().getGenDwarfForAssembly()) {
495 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
496 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
497 getStreamer().EmitLabel(SectionStartSym);
498 getContext().setGenDwarfSectionStartSym(SectionStartSym);
499 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
500 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
503 // While we have input, parse each statement.
504 while (Lexer.isNot(AsmToken::Eof)) {
505 if (!ParseStatement()) continue;
507 // We had an error, validate that one was emitted and recover by skipping to
509 assert(HadError && "Parse statement returned an error, but none emitted!");
510 EatToEndOfStatement();
513 if (TheCondState.TheCond != StartingCondState.TheCond ||
514 TheCondState.Ignore != StartingCondState.Ignore)
515 return TokError("unmatched .ifs or .elses");
517 // Check to see there are no empty DwarfFile slots.
518 const std::vector<MCDwarfFile *> &MCDwarfFiles =
519 getContext().getMCDwarfFiles();
520 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
521 if (!MCDwarfFiles[i])
522 TokError("unassigned file number: " + Twine(i) + " for .file directives");
525 // Check to see that all assembler local symbols were actually defined.
526 // Targets that don't do subsections via symbols may not want this, though,
527 // so conservatively exclude them. Only do this if we're finalizing, though,
528 // as otherwise we won't necessarilly have seen everything yet.
529 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
530 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
531 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
534 MCSymbol *Sym = i->getValue();
535 // Variable symbols may not be marked as defined, so check those
536 // explicitly. If we know it's a variable, we have a definition for
537 // the purposes of this check.
538 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
539 // FIXME: We would really like to refer back to where the symbol was
540 // first referenced for a source location. We need to add something
541 // to track that. Currently, we just point to the end of the file.
542 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
543 "assembler local symbol '" + Sym->getName() +
549 // Finalize the output stream if there are no errors and if the client wants
551 if (!HadError && !NoFinalize)
557 void AsmParser::CheckForValidSection() {
558 if (!getStreamer().getCurrentSection()) {
559 TokError("expected section directive before assembly directive");
560 Out.SwitchSection(Ctx.getMachOSection(
562 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
563 0, SectionKind::getText()));
567 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
568 void AsmParser::EatToEndOfStatement() {
569 while (Lexer.isNot(AsmToken::EndOfStatement) &&
570 Lexer.isNot(AsmToken::Eof))
574 if (Lexer.is(AsmToken::EndOfStatement))
578 StringRef AsmParser::ParseStringToEndOfStatement() {
579 const char *Start = getTok().getLoc().getPointer();
581 while (Lexer.isNot(AsmToken::EndOfStatement) &&
582 Lexer.isNot(AsmToken::Eof))
585 const char *End = getTok().getLoc().getPointer();
586 return StringRef(Start, End - Start);
589 /// ParseParenExpr - Parse a paren expression and return it.
590 /// NOTE: This assumes the leading '(' has already been consumed.
592 /// parenexpr ::= expr)
594 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
595 if (ParseExpression(Res)) return true;
596 if (Lexer.isNot(AsmToken::RParen))
597 return TokError("expected ')' in parentheses expression");
598 EndLoc = Lexer.getLoc();
603 /// ParseBracketExpr - Parse a bracket expression and return it.
604 /// NOTE: This assumes the leading '[' has already been consumed.
606 /// bracketexpr ::= expr]
608 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
609 if (ParseExpression(Res)) return true;
610 if (Lexer.isNot(AsmToken::RBrac))
611 return TokError("expected ']' in brackets expression");
612 EndLoc = Lexer.getLoc();
617 /// ParsePrimaryExpr - Parse a primary expression and return it.
618 /// primaryexpr ::= (parenexpr
619 /// primaryexpr ::= symbol
620 /// primaryexpr ::= number
621 /// primaryexpr ::= '.'
622 /// primaryexpr ::= ~,+,- primaryexpr
623 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
624 switch (Lexer.getKind()) {
626 return TokError("unknown token in expression");
627 // If we have an error assume that we've already handled it.
628 case AsmToken::Error:
630 case AsmToken::Exclaim:
631 Lex(); // Eat the operator.
632 if (ParsePrimaryExpr(Res, EndLoc))
634 Res = MCUnaryExpr::CreateLNot(Res, getContext());
636 case AsmToken::Dollar:
637 case AsmToken::String:
638 case AsmToken::Identifier: {
639 EndLoc = Lexer.getLoc();
641 StringRef Identifier;
642 if (ParseIdentifier(Identifier))
645 // This is a symbol reference.
646 std::pair<StringRef, StringRef> Split = Identifier.split('@');
647 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
649 // Lookup the symbol variant if used.
650 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
651 if (Split.first.size() != Identifier.size()) {
652 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
653 if (Variant == MCSymbolRefExpr::VK_Invalid) {
654 Variant = MCSymbolRefExpr::VK_None;
655 return TokError("invalid variant '" + Split.second + "'");
659 // If this is an absolute variable reference, substitute it now to preserve
660 // semantics in the face of reassignment.
661 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
663 return Error(EndLoc, "unexpected modifier on variable reference");
665 Res = Sym->getVariableValue();
669 // Otherwise create a symbol ref.
670 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
673 case AsmToken::Integer: {
674 SMLoc Loc = getTok().getLoc();
675 int64_t IntVal = getTok().getIntVal();
676 Res = MCConstantExpr::Create(IntVal, getContext());
677 EndLoc = Lexer.getLoc();
679 // Look for 'b' or 'f' following an Integer as a directional label
680 if (Lexer.getKind() == AsmToken::Identifier) {
681 StringRef IDVal = getTok().getString();
682 if (IDVal == "f" || IDVal == "b"){
683 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
684 IDVal == "f" ? 1 : 0);
685 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
687 if(IDVal == "b" && Sym->isUndefined())
688 return Error(Loc, "invalid reference to undefined symbol");
689 EndLoc = Lexer.getLoc();
690 Lex(); // Eat identifier.
695 case AsmToken::Real: {
696 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
697 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
698 Res = MCConstantExpr::Create(IntVal, getContext());
702 case AsmToken::Dot: {
703 // This is a '.' reference, which references the current PC. Emit a
704 // temporary label to the streamer and refer to it.
705 MCSymbol *Sym = Ctx.CreateTempSymbol();
707 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
708 EndLoc = Lexer.getLoc();
709 Lex(); // Eat identifier.
712 case AsmToken::LParen:
713 Lex(); // Eat the '('.
714 return ParseParenExpr(Res, EndLoc);
715 case AsmToken::LBrac:
716 if (!PlatformParser->HasBracketExpressions())
717 return TokError("brackets expression not supported on this target");
718 Lex(); // Eat the '['.
719 return ParseBracketExpr(Res, EndLoc);
720 case AsmToken::Minus:
721 Lex(); // Eat the operator.
722 if (ParsePrimaryExpr(Res, EndLoc))
724 Res = MCUnaryExpr::CreateMinus(Res, getContext());
727 Lex(); // Eat the operator.
728 if (ParsePrimaryExpr(Res, EndLoc))
730 Res = MCUnaryExpr::CreatePlus(Res, getContext());
732 case AsmToken::Tilde:
733 Lex(); // Eat the operator.
734 if (ParsePrimaryExpr(Res, EndLoc))
736 Res = MCUnaryExpr::CreateNot(Res, getContext());
741 bool AsmParser::ParseExpression(const MCExpr *&Res) {
743 return ParseExpression(Res, EndLoc);
747 AsmParser::ApplyModifierToExpr(const MCExpr *E,
748 MCSymbolRefExpr::VariantKind Variant) {
749 // Recurse over the given expression, rebuilding it to apply the given variant
750 // if there is exactly one symbol.
751 switch (E->getKind()) {
753 case MCExpr::Constant:
756 case MCExpr::SymbolRef: {
757 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
759 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
760 TokError("invalid variant on expression '" +
761 getTok().getIdentifier() + "' (already modified)");
765 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
768 case MCExpr::Unary: {
769 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
770 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
773 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
776 case MCExpr::Binary: {
777 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
778 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
779 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
784 if (!LHS) LHS = BE->getLHS();
785 if (!RHS) RHS = BE->getRHS();
787 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
791 assert(0 && "Invalid expression kind!");
795 /// ParseExpression - Parse an expression and return it.
797 /// expr ::= expr &&,|| expr -> lowest.
798 /// expr ::= expr |,^,&,! expr
799 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
800 /// expr ::= expr <<,>> expr
801 /// expr ::= expr +,- expr
802 /// expr ::= expr *,/,% expr -> highest.
803 /// expr ::= primaryexpr
805 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
806 // Parse the expression.
808 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
811 // As a special case, we support 'a op b @ modifier' by rewriting the
812 // expression to include the modifier. This is inefficient, but in general we
813 // expect users to use 'a@modifier op b'.
814 if (Lexer.getKind() == AsmToken::At) {
817 if (Lexer.isNot(AsmToken::Identifier))
818 return TokError("unexpected symbol modifier following '@'");
820 MCSymbolRefExpr::VariantKind Variant =
821 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
822 if (Variant == MCSymbolRefExpr::VK_Invalid)
823 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
825 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
827 return TokError("invalid modifier '" + getTok().getIdentifier() +
828 "' (no symbols present)");
836 // Try to constant fold it up front, if possible.
838 if (Res->EvaluateAsAbsolute(Value))
839 Res = MCConstantExpr::Create(Value, getContext());
844 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
846 return ParseParenExpr(Res, EndLoc) ||
847 ParseBinOpRHS(1, Res, EndLoc);
850 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
853 SMLoc StartLoc = Lexer.getLoc();
854 if (ParseExpression(Expr))
857 if (!Expr->EvaluateAsAbsolute(Res))
858 return Error(StartLoc, "expected absolute expression");
863 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
864 MCBinaryExpr::Opcode &Kind) {
867 return 0; // not a binop.
869 // Lowest Precedence: &&, ||
870 case AsmToken::AmpAmp:
871 Kind = MCBinaryExpr::LAnd;
873 case AsmToken::PipePipe:
874 Kind = MCBinaryExpr::LOr;
878 // Low Precedence: |, &, ^
880 // FIXME: gas seems to support '!' as an infix operator?
882 Kind = MCBinaryExpr::Or;
884 case AsmToken::Caret:
885 Kind = MCBinaryExpr::Xor;
888 Kind = MCBinaryExpr::And;
891 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
892 case AsmToken::EqualEqual:
893 Kind = MCBinaryExpr::EQ;
895 case AsmToken::ExclaimEqual:
896 case AsmToken::LessGreater:
897 Kind = MCBinaryExpr::NE;
900 Kind = MCBinaryExpr::LT;
902 case AsmToken::LessEqual:
903 Kind = MCBinaryExpr::LTE;
905 case AsmToken::Greater:
906 Kind = MCBinaryExpr::GT;
908 case AsmToken::GreaterEqual:
909 Kind = MCBinaryExpr::GTE;
912 // Intermediate Precedence: <<, >>
913 case AsmToken::LessLess:
914 Kind = MCBinaryExpr::Shl;
916 case AsmToken::GreaterGreater:
917 Kind = MCBinaryExpr::Shr;
920 // High Intermediate Precedence: +, -
922 Kind = MCBinaryExpr::Add;
924 case AsmToken::Minus:
925 Kind = MCBinaryExpr::Sub;
928 // Highest Precedence: *, /, %
930 Kind = MCBinaryExpr::Mul;
932 case AsmToken::Slash:
933 Kind = MCBinaryExpr::Div;
935 case AsmToken::Percent:
936 Kind = MCBinaryExpr::Mod;
942 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
943 /// Res contains the LHS of the expression on input.
944 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
947 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
948 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
950 // If the next token is lower precedence than we are allowed to eat, return
951 // successfully with what we ate already.
952 if (TokPrec < Precedence)
957 // Eat the next primary expression.
959 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
961 // If BinOp binds less tightly with RHS than the operator after RHS, let
962 // the pending operator take RHS as its LHS.
963 MCBinaryExpr::Opcode Dummy;
964 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
965 if (TokPrec < NextTokPrec) {
966 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
969 // Merge LHS and RHS according to operator.
970 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
978 /// ::= EndOfStatement
979 /// ::= Label* Directive ...Operands... EndOfStatement
980 /// ::= Label* Identifier OperandList* EndOfStatement
981 bool AsmParser::ParseStatement() {
982 if (Lexer.is(AsmToken::EndOfStatement)) {
988 // Statements always start with an identifier or are a full line comment.
989 AsmToken ID = getTok();
990 SMLoc IDLoc = ID.getLoc();
992 int64_t LocalLabelVal = -1;
993 // A full line comment is a '#' as the first token.
994 if (Lexer.is(AsmToken::Hash))
995 return ParseCppHashLineFilenameComment(IDLoc);
997 // Allow an integer followed by a ':' as a directional local label.
998 if (Lexer.is(AsmToken::Integer)) {
999 LocalLabelVal = getTok().getIntVal();
1000 if (LocalLabelVal < 0) {
1001 if (!TheCondState.Ignore)
1002 return TokError("unexpected token at start of statement");
1006 IDVal = getTok().getString();
1007 Lex(); // Consume the integer token to be used as an identifier token.
1008 if (Lexer.getKind() != AsmToken::Colon) {
1009 if (!TheCondState.Ignore)
1010 return TokError("unexpected token at start of statement");
1014 } else if (Lexer.is(AsmToken::Dot)) {
1015 // Treat '.' as a valid identifier in this context.
1019 } else if (ParseIdentifier(IDVal)) {
1020 if (!TheCondState.Ignore)
1021 return TokError("unexpected token at start of statement");
1026 // Handle conditional assembly here before checking for skipping. We
1027 // have to do this so that .endif isn't skipped in a ".if 0" block for
1030 return ParseDirectiveIf(IDLoc);
1031 if (IDVal == ".ifdef")
1032 return ParseDirectiveIfdef(IDLoc, true);
1033 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1034 return ParseDirectiveIfdef(IDLoc, false);
1035 if (IDVal == ".elseif")
1036 return ParseDirectiveElseIf(IDLoc);
1037 if (IDVal == ".else")
1038 return ParseDirectiveElse(IDLoc);
1039 if (IDVal == ".endif")
1040 return ParseDirectiveEndIf(IDLoc);
1042 // If we are in a ".if 0" block, ignore this statement.
1043 if (TheCondState.Ignore) {
1044 EatToEndOfStatement();
1048 // FIXME: Recurse on local labels?
1050 // See what kind of statement we have.
1051 switch (Lexer.getKind()) {
1052 case AsmToken::Colon: {
1053 CheckForValidSection();
1055 // identifier ':' -> Label.
1058 // Diagnose attempt to use '.' as a label.
1060 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1062 // Diagnose attempt to use a variable as a label.
1064 // FIXME: Diagnostics. Note the location of the definition as a label.
1065 // FIXME: This doesn't diagnose assignment to a symbol which has been
1066 // implicitly marked as external.
1068 if (LocalLabelVal == -1)
1069 Sym = getContext().GetOrCreateSymbol(IDVal);
1071 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1072 if (!Sym->isUndefined() || Sym->isVariable())
1073 return Error(IDLoc, "invalid symbol redefinition");
1078 // If we are generating dwarf for assembly source files then gather the
1079 // info to make a dwarf label entry for this label if needed.
1080 if (getContext().getGenDwarfForAssembly())
1081 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1084 // Consume any end of statement token, if present, to avoid spurious
1085 // AddBlankLine calls().
1086 if (Lexer.is(AsmToken::EndOfStatement)) {
1088 if (Lexer.is(AsmToken::Eof))
1092 return ParseStatement();
1095 case AsmToken::Equal:
1096 // identifier '=' ... -> assignment statement
1099 return ParseAssignment(IDVal, true);
1101 default: // Normal instruction or directive.
1105 // If macros are enabled, check to see if this is a macro instantiation.
1107 if (const Macro *M = MacroMap.lookup(IDVal))
1108 return HandleMacroEntry(IDVal, IDLoc, M);
1110 // Otherwise, we have a normal instruction or directive.
1111 if (IDVal[0] == '.' && IDVal != ".") {
1112 // Assembler features
1113 if (IDVal == ".set" || IDVal == ".equ")
1114 return ParseDirectiveSet(IDVal, true);
1115 if (IDVal == ".equiv")
1116 return ParseDirectiveSet(IDVal, false);
1120 if (IDVal == ".ascii")
1121 return ParseDirectiveAscii(IDVal, false);
1122 if (IDVal == ".asciz" || IDVal == ".string")
1123 return ParseDirectiveAscii(IDVal, true);
1125 if (IDVal == ".byte")
1126 return ParseDirectiveValue(1);
1127 if (IDVal == ".short")
1128 return ParseDirectiveValue(2);
1129 if (IDVal == ".value")
1130 return ParseDirectiveValue(2);
1131 if (IDVal == ".2byte")
1132 return ParseDirectiveValue(2);
1133 if (IDVal == ".long")
1134 return ParseDirectiveValue(4);
1135 if (IDVal == ".int")
1136 return ParseDirectiveValue(4);
1137 if (IDVal == ".4byte")
1138 return ParseDirectiveValue(4);
1139 if (IDVal == ".quad")
1140 return ParseDirectiveValue(8);
1141 if (IDVal == ".8byte")
1142 return ParseDirectiveValue(8);
1143 if (IDVal == ".single" || IDVal == ".float")
1144 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1145 if (IDVal == ".double")
1146 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1148 if (IDVal == ".align") {
1149 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1150 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1152 if (IDVal == ".align32") {
1153 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1154 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1156 if (IDVal == ".balign")
1157 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1158 if (IDVal == ".balignw")
1159 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1160 if (IDVal == ".balignl")
1161 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1162 if (IDVal == ".p2align")
1163 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1164 if (IDVal == ".p2alignw")
1165 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1166 if (IDVal == ".p2alignl")
1167 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1169 if (IDVal == ".org")
1170 return ParseDirectiveOrg();
1172 if (IDVal == ".fill")
1173 return ParseDirectiveFill();
1174 if (IDVal == ".space" || IDVal == ".skip")
1175 return ParseDirectiveSpace();
1176 if (IDVal == ".zero")
1177 return ParseDirectiveZero();
1179 // Symbol attribute directives
1181 if (IDVal == ".globl" || IDVal == ".global")
1182 return ParseDirectiveSymbolAttribute(MCSA_Global);
1183 if (IDVal == ".indirect_symbol")
1184 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1185 if (IDVal == ".lazy_reference")
1186 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1187 if (IDVal == ".no_dead_strip")
1188 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1189 if (IDVal == ".symbol_resolver")
1190 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1191 if (IDVal == ".private_extern")
1192 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1193 if (IDVal == ".reference")
1194 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1195 if (IDVal == ".weak_definition")
1196 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1197 if (IDVal == ".weak_reference")
1198 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1199 if (IDVal == ".weak_def_can_be_hidden")
1200 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1202 if (IDVal == ".comm" || IDVal == ".common")
1203 return ParseDirectiveComm(/*IsLocal=*/false);
1204 if (IDVal == ".lcomm")
1205 return ParseDirectiveComm(/*IsLocal=*/true);
1207 if (IDVal == ".abort")
1208 return ParseDirectiveAbort();
1209 if (IDVal == ".include")
1210 return ParseDirectiveInclude();
1211 if (IDVal == ".incbin")
1212 return ParseDirectiveIncbin();
1214 if (IDVal == ".code16")
1215 return TokError(Twine(IDVal) + " not supported yet");
1217 // Look up the handler in the handler table.
1218 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1219 DirectiveMap.lookup(IDVal);
1221 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1223 // Target hook for parsing target specific directives.
1224 if (!getTargetParser().ParseDirective(ID))
1227 bool retval = Warning(IDLoc, "ignoring directive for now");
1228 EatToEndOfStatement();
1232 CheckForValidSection();
1234 // Canonicalize the opcode to lower case.
1235 SmallString<128> Opcode;
1236 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1237 Opcode.push_back(tolower(IDVal[i]));
1239 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1240 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1243 // Dump the parsed representation, if requested.
1244 if (getShowParsedOperands()) {
1245 SmallString<256> Str;
1246 raw_svector_ostream OS(Str);
1247 OS << "parsed instruction: [";
1248 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1251 ParsedOperands[i]->print(OS);
1255 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1258 // If we are generating dwarf for assembly source files and the current
1259 // section is the initial text section then generate a .loc directive for
1261 if (!HadError && getContext().getGenDwarfForAssembly() &&
1262 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1263 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1264 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1265 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1266 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1270 // If parsing succeeded, match the instruction.
1272 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1275 // Free any parsed operands.
1276 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1277 delete ParsedOperands[i];
1279 // Don't skip the rest of the line, the instruction parser is responsible for
1284 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1285 /// since they may not be able to be tokenized to get to the end of line token.
1286 void AsmParser::EatToEndOfLine() {
1287 if (!Lexer.is(AsmToken::EndOfStatement))
1288 Lexer.LexUntilEndOfLine();
1293 /// ParseCppHashLineFilenameComment as this:
1294 /// ::= # number "filename"
1295 /// or just as a full line comment if it doesn't have a number and a string.
1296 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1297 Lex(); // Eat the hash token.
1299 if (getLexer().isNot(AsmToken::Integer)) {
1300 // Consume the line since in cases it is not a well-formed line directive,
1301 // as if were simply a full line comment.
1306 int64_t LineNumber = getTok().getIntVal();
1309 if (getLexer().isNot(AsmToken::String)) {
1314 StringRef Filename = getTok().getString();
1315 // Get rid of the enclosing quotes.
1316 Filename = Filename.substr(1, Filename.size()-2);
1318 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1320 CppHashFilename = Filename;
1321 CppHashLineNumber = LineNumber;
1323 // Ignore any trailing characters, they're just comment.
1328 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1329 /// for the Filename and LineNo if any in the diagnostic.
1330 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1331 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1332 raw_ostream &OS = errs();
1334 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1335 const SMLoc &DiagLoc = Diag.getLoc();
1336 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1337 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1339 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1340 // before printing the message.
1341 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1342 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1343 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1344 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1347 // If we have not parsed a cpp hash line filename comment or the source
1348 // manager changed or buffer changed (like in a nested include) then just
1349 // print the normal diagnostic using its Filename and LineNo.
1350 if (!Parser->CppHashLineNumber ||
1351 &DiagSrcMgr != &Parser->SrcMgr ||
1352 DiagBuf != CppHashBuf) {
1353 if (Parser->SavedDiagHandler)
1354 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1360 // Use the CppHashFilename and calculate a line number based on the
1361 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1363 const std::string Filename = Parser->CppHashFilename;
1365 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1366 int CppHashLocLineNo =
1367 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1368 int LineNo = Parser->CppHashLineNumber - 1 +
1369 (DiagLocLineNo - CppHashLocLineNo);
1371 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1372 Filename, LineNo, Diag.getColumnNo(),
1373 Diag.getKind(), Diag.getMessage(),
1374 Diag.getLineContents(), Diag.getRanges());
1376 if (Parser->SavedDiagHandler)
1377 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1379 NewDiag.print(0, OS);
1382 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1383 const std::vector<StringRef> &Parameters,
1384 const std::vector<std::vector<AsmToken> > &A,
1386 raw_svector_ostream OS(Buf);
1387 unsigned NParameters = Parameters.size();
1388 if (NParameters != 0 && NParameters != A.size())
1389 return Error(L, "Wrong number of arguments");
1391 while (!Body.empty()) {
1392 // Scan for the next substitution.
1393 std::size_t End = Body.size(), Pos = 0;
1394 for (; Pos != End; ++Pos) {
1395 // Check for a substitution or escape.
1397 // This macro has no parameters, look for $0, $1, etc.
1398 if (Body[Pos] != '$' || Pos + 1 == End)
1401 char Next = Body[Pos + 1];
1402 if (Next == '$' || Next == 'n' || isdigit(Next))
1405 // This macro has parameters, look for \foo, \bar, etc.
1406 if (Body[Pos] == '\\' && Pos + 1 != End)
1412 OS << Body.slice(0, Pos);
1414 // Check if we reached the end.
1419 switch (Body[Pos+1]) {
1425 // $n => number of arguments
1430 // $[0-9] => argument
1432 // Missing arguments are ignored.
1433 unsigned Index = Body[Pos+1] - '0';
1434 if (Index >= A.size())
1437 // Otherwise substitute with the token values, with spaces eliminated.
1438 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1439 ie = A[Index].end(); it != ie; ++it)
1440 OS << it->getString();
1446 unsigned I = Pos + 1;
1447 while (isalnum(Body[I]) && I + 1 != End)
1450 const char *Begin = Body.data() + Pos +1;
1451 StringRef Argument(Begin, I - (Pos +1));
1453 for (; Index < NParameters; ++Index)
1454 if (Parameters[Index] == Argument)
1457 // FIXME: We should error at the macro definition.
1458 if (Index == NParameters)
1459 return Error(L, "Parameter not found");
1461 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1462 ie = A[Index].end(); it != ie; ++it)
1463 OS << it->getString();
1465 Pos += 1 + Argument.size();
1467 // Update the scan point.
1468 Body = Body.substr(Pos);
1471 // We include the .endmacro in the buffer as our queue to exit the macro
1473 OS << ".endmacro\n";
1477 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1479 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1483 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1485 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1486 // this, although we should protect against infinite loops.
1487 if (ActiveMacros.size() == 20)
1488 return TokError("macros cannot be nested more than 20 levels deep");
1490 // Parse the macro instantiation arguments.
1491 std::vector<std::vector<AsmToken> > MacroArguments;
1492 MacroArguments.push_back(std::vector<AsmToken>());
1493 unsigned ParenLevel = 0;
1495 if (Lexer.is(AsmToken::Eof))
1496 return TokError("unexpected token in macro instantiation");
1497 if (Lexer.is(AsmToken::EndOfStatement))
1500 // If we aren't inside parentheses and this is a comma, start a new token
1502 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1503 MacroArguments.push_back(std::vector<AsmToken>());
1505 // Adjust the current parentheses level.
1506 if (Lexer.is(AsmToken::LParen))
1508 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1511 // Append the token to the current argument list.
1512 MacroArguments.back().push_back(getTok());
1517 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1518 // to hold the macro body with substitutions.
1519 SmallString<256> Buf;
1520 StringRef Body = M->Body;
1522 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1525 MemoryBuffer *Instantiation =
1526 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1528 // Create the macro instantiation object and add to the current macro
1529 // instantiation stack.
1530 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1533 ActiveMacros.push_back(MI);
1535 // Jump to the macro instantiation and prime the lexer.
1536 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1537 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1543 void AsmParser::HandleMacroExit() {
1544 // Jump to the EndOfStatement we should return to, and consume it.
1545 JumpToLoc(ActiveMacros.back()->ExitLoc);
1548 // Pop the instantiation entry.
1549 delete ActiveMacros.back();
1550 ActiveMacros.pop_back();
1553 static void MarkUsed(const MCExpr *Value) {
1554 switch (Value->getKind()) {
1555 case MCExpr::Binary:
1556 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1557 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1559 case MCExpr::Target:
1560 case MCExpr::Constant:
1562 case MCExpr::SymbolRef: {
1563 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1567 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1572 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1573 // FIXME: Use better location, we should use proper tokens.
1574 SMLoc EqualLoc = Lexer.getLoc();
1576 const MCExpr *Value;
1577 if (ParseExpression(Value))
1582 if (Lexer.isNot(AsmToken::EndOfStatement))
1583 return TokError("unexpected token in assignment");
1585 // Error on assignment to '.'.
1587 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1588 "(use '.space' or '.org').)"));
1591 // Eat the end of statement marker.
1594 // Validate that the LHS is allowed to be a variable (either it has not been
1595 // used as a symbol, or it is an absolute symbol).
1596 MCSymbol *Sym = getContext().LookupSymbol(Name);
1598 // Diagnose assignment to a label.
1600 // FIXME: Diagnostics. Note the location of the definition as a label.
1601 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1602 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1603 ; // Allow redefinitions of undefined symbols only used in directives.
1604 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1605 return Error(EqualLoc, "redefinition of '" + Name + "'");
1606 else if (!Sym->isVariable())
1607 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1608 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1609 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1612 // Don't count these checks as uses.
1613 Sym->setUsed(false);
1615 Sym = getContext().GetOrCreateSymbol(Name);
1617 // FIXME: Handle '.'.
1619 // Do the assignment.
1620 Out.EmitAssignment(Sym, Value);
1625 /// ParseIdentifier:
1628 bool AsmParser::ParseIdentifier(StringRef &Res) {
1629 // The assembler has relaxed rules for accepting identifiers, in particular we
1630 // allow things like '.globl $foo', which would normally be separate
1631 // tokens. At this level, we have already lexed so we cannot (currently)
1632 // handle this as a context dependent token, instead we detect adjacent tokens
1633 // and return the combined identifier.
1634 if (Lexer.is(AsmToken::Dollar)) {
1635 SMLoc DollarLoc = getLexer().getLoc();
1637 // Consume the dollar sign, and check for a following identifier.
1639 if (Lexer.isNot(AsmToken::Identifier))
1642 // We have a '$' followed by an identifier, make sure they are adjacent.
1643 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1646 // Construct the joined identifier and consume the token.
1647 Res = StringRef(DollarLoc.getPointer(),
1648 getTok().getIdentifier().size() + 1);
1653 if (Lexer.isNot(AsmToken::Identifier) &&
1654 Lexer.isNot(AsmToken::String))
1657 Res = getTok().getIdentifier();
1659 Lex(); // Consume the identifier token.
1664 /// ParseDirectiveSet:
1665 /// ::= .equ identifier ',' expression
1666 /// ::= .equiv identifier ',' expression
1667 /// ::= .set identifier ',' expression
1668 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1671 if (ParseIdentifier(Name))
1672 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1674 if (getLexer().isNot(AsmToken::Comma))
1675 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1678 return ParseAssignment(Name, allow_redef);
1681 bool AsmParser::ParseEscapedString(std::string &Data) {
1682 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1685 StringRef Str = getTok().getStringContents();
1686 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1687 if (Str[i] != '\\') {
1692 // Recognize escaped characters. Note that this escape semantics currently
1693 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1696 return TokError("unexpected backslash at end of string");
1698 // Recognize octal sequences.
1699 if ((unsigned) (Str[i] - '0') <= 7) {
1700 // Consume up to three octal characters.
1701 unsigned Value = Str[i] - '0';
1703 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1705 Value = Value * 8 + (Str[i] - '0');
1707 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1709 Value = Value * 8 + (Str[i] - '0');
1714 return TokError("invalid octal escape sequence (out of range)");
1716 Data += (unsigned char) Value;
1720 // Otherwise recognize individual escapes.
1723 // Just reject invalid escape sequences for now.
1724 return TokError("invalid escape sequence (unrecognized character)");
1726 case 'b': Data += '\b'; break;
1727 case 'f': Data += '\f'; break;
1728 case 'n': Data += '\n'; break;
1729 case 'r': Data += '\r'; break;
1730 case 't': Data += '\t'; break;
1731 case '"': Data += '"'; break;
1732 case '\\': Data += '\\'; break;
1739 /// ParseDirectiveAscii:
1740 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1741 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1742 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1743 CheckForValidSection();
1746 if (getLexer().isNot(AsmToken::String))
1747 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1750 if (ParseEscapedString(Data))
1753 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1755 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1759 if (getLexer().is(AsmToken::EndOfStatement))
1762 if (getLexer().isNot(AsmToken::Comma))
1763 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1772 /// ParseDirectiveValue
1773 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1774 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1775 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1776 CheckForValidSection();
1779 const MCExpr *Value;
1780 SMLoc ExprLoc = getLexer().getLoc();
1781 if (ParseExpression(Value))
1784 // Special case constant expressions to match code generator.
1785 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1786 assert(Size <= 8 && "Invalid size");
1787 uint64_t IntValue = MCE->getValue();
1788 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1789 return Error(ExprLoc, "literal value out of range for directive");
1790 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1792 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1794 if (getLexer().is(AsmToken::EndOfStatement))
1797 // FIXME: Improve diagnostic.
1798 if (getLexer().isNot(AsmToken::Comma))
1799 return TokError("unexpected token in directive");
1808 /// ParseDirectiveRealValue
1809 /// ::= (.single | .double) [ expression (, expression)* ]
1810 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1811 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1812 CheckForValidSection();
1815 // We don't truly support arithmetic on floating point expressions, so we
1816 // have to manually parse unary prefixes.
1818 if (getLexer().is(AsmToken::Minus)) {
1821 } else if (getLexer().is(AsmToken::Plus))
1824 if (getLexer().isNot(AsmToken::Integer) &&
1825 getLexer().isNot(AsmToken::Real) &&
1826 getLexer().isNot(AsmToken::Identifier))
1827 return TokError("unexpected token in directive");
1829 // Convert to an APFloat.
1830 APFloat Value(Semantics);
1831 StringRef IDVal = getTok().getString();
1832 if (getLexer().is(AsmToken::Identifier)) {
1833 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1834 Value = APFloat::getInf(Semantics);
1835 else if (!IDVal.compare_lower("nan"))
1836 Value = APFloat::getNaN(Semantics, false, ~0);
1838 return TokError("invalid floating point literal");
1839 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1840 APFloat::opInvalidOp)
1841 return TokError("invalid floating point literal");
1845 // Consume the numeric token.
1848 // Emit the value as an integer.
1849 APInt AsInt = Value.bitcastToAPInt();
1850 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1851 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1853 if (getLexer().is(AsmToken::EndOfStatement))
1856 if (getLexer().isNot(AsmToken::Comma))
1857 return TokError("unexpected token in directive");
1866 /// ParseDirectiveSpace
1867 /// ::= .space expression [ , expression ]
1868 bool AsmParser::ParseDirectiveSpace() {
1869 CheckForValidSection();
1872 if (ParseAbsoluteExpression(NumBytes))
1875 int64_t FillExpr = 0;
1876 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1877 if (getLexer().isNot(AsmToken::Comma))
1878 return TokError("unexpected token in '.space' directive");
1881 if (ParseAbsoluteExpression(FillExpr))
1884 if (getLexer().isNot(AsmToken::EndOfStatement))
1885 return TokError("unexpected token in '.space' directive");
1891 return TokError("invalid number of bytes in '.space' directive");
1893 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1894 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1899 /// ParseDirectiveZero
1900 /// ::= .zero expression
1901 bool AsmParser::ParseDirectiveZero() {
1902 CheckForValidSection();
1905 if (ParseAbsoluteExpression(NumBytes))
1909 if (getLexer().is(AsmToken::Comma)) {
1911 if (ParseAbsoluteExpression(Val))
1915 if (getLexer().isNot(AsmToken::EndOfStatement))
1916 return TokError("unexpected token in '.zero' directive");
1920 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1925 /// ParseDirectiveFill
1926 /// ::= .fill expression , expression , expression
1927 bool AsmParser::ParseDirectiveFill() {
1928 CheckForValidSection();
1931 if (ParseAbsoluteExpression(NumValues))
1934 if (getLexer().isNot(AsmToken::Comma))
1935 return TokError("unexpected token in '.fill' directive");
1939 if (ParseAbsoluteExpression(FillSize))
1942 if (getLexer().isNot(AsmToken::Comma))
1943 return TokError("unexpected token in '.fill' directive");
1947 if (ParseAbsoluteExpression(FillExpr))
1950 if (getLexer().isNot(AsmToken::EndOfStatement))
1951 return TokError("unexpected token in '.fill' directive");
1955 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1956 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1958 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1959 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1964 /// ParseDirectiveOrg
1965 /// ::= .org expression [ , expression ]
1966 bool AsmParser::ParseDirectiveOrg() {
1967 CheckForValidSection();
1969 const MCExpr *Offset;
1970 if (ParseExpression(Offset))
1973 // Parse optional fill expression.
1974 int64_t FillExpr = 0;
1975 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1976 if (getLexer().isNot(AsmToken::Comma))
1977 return TokError("unexpected token in '.org' directive");
1980 if (ParseAbsoluteExpression(FillExpr))
1983 if (getLexer().isNot(AsmToken::EndOfStatement))
1984 return TokError("unexpected token in '.org' directive");
1989 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1990 // has to be relative to the current section.
1991 getStreamer().EmitValueToOffset(Offset, FillExpr);
1996 /// ParseDirectiveAlign
1997 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1998 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1999 CheckForValidSection();
2001 SMLoc AlignmentLoc = getLexer().getLoc();
2003 if (ParseAbsoluteExpression(Alignment))
2007 bool HasFillExpr = false;
2008 int64_t FillExpr = 0;
2009 int64_t MaxBytesToFill = 0;
2010 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2011 if (getLexer().isNot(AsmToken::Comma))
2012 return TokError("unexpected token in directive");
2015 // The fill expression can be omitted while specifying a maximum number of
2016 // alignment bytes, e.g:
2018 if (getLexer().isNot(AsmToken::Comma)) {
2020 if (ParseAbsoluteExpression(FillExpr))
2024 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2025 if (getLexer().isNot(AsmToken::Comma))
2026 return TokError("unexpected token in directive");
2029 MaxBytesLoc = getLexer().getLoc();
2030 if (ParseAbsoluteExpression(MaxBytesToFill))
2033 if (getLexer().isNot(AsmToken::EndOfStatement))
2034 return TokError("unexpected token in directive");
2043 // Compute alignment in bytes.
2045 // FIXME: Diagnose overflow.
2046 if (Alignment >= 32) {
2047 Error(AlignmentLoc, "invalid alignment value");
2051 Alignment = 1ULL << Alignment;
2054 // Diagnose non-sensical max bytes to align.
2055 if (MaxBytesLoc.isValid()) {
2056 if (MaxBytesToFill < 1) {
2057 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2058 "many bytes, ignoring maximum bytes expression");
2062 if (MaxBytesToFill >= Alignment) {
2063 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2069 // Check whether we should use optimal code alignment for this .align
2071 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2072 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2073 ValueSize == 1 && UseCodeAlign) {
2074 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2076 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2077 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2084 /// ParseDirectiveSymbolAttribute
2085 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2086 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2087 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2090 SMLoc Loc = getTok().getLoc();
2092 if (ParseIdentifier(Name))
2093 return Error(Loc, "expected identifier in directive");
2095 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2097 // Assembler local symbols don't make any sense here. Complain loudly.
2098 if (Sym->isTemporary())
2099 return Error(Loc, "non-local symbol required in directive");
2101 getStreamer().EmitSymbolAttribute(Sym, Attr);
2103 if (getLexer().is(AsmToken::EndOfStatement))
2106 if (getLexer().isNot(AsmToken::Comma))
2107 return TokError("unexpected token in directive");
2116 /// ParseDirectiveComm
2117 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2118 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2119 CheckForValidSection();
2121 SMLoc IDLoc = getLexer().getLoc();
2123 if (ParseIdentifier(Name))
2124 return TokError("expected identifier in directive");
2126 // Handle the identifier as the key symbol.
2127 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2129 if (getLexer().isNot(AsmToken::Comma))
2130 return TokError("unexpected token in directive");
2134 SMLoc SizeLoc = getLexer().getLoc();
2135 if (ParseAbsoluteExpression(Size))
2138 int64_t Pow2Alignment = 0;
2139 SMLoc Pow2AlignmentLoc;
2140 if (getLexer().is(AsmToken::Comma)) {
2142 Pow2AlignmentLoc = getLexer().getLoc();
2143 if (ParseAbsoluteExpression(Pow2Alignment))
2146 // If this target takes alignments in bytes (not log) validate and convert.
2147 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2148 if (!isPowerOf2_64(Pow2Alignment))
2149 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2150 Pow2Alignment = Log2_64(Pow2Alignment);
2154 if (getLexer().isNot(AsmToken::EndOfStatement))
2155 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2159 // NOTE: a size of zero for a .comm should create a undefined symbol
2160 // but a size of .lcomm creates a bss symbol of size zero.
2162 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2163 "be less than zero");
2165 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2166 // may internally end up wanting an alignment in bytes.
2167 // FIXME: Diagnose overflow.
2168 if (Pow2Alignment < 0)
2169 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2170 "alignment, can't be less than zero");
2172 if (!Sym->isUndefined())
2173 return Error(IDLoc, "invalid symbol redefinition");
2175 // '.lcomm' is equivalent to '.zerofill'.
2176 // Create the Symbol as a common or local common with Size and Pow2Alignment
2178 getStreamer().EmitZerofill(Ctx.getMachOSection(
2179 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2180 0, SectionKind::getBSS()),
2181 Sym, Size, 1 << Pow2Alignment);
2185 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2189 /// ParseDirectiveAbort
2190 /// ::= .abort [... message ...]
2191 bool AsmParser::ParseDirectiveAbort() {
2192 // FIXME: Use loc from directive.
2193 SMLoc Loc = getLexer().getLoc();
2195 StringRef Str = ParseStringToEndOfStatement();
2196 if (getLexer().isNot(AsmToken::EndOfStatement))
2197 return TokError("unexpected token in '.abort' directive");
2202 Error(Loc, ".abort detected. Assembly stopping.");
2204 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2205 // FIXME: Actually abort assembly here.
2210 /// ParseDirectiveInclude
2211 /// ::= .include "filename"
2212 bool AsmParser::ParseDirectiveInclude() {
2213 if (getLexer().isNot(AsmToken::String))
2214 return TokError("expected string in '.include' directive");
2216 std::string Filename = getTok().getString();
2217 SMLoc IncludeLoc = getLexer().getLoc();
2220 if (getLexer().isNot(AsmToken::EndOfStatement))
2221 return TokError("unexpected token in '.include' directive");
2223 // Strip the quotes.
2224 Filename = Filename.substr(1, Filename.size()-2);
2226 // Attempt to switch the lexer to the included file before consuming the end
2227 // of statement to avoid losing it when we switch.
2228 if (EnterIncludeFile(Filename)) {
2229 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2236 /// ParseDirectiveIncbin
2237 /// ::= .incbin "filename"
2238 bool AsmParser::ParseDirectiveIncbin() {
2239 if (getLexer().isNot(AsmToken::String))
2240 return TokError("expected string in '.incbin' directive");
2242 std::string Filename = getTok().getString();
2243 SMLoc IncbinLoc = getLexer().getLoc();
2246 if (getLexer().isNot(AsmToken::EndOfStatement))
2247 return TokError("unexpected token in '.incbin' directive");
2249 // Strip the quotes.
2250 Filename = Filename.substr(1, Filename.size()-2);
2252 // Attempt to process the included file.
2253 if (ProcessIncbinFile(Filename)) {
2254 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2261 /// ParseDirectiveIf
2262 /// ::= .if expression
2263 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2264 TheCondStack.push_back(TheCondState);
2265 TheCondState.TheCond = AsmCond::IfCond;
2266 if(TheCondState.Ignore) {
2267 EatToEndOfStatement();
2271 if (ParseAbsoluteExpression(ExprValue))
2274 if (getLexer().isNot(AsmToken::EndOfStatement))
2275 return TokError("unexpected token in '.if' directive");
2279 TheCondState.CondMet = ExprValue;
2280 TheCondState.Ignore = !TheCondState.CondMet;
2286 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2288 TheCondStack.push_back(TheCondState);
2289 TheCondState.TheCond = AsmCond::IfCond;
2291 if (TheCondState.Ignore) {
2292 EatToEndOfStatement();
2294 if (ParseIdentifier(Name))
2295 return TokError("expected identifier after '.ifdef'");
2299 MCSymbol *Sym = getContext().LookupSymbol(Name);
2302 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2304 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2305 TheCondState.Ignore = !TheCondState.CondMet;
2311 /// ParseDirectiveElseIf
2312 /// ::= .elseif expression
2313 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2314 if (TheCondState.TheCond != AsmCond::IfCond &&
2315 TheCondState.TheCond != AsmCond::ElseIfCond)
2316 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2318 TheCondState.TheCond = AsmCond::ElseIfCond;
2320 bool LastIgnoreState = false;
2321 if (!TheCondStack.empty())
2322 LastIgnoreState = TheCondStack.back().Ignore;
2323 if (LastIgnoreState || TheCondState.CondMet) {
2324 TheCondState.Ignore = true;
2325 EatToEndOfStatement();
2329 if (ParseAbsoluteExpression(ExprValue))
2332 if (getLexer().isNot(AsmToken::EndOfStatement))
2333 return TokError("unexpected token in '.elseif' directive");
2336 TheCondState.CondMet = ExprValue;
2337 TheCondState.Ignore = !TheCondState.CondMet;
2343 /// ParseDirectiveElse
2345 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2346 if (getLexer().isNot(AsmToken::EndOfStatement))
2347 return TokError("unexpected token in '.else' directive");
2351 if (TheCondState.TheCond != AsmCond::IfCond &&
2352 TheCondState.TheCond != AsmCond::ElseIfCond)
2353 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2355 TheCondState.TheCond = AsmCond::ElseCond;
2356 bool LastIgnoreState = false;
2357 if (!TheCondStack.empty())
2358 LastIgnoreState = TheCondStack.back().Ignore;
2359 if (LastIgnoreState || TheCondState.CondMet)
2360 TheCondState.Ignore = true;
2362 TheCondState.Ignore = false;
2367 /// ParseDirectiveEndIf
2369 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2370 if (getLexer().isNot(AsmToken::EndOfStatement))
2371 return TokError("unexpected token in '.endif' directive");
2375 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2376 TheCondStack.empty())
2377 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2379 if (!TheCondStack.empty()) {
2380 TheCondState = TheCondStack.back();
2381 TheCondStack.pop_back();
2387 /// ParseDirectiveFile
2388 /// ::= .file [number] filename
2389 /// ::= .file number directory filename
2390 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2391 // FIXME: I'm not sure what this is.
2392 int64_t FileNumber = -1;
2393 SMLoc FileNumberLoc = getLexer().getLoc();
2394 if (getLexer().is(AsmToken::Integer)) {
2395 FileNumber = getTok().getIntVal();
2399 return TokError("file number less than one");
2402 if (getLexer().isNot(AsmToken::String))
2403 return TokError("unexpected token in '.file' directive");
2405 // Usually the directory and filename together, otherwise just the directory.
2406 StringRef Path = getTok().getString();
2407 Path = Path.substr(1, Path.size()-2);
2410 StringRef Directory;
2412 if (getLexer().is(AsmToken::String)) {
2413 if (FileNumber == -1)
2414 return TokError("explicit path specified, but no file number");
2415 Filename = getTok().getString();
2416 Filename = Filename.substr(1, Filename.size()-2);
2423 if (getLexer().isNot(AsmToken::EndOfStatement))
2424 return TokError("unexpected token in '.file' directive");
2426 if (getContext().getGenDwarfForAssembly() == true)
2427 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2428 "used to generate dwarf debug info for assembly code");
2430 if (FileNumber == -1)
2431 getStreamer().EmitFileDirective(Filename);
2433 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2434 Error(FileNumberLoc, "file number already allocated");
2440 /// ParseDirectiveLine
2441 /// ::= .line [number]
2442 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2443 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2444 if (getLexer().isNot(AsmToken::Integer))
2445 return TokError("unexpected token in '.line' directive");
2447 int64_t LineNumber = getTok().getIntVal();
2451 // FIXME: Do something with the .line.
2454 if (getLexer().isNot(AsmToken::EndOfStatement))
2455 return TokError("unexpected token in '.line' directive");
2461 /// ParseDirectiveLoc
2462 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2463 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2464 /// The first number is a file number, must have been previously assigned with
2465 /// a .file directive, the second number is the line number and optionally the
2466 /// third number is a column position (zero if not specified). The remaining
2467 /// optional items are .loc sub-directives.
2468 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2470 if (getLexer().isNot(AsmToken::Integer))
2471 return TokError("unexpected token in '.loc' directive");
2472 int64_t FileNumber = getTok().getIntVal();
2474 return TokError("file number less than one in '.loc' directive");
2475 if (!getContext().isValidDwarfFileNumber(FileNumber))
2476 return TokError("unassigned file number in '.loc' directive");
2479 int64_t LineNumber = 0;
2480 if (getLexer().is(AsmToken::Integer)) {
2481 LineNumber = getTok().getIntVal();
2483 return TokError("line number less than one in '.loc' directive");
2487 int64_t ColumnPos = 0;
2488 if (getLexer().is(AsmToken::Integer)) {
2489 ColumnPos = getTok().getIntVal();
2491 return TokError("column position less than zero in '.loc' directive");
2495 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2497 int64_t Discriminator = 0;
2498 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2500 if (getLexer().is(AsmToken::EndOfStatement))
2504 SMLoc Loc = getTok().getLoc();
2505 if (getParser().ParseIdentifier(Name))
2506 return TokError("unexpected token in '.loc' directive");
2508 if (Name == "basic_block")
2509 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2510 else if (Name == "prologue_end")
2511 Flags |= DWARF2_FLAG_PROLOGUE_END;
2512 else if (Name == "epilogue_begin")
2513 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2514 else if (Name == "is_stmt") {
2515 SMLoc Loc = getTok().getLoc();
2516 const MCExpr *Value;
2517 if (getParser().ParseExpression(Value))
2519 // The expression must be the constant 0 or 1.
2520 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2521 int Value = MCE->getValue();
2523 Flags &= ~DWARF2_FLAG_IS_STMT;
2524 else if (Value == 1)
2525 Flags |= DWARF2_FLAG_IS_STMT;
2527 return Error(Loc, "is_stmt value not 0 or 1");
2530 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2533 else if (Name == "isa") {
2534 SMLoc Loc = getTok().getLoc();
2535 const MCExpr *Value;
2536 if (getParser().ParseExpression(Value))
2538 // The expression must be a constant greater or equal to 0.
2539 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2540 int Value = MCE->getValue();
2542 return Error(Loc, "isa number less than zero");
2546 return Error(Loc, "isa number not a constant value");
2549 else if (Name == "discriminator") {
2550 if (getParser().ParseAbsoluteExpression(Discriminator))
2554 return Error(Loc, "unknown sub-directive in '.loc' directive");
2557 if (getLexer().is(AsmToken::EndOfStatement))
2562 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2563 Isa, Discriminator, StringRef());
2568 /// ParseDirectiveStabs
2569 /// ::= .stabs string, number, number, number
2570 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2571 SMLoc DirectiveLoc) {
2572 return TokError("unsupported directive '" + Directive + "'");
2575 /// ParseDirectiveCFISections
2576 /// ::= .cfi_sections section [, section]
2577 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2578 SMLoc DirectiveLoc) {
2583 if (getParser().ParseIdentifier(Name))
2584 return TokError("Expected an identifier");
2586 if (Name == ".eh_frame")
2588 else if (Name == ".debug_frame")
2591 if (getLexer().is(AsmToken::Comma)) {
2594 if (getParser().ParseIdentifier(Name))
2595 return TokError("Expected an identifier");
2597 if (Name == ".eh_frame")
2599 else if (Name == ".debug_frame")
2603 getStreamer().EmitCFISections(EH, Debug);
2608 /// ParseDirectiveCFIStartProc
2609 /// ::= .cfi_startproc
2610 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2611 SMLoc DirectiveLoc) {
2612 getStreamer().EmitCFIStartProc();
2616 /// ParseDirectiveCFIEndProc
2617 /// ::= .cfi_endproc
2618 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2619 getStreamer().EmitCFIEndProc();
2623 /// ParseRegisterOrRegisterNumber - parse register name or number.
2624 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2625 SMLoc DirectiveLoc) {
2628 if (getLexer().isNot(AsmToken::Integer)) {
2629 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2632 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2634 return getParser().ParseAbsoluteExpression(Register);
2639 /// ParseDirectiveCFIDefCfa
2640 /// ::= .cfi_def_cfa register, offset
2641 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2642 SMLoc DirectiveLoc) {
2643 int64_t Register = 0;
2644 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2647 if (getLexer().isNot(AsmToken::Comma))
2648 return TokError("unexpected token in directive");
2652 if (getParser().ParseAbsoluteExpression(Offset))
2655 getStreamer().EmitCFIDefCfa(Register, Offset);
2659 /// ParseDirectiveCFIDefCfaOffset
2660 /// ::= .cfi_def_cfa_offset offset
2661 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2662 SMLoc DirectiveLoc) {
2664 if (getParser().ParseAbsoluteExpression(Offset))
2667 getStreamer().EmitCFIDefCfaOffset(Offset);
2671 /// ParseDirectiveCFIAdjustCfaOffset
2672 /// ::= .cfi_adjust_cfa_offset adjustment
2673 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2674 SMLoc DirectiveLoc) {
2675 int64_t Adjustment = 0;
2676 if (getParser().ParseAbsoluteExpression(Adjustment))
2679 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2683 /// ParseDirectiveCFIDefCfaRegister
2684 /// ::= .cfi_def_cfa_register register
2685 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2686 SMLoc DirectiveLoc) {
2687 int64_t Register = 0;
2688 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2691 getStreamer().EmitCFIDefCfaRegister(Register);
2695 /// ParseDirectiveCFIOffset
2696 /// ::= .cfi_offset register, offset
2697 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2698 int64_t Register = 0;
2701 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2704 if (getLexer().isNot(AsmToken::Comma))
2705 return TokError("unexpected token in directive");
2708 if (getParser().ParseAbsoluteExpression(Offset))
2711 getStreamer().EmitCFIOffset(Register, Offset);
2715 /// ParseDirectiveCFIRelOffset
2716 /// ::= .cfi_rel_offset register, offset
2717 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2718 SMLoc DirectiveLoc) {
2719 int64_t Register = 0;
2721 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2724 if (getLexer().isNot(AsmToken::Comma))
2725 return TokError("unexpected token in directive");
2729 if (getParser().ParseAbsoluteExpression(Offset))
2732 getStreamer().EmitCFIRelOffset(Register, Offset);
2736 static bool isValidEncoding(int64_t Encoding) {
2737 if (Encoding & ~0xff)
2740 if (Encoding == dwarf::DW_EH_PE_omit)
2743 const unsigned Format = Encoding & 0xf;
2744 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2745 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2746 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2747 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2750 const unsigned Application = Encoding & 0x70;
2751 if (Application != dwarf::DW_EH_PE_absptr &&
2752 Application != dwarf::DW_EH_PE_pcrel)
2758 /// ParseDirectiveCFIPersonalityOrLsda
2759 /// ::= .cfi_personality encoding, [symbol_name]
2760 /// ::= .cfi_lsda encoding, [symbol_name]
2761 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2762 SMLoc DirectiveLoc) {
2763 int64_t Encoding = 0;
2764 if (getParser().ParseAbsoluteExpression(Encoding))
2766 if (Encoding == dwarf::DW_EH_PE_omit)
2769 if (!isValidEncoding(Encoding))
2770 return TokError("unsupported encoding.");
2772 if (getLexer().isNot(AsmToken::Comma))
2773 return TokError("unexpected token in directive");
2777 if (getParser().ParseIdentifier(Name))
2778 return TokError("expected identifier in directive");
2780 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2782 if (IDVal == ".cfi_personality")
2783 getStreamer().EmitCFIPersonality(Sym, Encoding);
2785 assert(IDVal == ".cfi_lsda");
2786 getStreamer().EmitCFILsda(Sym, Encoding);
2791 /// ParseDirectiveCFIRememberState
2792 /// ::= .cfi_remember_state
2793 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2794 SMLoc DirectiveLoc) {
2795 getStreamer().EmitCFIRememberState();
2799 /// ParseDirectiveCFIRestoreState
2800 /// ::= .cfi_remember_state
2801 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2802 SMLoc DirectiveLoc) {
2803 getStreamer().EmitCFIRestoreState();
2807 /// ParseDirectiveCFISameValue
2808 /// ::= .cfi_same_value register
2809 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2810 SMLoc DirectiveLoc) {
2811 int64_t Register = 0;
2813 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2816 getStreamer().EmitCFISameValue(Register);
2821 /// ParseDirectiveCFIRestore
2822 /// ::= .cfi_restore register
2823 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2824 SMLoc DirectiveLoc) {
2825 int64_t Register = 0;
2826 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2829 getStreamer().EmitCFIRestore(Register);
2834 /// ParseDirectiveCFIEscape
2835 /// ::= .cfi_escape expression[,...]
2836 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2837 SMLoc DirectiveLoc) {
2840 if (getParser().ParseAbsoluteExpression(CurrValue))
2843 Values.push_back((uint8_t)CurrValue);
2845 while (getLexer().is(AsmToken::Comma)) {
2848 if (getParser().ParseAbsoluteExpression(CurrValue))
2851 Values.push_back((uint8_t)CurrValue);
2854 getStreamer().EmitCFIEscape(Values);
2858 /// ParseDirectiveMacrosOnOff
2861 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2862 SMLoc DirectiveLoc) {
2863 if (getLexer().isNot(AsmToken::EndOfStatement))
2864 return Error(getLexer().getLoc(),
2865 "unexpected token in '" + Directive + "' directive");
2867 getParser().MacrosEnabled = Directive == ".macros_on";
2872 /// ParseDirectiveMacro
2873 /// ::= .macro name [parameters]
2874 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2875 SMLoc DirectiveLoc) {
2877 if (getParser().ParseIdentifier(Name))
2878 return TokError("expected identifier in directive");
2880 std::vector<StringRef> Parameters;
2881 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2883 StringRef Parameter;
2884 if (getParser().ParseIdentifier(Parameter))
2885 return TokError("expected identifier in directive");
2886 Parameters.push_back(Parameter);
2888 if (getLexer().isNot(AsmToken::Comma))
2894 if (getLexer().isNot(AsmToken::EndOfStatement))
2895 return TokError("unexpected token in '.macro' directive");
2897 // Eat the end of statement.
2900 AsmToken EndToken, StartToken = getTok();
2902 // Lex the macro definition.
2904 // Check whether we have reached the end of the file.
2905 if (getLexer().is(AsmToken::Eof))
2906 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2908 // Otherwise, check whether we have reach the .endmacro.
2909 if (getLexer().is(AsmToken::Identifier) &&
2910 (getTok().getIdentifier() == ".endm" ||
2911 getTok().getIdentifier() == ".endmacro")) {
2912 EndToken = getTok();
2914 if (getLexer().isNot(AsmToken::EndOfStatement))
2915 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2920 // Otherwise, scan til the end of the statement.
2921 getParser().EatToEndOfStatement();
2924 if (getParser().MacroMap.lookup(Name)) {
2925 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2928 const char *BodyStart = StartToken.getLoc().getPointer();
2929 const char *BodyEnd = EndToken.getLoc().getPointer();
2930 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2931 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2935 /// ParseDirectiveEndMacro
2938 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2939 SMLoc DirectiveLoc) {
2940 if (getLexer().isNot(AsmToken::EndOfStatement))
2941 return TokError("unexpected token in '" + Directive + "' directive");
2943 // If we are inside a macro instantiation, terminate the current
2945 if (!getParser().ActiveMacros.empty()) {
2946 getParser().HandleMacroExit();
2950 // Otherwise, this .endmacro is a stray entry in the file; well formed
2951 // .endmacro directives are handled during the macro definition parsing.
2952 return TokError("unexpected '" + Directive + "' in file, "
2953 "no current macro definition");
2956 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2957 getParser().CheckForValidSection();
2959 const MCExpr *Value;
2961 if (getParser().ParseExpression(Value))
2964 if (getLexer().isNot(AsmToken::EndOfStatement))
2965 return TokError("unexpected token in directive");
2967 if (DirName[1] == 's')
2968 getStreamer().EmitSLEB128Value(Value);
2970 getStreamer().EmitULEB128Value(Value);
2976 /// \brief Create an MCAsmParser instance.
2977 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
2978 MCContext &C, MCStreamer &Out,
2979 const MCAsmInfo &MAI) {
2980 return new AsmParser(SM, C, Out, MAI);