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 MCAsmParserExtension *GenericParser;
91 MCAsmParserExtension *PlatformParser;
93 /// This is the current buffer index we're lexing from as managed by the
98 std::vector<AsmCond> TheCondStack;
100 /// DirectiveMap - This is a table handlers for directives. Each handler is
101 /// invoked after the directive identifier is read and is responsible for
102 /// parsing and validating the rest of the directive. The handler is passed
103 /// in the directive name and the location of the directive keyword.
104 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
106 /// MacroMap - Map of currently defined macros.
107 StringMap<Macro*> MacroMap;
109 /// ActiveMacros - Stack of active macro instantiations.
110 std::vector<MacroInstantiation*> ActiveMacros;
112 /// Boolean tracking whether macro substitution is enabled.
113 unsigned MacrosEnabled : 1;
115 /// Flag tracking whether any errors have been encountered.
116 unsigned HadError : 1;
118 /// The values from the last parsed cpp hash file line comment if any.
119 StringRef CppHashFilename;
120 int64_t CppHashLineNumber;
124 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
125 const MCAsmInfo &MAI);
128 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
130 void AddDirectiveHandler(MCAsmParserExtension *Object,
132 DirectiveHandler Handler) {
133 DirectiveMap[Directive] = std::make_pair(Object, Handler);
137 /// @name MCAsmParser Interface
140 virtual SourceMgr &getSourceManager() { return SrcMgr; }
141 virtual MCAsmLexer &getLexer() { return Lexer; }
142 virtual MCContext &getContext() { return Ctx; }
143 virtual MCStreamer &getStreamer() { return Out; }
145 virtual bool Warning(SMLoc L, const Twine &Msg);
146 virtual bool Error(SMLoc L, const Twine &Msg);
148 const AsmToken &Lex();
150 bool ParseExpression(const MCExpr *&Res);
151 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
152 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
153 virtual bool ParseAbsoluteExpression(int64_t &Res);
158 void CheckForValidSection();
160 bool ParseStatement();
161 void EatToEndOfLine();
162 bool ParseCppHashLineFilenameComment(const SMLoc &L);
164 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
165 bool expandMacro(SmallString<256> &Buf, StringRef Body,
166 const std::vector<StringRef> &Parameters,
167 const std::vector<std::vector<AsmToken> > &A,
169 void HandleMacroExit();
171 void PrintMacroInstantiations();
172 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type,
173 bool ShowLine = true) const {
174 SrcMgr.PrintMessage(Loc, Msg, Type, ShowLine);
176 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
178 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
179 bool EnterIncludeFile(const std::string &Filename);
181 /// \brief Reset the current lexer position to that given by \arg Loc. The
182 /// current token is not set; clients should ensure Lex() is called
184 void JumpToLoc(SMLoc Loc);
186 void EatToEndOfStatement();
188 /// \brief Parse up to the end of statement and a return the contents from the
189 /// current token until the end of the statement; the current token on exit
190 /// will be either the EndOfStatement or EOF.
191 StringRef ParseStringToEndOfStatement();
193 bool ParseAssignment(StringRef Name, bool allow_redef);
195 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
196 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
197 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
198 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
200 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
201 /// and set \arg Res to the identifier contents.
202 bool ParseIdentifier(StringRef &Res);
204 // Directive Parsing.
206 // ".ascii", ".asciiz", ".string"
207 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
208 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
209 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
210 bool ParseDirectiveFill(); // ".fill"
211 bool ParseDirectiveSpace(); // ".space"
212 bool ParseDirectiveZero(); // ".zero"
213 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
214 bool ParseDirectiveOrg(); // ".org"
215 // ".align{,32}", ".p2align{,w,l}"
216 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
218 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
219 /// accepts a single symbol (which should be a label or an external).
220 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
222 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
224 bool ParseDirectiveAbort(); // ".abort"
225 bool ParseDirectiveInclude(); // ".include"
227 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
228 // ".ifdef" or ".ifndef", depending on expect_defined
229 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
230 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
231 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
232 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
234 /// ParseEscapedString - Parse the current token as a string which may include
235 /// escaped characters and return the string contents.
236 bool ParseEscapedString(std::string &Data);
238 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
239 MCSymbolRefExpr::VariantKind Variant);
242 /// \brief Generic implementations of directive handling, etc. which is shared
243 /// (or the default, at least) for all assembler parser.
244 class GenericAsmParser : public MCAsmParserExtension {
245 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
246 void AddDirectiveHandler(StringRef Directive) {
247 getParser().AddDirectiveHandler(this, Directive,
248 HandleDirective<GenericAsmParser, Handler>);
251 GenericAsmParser() {}
253 AsmParser &getParser() {
254 return (AsmParser&) this->MCAsmParserExtension::getParser();
257 virtual void Initialize(MCAsmParser &Parser) {
258 // Call the base implementation.
259 this->MCAsmParserExtension::Initialize(Parser);
261 // Debugging directives.
262 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
263 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
264 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
265 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
268 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
277 ".cfi_def_cfa_offset");
278 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
279 ".cfi_adjust_cfa_offset");
280 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
281 ".cfi_def_cfa_register");
282 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
287 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
289 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
291 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
293 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
295 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
298 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
300 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
302 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
303 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
307 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
310 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
312 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
313 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
314 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
315 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
316 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
317 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
318 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
319 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
320 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
321 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
322 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
323 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
324 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
325 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
326 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
327 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
328 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
330 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
331 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
332 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
334 bool ParseDirectiveLEB128(StringRef, SMLoc);
341 extern MCAsmParserExtension *createDarwinAsmParser();
342 extern MCAsmParserExtension *createELFAsmParser();
343 extern MCAsmParserExtension *createCOFFAsmParser();
347 enum { DEFAULT_ADDRSPACE = 0 };
349 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
350 MCStreamer &_Out, const MCAsmInfo &_MAI)
351 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
352 GenericParser(new GenericAsmParser), PlatformParser(0),
353 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0) {
354 SrcMgr.setDiagHandler(DiagHandler, this);
355 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
357 // Initialize the generic parser.
358 GenericParser->Initialize(*this);
360 // Initialize the platform / file format parser.
362 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
364 if (_MAI.hasMicrosoftFastStdCallMangling()) {
365 PlatformParser = createCOFFAsmParser();
366 PlatformParser->Initialize(*this);
367 } else if (_MAI.hasSubsectionsViaSymbols()) {
368 PlatformParser = createDarwinAsmParser();
369 PlatformParser->Initialize(*this);
371 PlatformParser = createELFAsmParser();
372 PlatformParser->Initialize(*this);
376 AsmParser::~AsmParser() {
377 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
379 // Destroy any macros.
380 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
381 ie = MacroMap.end(); it != ie; ++it)
382 delete it->getValue();
384 delete PlatformParser;
385 delete GenericParser;
388 void AsmParser::PrintMacroInstantiations() {
389 // Print the active macro instantiation stack.
390 for (std::vector<MacroInstantiation*>::const_reverse_iterator
391 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
392 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
396 bool AsmParser::Warning(SMLoc L, const Twine &Msg) {
397 if (FatalAssemblerWarnings)
398 return Error(L, Msg);
399 PrintMessage(L, Msg, "warning");
400 PrintMacroInstantiations();
404 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
406 PrintMessage(L, Msg, "error");
407 PrintMacroInstantiations();
411 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
412 std::string IncludedFile;
413 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
419 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
424 void AsmParser::JumpToLoc(SMLoc Loc) {
425 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
426 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
429 const AsmToken &AsmParser::Lex() {
430 const AsmToken *tok = &Lexer.Lex();
432 if (tok->is(AsmToken::Eof)) {
433 // If this is the end of an included file, pop the parent file off the
435 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
436 if (ParentIncludeLoc != SMLoc()) {
437 JumpToLoc(ParentIncludeLoc);
442 if (tok->is(AsmToken::Error))
443 Error(Lexer.getErrLoc(), Lexer.getErr());
448 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
449 // Create the initial section, if requested.
450 if (!NoInitialTextSection)
457 AsmCond StartingCondState = TheCondState;
459 // While we have input, parse each statement.
460 while (Lexer.isNot(AsmToken::Eof)) {
461 if (!ParseStatement()) continue;
463 // We had an error, validate that one was emitted and recover by skipping to
465 assert(HadError && "Parse statement returned an error, but none emitted!");
466 EatToEndOfStatement();
469 if (TheCondState.TheCond != StartingCondState.TheCond ||
470 TheCondState.Ignore != StartingCondState.Ignore)
471 return TokError("unmatched .ifs or .elses");
473 // Check to see there are no empty DwarfFile slots.
474 const std::vector<MCDwarfFile *> &MCDwarfFiles =
475 getContext().getMCDwarfFiles();
476 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
477 if (!MCDwarfFiles[i])
478 TokError("unassigned file number: " + Twine(i) + " for .file directives");
481 // Check to see that all assembler local symbols were actually defined.
482 // Targets that don't do subsections via symbols may not want this, though,
483 // so conservatively exclude them. Only do this if we're finalizing, though,
484 // as otherwise we won't necessarilly have seen everything yet.
485 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
486 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
487 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
490 MCSymbol *Sym = i->getValue();
491 // Variable symbols may not be marked as defined, so check those
492 // explicitly. If we know it's a variable, we have a definition for
493 // the purposes of this check.
494 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
495 // FIXME: We would really like to refer back to where the symbol was
496 // first referenced for a source location. We need to add something
497 // to track that. Currently, we just point to the end of the file.
498 PrintMessage(getLexer().getLoc(), "assembler local symbol '" +
499 Sym->getName() + "' not defined", "error", false);
504 // Finalize the output stream if there are no errors and if the client wants
506 if (!HadError && !NoFinalize)
512 void AsmParser::CheckForValidSection() {
513 if (!getStreamer().getCurrentSection()) {
514 TokError("expected section directive before assembly directive");
515 Out.SwitchSection(Ctx.getMachOSection(
517 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
518 0, SectionKind::getText()));
522 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
523 void AsmParser::EatToEndOfStatement() {
524 while (Lexer.isNot(AsmToken::EndOfStatement) &&
525 Lexer.isNot(AsmToken::Eof))
529 if (Lexer.is(AsmToken::EndOfStatement))
533 StringRef AsmParser::ParseStringToEndOfStatement() {
534 const char *Start = getTok().getLoc().getPointer();
536 while (Lexer.isNot(AsmToken::EndOfStatement) &&
537 Lexer.isNot(AsmToken::Eof))
540 const char *End = getTok().getLoc().getPointer();
541 return StringRef(Start, End - Start);
544 /// ParseParenExpr - Parse a paren expression and return it.
545 /// NOTE: This assumes the leading '(' has already been consumed.
547 /// parenexpr ::= expr)
549 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
550 if (ParseExpression(Res)) return true;
551 if (Lexer.isNot(AsmToken::RParen))
552 return TokError("expected ')' in parentheses expression");
553 EndLoc = Lexer.getLoc();
558 /// ParseBracketExpr - Parse a bracket expression and return it.
559 /// NOTE: This assumes the leading '[' has already been consumed.
561 /// bracketexpr ::= expr]
563 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
564 if (ParseExpression(Res)) return true;
565 if (Lexer.isNot(AsmToken::RBrac))
566 return TokError("expected ']' in brackets expression");
567 EndLoc = Lexer.getLoc();
572 /// ParsePrimaryExpr - Parse a primary expression and return it.
573 /// primaryexpr ::= (parenexpr
574 /// primaryexpr ::= symbol
575 /// primaryexpr ::= number
576 /// primaryexpr ::= '.'
577 /// primaryexpr ::= ~,+,- primaryexpr
578 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
579 switch (Lexer.getKind()) {
581 return TokError("unknown token in expression");
582 // If we have an error assume that we've already handled it.
583 case AsmToken::Error:
585 case AsmToken::Exclaim:
586 Lex(); // Eat the operator.
587 if (ParsePrimaryExpr(Res, EndLoc))
589 Res = MCUnaryExpr::CreateLNot(Res, getContext());
591 case AsmToken::Dollar:
592 case AsmToken::String:
593 case AsmToken::Identifier: {
594 EndLoc = Lexer.getLoc();
596 StringRef Identifier;
597 if (ParseIdentifier(Identifier))
600 // This is a symbol reference.
601 std::pair<StringRef, StringRef> Split = Identifier.split('@');
602 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
604 // Lookup the symbol variant if used.
605 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
606 if (Split.first.size() != Identifier.size()) {
607 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
608 if (Variant == MCSymbolRefExpr::VK_Invalid) {
609 Variant = MCSymbolRefExpr::VK_None;
610 return TokError("invalid variant '" + Split.second + "'");
614 // If this is an absolute variable reference, substitute it now to preserve
615 // semantics in the face of reassignment.
616 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
618 return Error(EndLoc, "unexpected modifier on variable reference");
620 Res = Sym->getVariableValue();
624 // Otherwise create a symbol ref.
625 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
628 case AsmToken::Integer: {
629 SMLoc Loc = getTok().getLoc();
630 int64_t IntVal = getTok().getIntVal();
631 Res = MCConstantExpr::Create(IntVal, getContext());
632 EndLoc = Lexer.getLoc();
634 // Look for 'b' or 'f' following an Integer as a directional label
635 if (Lexer.getKind() == AsmToken::Identifier) {
636 StringRef IDVal = getTok().getString();
637 if (IDVal == "f" || IDVal == "b"){
638 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
639 IDVal == "f" ? 1 : 0);
640 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
642 if(IDVal == "b" && Sym->isUndefined())
643 return Error(Loc, "invalid reference to undefined symbol");
644 EndLoc = Lexer.getLoc();
645 Lex(); // Eat identifier.
650 case AsmToken::Real: {
651 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
652 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
653 Res = MCConstantExpr::Create(IntVal, getContext());
657 case AsmToken::Dot: {
658 // This is a '.' reference, which references the current PC. Emit a
659 // temporary label to the streamer and refer to it.
660 MCSymbol *Sym = Ctx.CreateTempSymbol();
662 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
663 EndLoc = Lexer.getLoc();
664 Lex(); // Eat identifier.
667 case AsmToken::LParen:
668 Lex(); // Eat the '('.
669 return ParseParenExpr(Res, EndLoc);
670 case AsmToken::LBrac:
671 if (!PlatformParser->HasBracketExpressions())
672 return TokError("brackets expression not supported on this target");
673 Lex(); // Eat the '['.
674 return ParseBracketExpr(Res, EndLoc);
675 case AsmToken::Minus:
676 Lex(); // Eat the operator.
677 if (ParsePrimaryExpr(Res, EndLoc))
679 Res = MCUnaryExpr::CreateMinus(Res, getContext());
682 Lex(); // Eat the operator.
683 if (ParsePrimaryExpr(Res, EndLoc))
685 Res = MCUnaryExpr::CreatePlus(Res, getContext());
687 case AsmToken::Tilde:
688 Lex(); // Eat the operator.
689 if (ParsePrimaryExpr(Res, EndLoc))
691 Res = MCUnaryExpr::CreateNot(Res, getContext());
696 bool AsmParser::ParseExpression(const MCExpr *&Res) {
698 return ParseExpression(Res, EndLoc);
702 AsmParser::ApplyModifierToExpr(const MCExpr *E,
703 MCSymbolRefExpr::VariantKind Variant) {
704 // Recurse over the given expression, rebuilding it to apply the given variant
705 // if there is exactly one symbol.
706 switch (E->getKind()) {
708 case MCExpr::Constant:
711 case MCExpr::SymbolRef: {
712 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
714 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
715 TokError("invalid variant on expression '" +
716 getTok().getIdentifier() + "' (already modified)");
720 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
723 case MCExpr::Unary: {
724 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
725 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
728 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
731 case MCExpr::Binary: {
732 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
733 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
734 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
739 if (!LHS) LHS = BE->getLHS();
740 if (!RHS) RHS = BE->getRHS();
742 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
746 assert(0 && "Invalid expression kind!");
750 /// ParseExpression - Parse an expression and return it.
752 /// expr ::= expr &&,|| expr -> lowest.
753 /// expr ::= expr |,^,&,! expr
754 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
755 /// expr ::= expr <<,>> expr
756 /// expr ::= expr +,- expr
757 /// expr ::= expr *,/,% expr -> highest.
758 /// expr ::= primaryexpr
760 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
761 // Parse the expression.
763 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
766 // As a special case, we support 'a op b @ modifier' by rewriting the
767 // expression to include the modifier. This is inefficient, but in general we
768 // expect users to use 'a@modifier op b'.
769 if (Lexer.getKind() == AsmToken::At) {
772 if (Lexer.isNot(AsmToken::Identifier))
773 return TokError("unexpected symbol modifier following '@'");
775 MCSymbolRefExpr::VariantKind Variant =
776 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
777 if (Variant == MCSymbolRefExpr::VK_Invalid)
778 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
780 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
782 return TokError("invalid modifier '" + getTok().getIdentifier() +
783 "' (no symbols present)");
791 // Try to constant fold it up front, if possible.
793 if (Res->EvaluateAsAbsolute(Value))
794 Res = MCConstantExpr::Create(Value, getContext());
799 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
801 return ParseParenExpr(Res, EndLoc) ||
802 ParseBinOpRHS(1, Res, EndLoc);
805 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
808 SMLoc StartLoc = Lexer.getLoc();
809 if (ParseExpression(Expr))
812 if (!Expr->EvaluateAsAbsolute(Res))
813 return Error(StartLoc, "expected absolute expression");
818 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
819 MCBinaryExpr::Opcode &Kind) {
822 return 0; // not a binop.
824 // Lowest Precedence: &&, ||
825 case AsmToken::AmpAmp:
826 Kind = MCBinaryExpr::LAnd;
828 case AsmToken::PipePipe:
829 Kind = MCBinaryExpr::LOr;
833 // Low Precedence: |, &, ^
835 // FIXME: gas seems to support '!' as an infix operator?
837 Kind = MCBinaryExpr::Or;
839 case AsmToken::Caret:
840 Kind = MCBinaryExpr::Xor;
843 Kind = MCBinaryExpr::And;
846 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
847 case AsmToken::EqualEqual:
848 Kind = MCBinaryExpr::EQ;
850 case AsmToken::ExclaimEqual:
851 case AsmToken::LessGreater:
852 Kind = MCBinaryExpr::NE;
855 Kind = MCBinaryExpr::LT;
857 case AsmToken::LessEqual:
858 Kind = MCBinaryExpr::LTE;
860 case AsmToken::Greater:
861 Kind = MCBinaryExpr::GT;
863 case AsmToken::GreaterEqual:
864 Kind = MCBinaryExpr::GTE;
867 // Intermediate Precedence: <<, >>
868 case AsmToken::LessLess:
869 Kind = MCBinaryExpr::Shl;
871 case AsmToken::GreaterGreater:
872 Kind = MCBinaryExpr::Shr;
875 // High Intermediate Precedence: +, -
877 Kind = MCBinaryExpr::Add;
879 case AsmToken::Minus:
880 Kind = MCBinaryExpr::Sub;
883 // Highest Precedence: *, /, %
885 Kind = MCBinaryExpr::Mul;
887 case AsmToken::Slash:
888 Kind = MCBinaryExpr::Div;
890 case AsmToken::Percent:
891 Kind = MCBinaryExpr::Mod;
897 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
898 /// Res contains the LHS of the expression on input.
899 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
902 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
903 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
905 // If the next token is lower precedence than we are allowed to eat, return
906 // successfully with what we ate already.
907 if (TokPrec < Precedence)
912 // Eat the next primary expression.
914 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
916 // If BinOp binds less tightly with RHS than the operator after RHS, let
917 // the pending operator take RHS as its LHS.
918 MCBinaryExpr::Opcode Dummy;
919 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
920 if (TokPrec < NextTokPrec) {
921 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
924 // Merge LHS and RHS according to operator.
925 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
933 /// ::= EndOfStatement
934 /// ::= Label* Directive ...Operands... EndOfStatement
935 /// ::= Label* Identifier OperandList* EndOfStatement
936 bool AsmParser::ParseStatement() {
937 if (Lexer.is(AsmToken::EndOfStatement)) {
943 // Statements always start with an identifier or are a full line comment.
944 AsmToken ID = getTok();
945 SMLoc IDLoc = ID.getLoc();
947 int64_t LocalLabelVal = -1;
948 // A full line comment is a '#' as the first token.
949 if (Lexer.is(AsmToken::Hash))
950 return ParseCppHashLineFilenameComment(IDLoc);
952 // Allow an integer followed by a ':' as a directional local label.
953 if (Lexer.is(AsmToken::Integer)) {
954 LocalLabelVal = getTok().getIntVal();
955 if (LocalLabelVal < 0) {
956 if (!TheCondState.Ignore)
957 return TokError("unexpected token at start of statement");
961 IDVal = getTok().getString();
962 Lex(); // Consume the integer token to be used as an identifier token.
963 if (Lexer.getKind() != AsmToken::Colon) {
964 if (!TheCondState.Ignore)
965 return TokError("unexpected token at start of statement");
969 } else if (Lexer.is(AsmToken::Dot)) {
970 // Treat '.' as a valid identifier in this context.
974 } else if (ParseIdentifier(IDVal)) {
975 if (!TheCondState.Ignore)
976 return TokError("unexpected token at start of statement");
981 // Handle conditional assembly here before checking for skipping. We
982 // have to do this so that .endif isn't skipped in a ".if 0" block for
985 return ParseDirectiveIf(IDLoc);
986 if (IDVal == ".ifdef")
987 return ParseDirectiveIfdef(IDLoc, true);
988 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
989 return ParseDirectiveIfdef(IDLoc, false);
990 if (IDVal == ".elseif")
991 return ParseDirectiveElseIf(IDLoc);
992 if (IDVal == ".else")
993 return ParseDirectiveElse(IDLoc);
994 if (IDVal == ".endif")
995 return ParseDirectiveEndIf(IDLoc);
997 // If we are in a ".if 0" block, ignore this statement.
998 if (TheCondState.Ignore) {
999 EatToEndOfStatement();
1003 // FIXME: Recurse on local labels?
1005 // See what kind of statement we have.
1006 switch (Lexer.getKind()) {
1007 case AsmToken::Colon: {
1008 CheckForValidSection();
1010 // identifier ':' -> Label.
1013 // Diagnose attempt to use '.' as a label.
1015 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1017 // Diagnose attempt to use a variable as a label.
1019 // FIXME: Diagnostics. Note the location of the definition as a label.
1020 // FIXME: This doesn't diagnose assignment to a symbol which has been
1021 // implicitly marked as external.
1023 if (LocalLabelVal == -1)
1024 Sym = getContext().GetOrCreateSymbol(IDVal);
1026 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1027 if (!Sym->isUndefined() || Sym->isVariable())
1028 return Error(IDLoc, "invalid symbol redefinition");
1033 // Consume any end of statement token, if present, to avoid spurious
1034 // AddBlankLine calls().
1035 if (Lexer.is(AsmToken::EndOfStatement)) {
1037 if (Lexer.is(AsmToken::Eof))
1041 return ParseStatement();
1044 case AsmToken::Equal:
1045 // identifier '=' ... -> assignment statement
1048 return ParseAssignment(IDVal, true);
1050 default: // Normal instruction or directive.
1054 // If macros are enabled, check to see if this is a macro instantiation.
1056 if (const Macro *M = MacroMap.lookup(IDVal))
1057 return HandleMacroEntry(IDVal, IDLoc, M);
1059 // Otherwise, we have a normal instruction or directive.
1060 if (IDVal[0] == '.' && IDVal != ".") {
1061 // Assembler features
1062 if (IDVal == ".set" || IDVal == ".equ")
1063 return ParseDirectiveSet(IDVal, true);
1064 if (IDVal == ".equiv")
1065 return ParseDirectiveSet(IDVal, false);
1069 if (IDVal == ".ascii")
1070 return ParseDirectiveAscii(IDVal, false);
1071 if (IDVal == ".asciz" || IDVal == ".string")
1072 return ParseDirectiveAscii(IDVal, true);
1074 if (IDVal == ".byte")
1075 return ParseDirectiveValue(1);
1076 if (IDVal == ".short")
1077 return ParseDirectiveValue(2);
1078 if (IDVal == ".value")
1079 return ParseDirectiveValue(2);
1080 if (IDVal == ".2byte")
1081 return ParseDirectiveValue(2);
1082 if (IDVal == ".long")
1083 return ParseDirectiveValue(4);
1084 if (IDVal == ".int")
1085 return ParseDirectiveValue(4);
1086 if (IDVal == ".4byte")
1087 return ParseDirectiveValue(4);
1088 if (IDVal == ".quad")
1089 return ParseDirectiveValue(8);
1090 if (IDVal == ".8byte")
1091 return ParseDirectiveValue(8);
1092 if (IDVal == ".single" || IDVal == ".float")
1093 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1094 if (IDVal == ".double")
1095 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1097 if (IDVal == ".align") {
1098 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1099 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1101 if (IDVal == ".align32") {
1102 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1103 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1105 if (IDVal == ".balign")
1106 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1107 if (IDVal == ".balignw")
1108 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1109 if (IDVal == ".balignl")
1110 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1111 if (IDVal == ".p2align")
1112 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1113 if (IDVal == ".p2alignw")
1114 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1115 if (IDVal == ".p2alignl")
1116 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1118 if (IDVal == ".org")
1119 return ParseDirectiveOrg();
1121 if (IDVal == ".fill")
1122 return ParseDirectiveFill();
1123 if (IDVal == ".space" || IDVal == ".skip")
1124 return ParseDirectiveSpace();
1125 if (IDVal == ".zero")
1126 return ParseDirectiveZero();
1128 // Symbol attribute directives
1130 if (IDVal == ".globl" || IDVal == ".global")
1131 return ParseDirectiveSymbolAttribute(MCSA_Global);
1132 if (IDVal == ".indirect_symbol")
1133 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1134 if (IDVal == ".lazy_reference")
1135 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1136 if (IDVal == ".no_dead_strip")
1137 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1138 if (IDVal == ".symbol_resolver")
1139 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1140 if (IDVal == ".private_extern")
1141 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1142 if (IDVal == ".reference")
1143 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1144 if (IDVal == ".weak_definition")
1145 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1146 if (IDVal == ".weak_reference")
1147 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1148 if (IDVal == ".weak_def_can_be_hidden")
1149 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1151 if (IDVal == ".comm" || IDVal == ".common")
1152 return ParseDirectiveComm(/*IsLocal=*/false);
1153 if (IDVal == ".lcomm")
1154 return ParseDirectiveComm(/*IsLocal=*/true);
1156 if (IDVal == ".abort")
1157 return ParseDirectiveAbort();
1158 if (IDVal == ".include")
1159 return ParseDirectiveInclude();
1161 if (IDVal == ".code16")
1162 return TokError(Twine(IDVal) + " not supported yet");
1164 // Look up the handler in the handler table.
1165 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1166 DirectiveMap.lookup(IDVal);
1168 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1170 // Target hook for parsing target specific directives.
1171 if (!getTargetParser().ParseDirective(ID))
1174 bool retval = Warning(IDLoc, "ignoring directive for now");
1175 EatToEndOfStatement();
1179 CheckForValidSection();
1181 // Canonicalize the opcode to lower case.
1182 SmallString<128> Opcode;
1183 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1184 Opcode.push_back(tolower(IDVal[i]));
1186 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1187 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1190 // Dump the parsed representation, if requested.
1191 if (getShowParsedOperands()) {
1192 SmallString<256> Str;
1193 raw_svector_ostream OS(Str);
1194 OS << "parsed instruction: [";
1195 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1198 ParsedOperands[i]->print(OS);
1202 PrintMessage(IDLoc, OS.str(), "note");
1205 // If parsing succeeded, match the instruction.
1207 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1210 // Free any parsed operands.
1211 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1212 delete ParsedOperands[i];
1214 // Don't skip the rest of the line, the instruction parser is responsible for
1219 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1220 /// since they may not be able to be tokenized to get to the end of line token.
1221 void AsmParser::EatToEndOfLine() {
1222 Lexer.LexUntilEndOfLine();
1227 /// ParseCppHashLineFilenameComment as this:
1228 /// ::= # number "filename"
1229 /// or just as a full line comment if it doesn't have a number and a string.
1230 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1231 Lex(); // Eat the hash token.
1233 if (getLexer().isNot(AsmToken::Integer)) {
1234 // Consume the line since in cases it is not a well-formed line directive,
1235 // as if were simply a full line comment.
1240 int64_t LineNumber = getTok().getIntVal();
1243 if (getLexer().isNot(AsmToken::String)) {
1248 StringRef Filename = getTok().getString();
1249 // Get rid of the enclosing quotes.
1250 Filename = Filename.substr(1, Filename.size()-2);
1252 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1254 CppHashFilename = Filename;
1255 CppHashLineNumber = LineNumber;
1257 // Ignore any trailing characters, they're just comment.
1262 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1263 /// for the Filename and LineNo if any in the diagnostic.
1264 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1265 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1266 raw_ostream &OS = errs();
1268 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1269 const SMLoc &DiagLoc = Diag.getLoc();
1270 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1271 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1273 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1274 // before printing the message.
1275 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1276 if (DiagCurBuffer > 0) {
1277 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1278 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1281 // If we have not parsed a cpp hash line filename comment or the source
1282 // manager changed or buffer changed (like in a nested include) then just
1283 // print the normal diagnostic using its Filename and LineNo.
1284 if (!Parser->CppHashLineNumber ||
1285 &DiagSrcMgr != &Parser->SrcMgr ||
1286 DiagBuf != CppHashBuf) {
1291 // Use the CppHashFilename and calculate a line number based on the
1292 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1294 const std::string Filename = Parser->CppHashFilename;
1296 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1297 int CppHashLocLineNo =
1298 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1299 int LineNo = Parser->CppHashLineNumber - 1 +
1300 (DiagLocLineNo - CppHashLocLineNo);
1302 SMDiagnostic NewDiag(*Diag.getSourceMgr(),
1308 Diag.getLineContents(),
1309 Diag.getShowLine());
1311 NewDiag.Print(0, OS);
1314 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1315 const std::vector<StringRef> &Parameters,
1316 const std::vector<std::vector<AsmToken> > &A,
1318 raw_svector_ostream OS(Buf);
1319 unsigned NParameters = Parameters.size();
1320 if (NParameters != 0 && NParameters != A.size())
1321 return Error(L, "Wrong number of arguments");
1323 while (!Body.empty()) {
1324 // Scan for the next substitution.
1325 std::size_t End = Body.size(), Pos = 0;
1326 for (; Pos != End; ++Pos) {
1327 // Check for a substitution or escape.
1329 // This macro has no parameters, look for $0, $1, etc.
1330 if (Body[Pos] != '$' || Pos + 1 == End)
1333 char Next = Body[Pos + 1];
1334 if (Next == '$' || Next == 'n' || isdigit(Next))
1337 // This macro has parameters, look for \foo, \bar, etc.
1338 if (Body[Pos] == '\\' && Pos + 1 != End)
1344 OS << Body.slice(0, Pos);
1346 // Check if we reached the end.
1351 switch (Body[Pos+1]) {
1357 // $n => number of arguments
1362 // $[0-9] => argument
1364 // Missing arguments are ignored.
1365 unsigned Index = Body[Pos+1] - '0';
1366 if (Index >= A.size())
1369 // Otherwise substitute with the token values, with spaces eliminated.
1370 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1371 ie = A[Index].end(); it != ie; ++it)
1372 OS << it->getString();
1378 unsigned I = Pos + 1;
1379 while (isalnum(Body[I]) && I + 1 != End)
1382 const char *Begin = Body.data() + Pos +1;
1383 StringRef Argument(Begin, I - (Pos +1));
1385 for (; Index < NParameters; ++Index)
1386 if (Parameters[Index] == Argument)
1389 // FIXME: We should error at the macro definition.
1390 if (Index == NParameters)
1391 return Error(L, "Parameter not found");
1393 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1394 ie = A[Index].end(); it != ie; ++it)
1395 OS << it->getString();
1397 Pos += 1 + Argument.size();
1399 // Update the scan point.
1400 Body = Body.substr(Pos);
1403 // We include the .endmacro in the buffer as our queue to exit the macro
1405 OS << ".endmacro\n";
1409 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1411 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1415 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1417 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1418 // this, although we should protect against infinite loops.
1419 if (ActiveMacros.size() == 20)
1420 return TokError("macros cannot be nested more than 20 levels deep");
1422 // Parse the macro instantiation arguments.
1423 std::vector<std::vector<AsmToken> > MacroArguments;
1424 MacroArguments.push_back(std::vector<AsmToken>());
1425 unsigned ParenLevel = 0;
1427 if (Lexer.is(AsmToken::Eof))
1428 return TokError("unexpected token in macro instantiation");
1429 if (Lexer.is(AsmToken::EndOfStatement))
1432 // If we aren't inside parentheses and this is a comma, start a new token
1434 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1435 MacroArguments.push_back(std::vector<AsmToken>());
1437 // Adjust the current parentheses level.
1438 if (Lexer.is(AsmToken::LParen))
1440 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1443 // Append the token to the current argument list.
1444 MacroArguments.back().push_back(getTok());
1449 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1450 // to hold the macro body with substitutions.
1451 SmallString<256> Buf;
1452 StringRef Body = M->Body;
1454 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1457 MemoryBuffer *Instantiation =
1458 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1460 // Create the macro instantiation object and add to the current macro
1461 // instantiation stack.
1462 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1465 ActiveMacros.push_back(MI);
1467 // Jump to the macro instantiation and prime the lexer.
1468 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1469 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1475 void AsmParser::HandleMacroExit() {
1476 // Jump to the EndOfStatement we should return to, and consume it.
1477 JumpToLoc(ActiveMacros.back()->ExitLoc);
1480 // Pop the instantiation entry.
1481 delete ActiveMacros.back();
1482 ActiveMacros.pop_back();
1485 static void MarkUsed(const MCExpr *Value) {
1486 switch (Value->getKind()) {
1487 case MCExpr::Binary:
1488 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1489 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1491 case MCExpr::Target:
1492 case MCExpr::Constant:
1494 case MCExpr::SymbolRef: {
1495 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1499 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1504 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1505 // FIXME: Use better location, we should use proper tokens.
1506 SMLoc EqualLoc = Lexer.getLoc();
1508 const MCExpr *Value;
1509 if (ParseExpression(Value))
1514 if (Lexer.isNot(AsmToken::EndOfStatement))
1515 return TokError("unexpected token in assignment");
1517 // Error on assignment to '.'.
1519 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1520 "(use '.space' or '.org').)"));
1523 // Eat the end of statement marker.
1526 // Validate that the LHS is allowed to be a variable (either it has not been
1527 // used as a symbol, or it is an absolute symbol).
1528 MCSymbol *Sym = getContext().LookupSymbol(Name);
1530 // Diagnose assignment to a label.
1532 // FIXME: Diagnostics. Note the location of the definition as a label.
1533 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1534 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1535 ; // Allow redefinitions of undefined symbols only used in directives.
1536 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1537 return Error(EqualLoc, "redefinition of '" + Name + "'");
1538 else if (!Sym->isVariable())
1539 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1540 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1541 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1544 // Don't count these checks as uses.
1545 Sym->setUsed(false);
1547 Sym = getContext().GetOrCreateSymbol(Name);
1549 // FIXME: Handle '.'.
1551 // Do the assignment.
1552 Out.EmitAssignment(Sym, Value);
1557 /// ParseIdentifier:
1560 bool AsmParser::ParseIdentifier(StringRef &Res) {
1561 // The assembler has relaxed rules for accepting identifiers, in particular we
1562 // allow things like '.globl $foo', which would normally be separate
1563 // tokens. At this level, we have already lexed so we cannot (currently)
1564 // handle this as a context dependent token, instead we detect adjacent tokens
1565 // and return the combined identifier.
1566 if (Lexer.is(AsmToken::Dollar)) {
1567 SMLoc DollarLoc = getLexer().getLoc();
1569 // Consume the dollar sign, and check for a following identifier.
1571 if (Lexer.isNot(AsmToken::Identifier))
1574 // We have a '$' followed by an identifier, make sure they are adjacent.
1575 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1578 // Construct the joined identifier and consume the token.
1579 Res = StringRef(DollarLoc.getPointer(),
1580 getTok().getIdentifier().size() + 1);
1585 if (Lexer.isNot(AsmToken::Identifier) &&
1586 Lexer.isNot(AsmToken::String))
1589 Res = getTok().getIdentifier();
1591 Lex(); // Consume the identifier token.
1596 /// ParseDirectiveSet:
1597 /// ::= .equ identifier ',' expression
1598 /// ::= .equiv identifier ',' expression
1599 /// ::= .set identifier ',' expression
1600 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1603 if (ParseIdentifier(Name))
1604 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1606 if (getLexer().isNot(AsmToken::Comma))
1607 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1610 return ParseAssignment(Name, allow_redef);
1613 bool AsmParser::ParseEscapedString(std::string &Data) {
1614 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1617 StringRef Str = getTok().getStringContents();
1618 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1619 if (Str[i] != '\\') {
1624 // Recognize escaped characters. Note that this escape semantics currently
1625 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1628 return TokError("unexpected backslash at end of string");
1630 // Recognize octal sequences.
1631 if ((unsigned) (Str[i] - '0') <= 7) {
1632 // Consume up to three octal characters.
1633 unsigned Value = Str[i] - '0';
1635 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1637 Value = Value * 8 + (Str[i] - '0');
1639 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1641 Value = Value * 8 + (Str[i] - '0');
1646 return TokError("invalid octal escape sequence (out of range)");
1648 Data += (unsigned char) Value;
1652 // Otherwise recognize individual escapes.
1655 // Just reject invalid escape sequences for now.
1656 return TokError("invalid escape sequence (unrecognized character)");
1658 case 'b': Data += '\b'; break;
1659 case 'f': Data += '\f'; break;
1660 case 'n': Data += '\n'; break;
1661 case 'r': Data += '\r'; break;
1662 case 't': Data += '\t'; break;
1663 case '"': Data += '"'; break;
1664 case '\\': Data += '\\'; break;
1671 /// ParseDirectiveAscii:
1672 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1673 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1674 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1675 CheckForValidSection();
1678 if (getLexer().isNot(AsmToken::String))
1679 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1682 if (ParseEscapedString(Data))
1685 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1687 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1691 if (getLexer().is(AsmToken::EndOfStatement))
1694 if (getLexer().isNot(AsmToken::Comma))
1695 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1704 /// ParseDirectiveValue
1705 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1706 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1707 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1708 CheckForValidSection();
1711 const MCExpr *Value;
1712 SMLoc ExprLoc = getLexer().getLoc();
1713 if (ParseExpression(Value))
1716 // Special case constant expressions to match code generator.
1717 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1718 assert(Size <= 8 && "Invalid size");
1719 uint64_t IntValue = MCE->getValue();
1720 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1721 return Error(ExprLoc, "literal value out of range for directive");
1722 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1724 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1726 if (getLexer().is(AsmToken::EndOfStatement))
1729 // FIXME: Improve diagnostic.
1730 if (getLexer().isNot(AsmToken::Comma))
1731 return TokError("unexpected token in directive");
1740 /// ParseDirectiveRealValue
1741 /// ::= (.single | .double) [ expression (, expression)* ]
1742 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1743 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1744 CheckForValidSection();
1747 // We don't truly support arithmetic on floating point expressions, so we
1748 // have to manually parse unary prefixes.
1750 if (getLexer().is(AsmToken::Minus)) {
1753 } else if (getLexer().is(AsmToken::Plus))
1756 if (getLexer().isNot(AsmToken::Integer) &&
1757 getLexer().isNot(AsmToken::Real) &&
1758 getLexer().isNot(AsmToken::Identifier))
1759 return TokError("unexpected token in directive");
1761 // Convert to an APFloat.
1762 APFloat Value(Semantics);
1763 StringRef IDVal = getTok().getString();
1764 if (getLexer().is(AsmToken::Identifier)) {
1765 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1766 Value = APFloat::getInf(Semantics);
1767 else if (!IDVal.compare_lower("nan"))
1768 Value = APFloat::getNaN(Semantics, false, ~0);
1770 return TokError("invalid floating point literal");
1771 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1772 APFloat::opInvalidOp)
1773 return TokError("invalid floating point literal");
1777 // Consume the numeric token.
1780 // Emit the value as an integer.
1781 APInt AsInt = Value.bitcastToAPInt();
1782 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1783 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1785 if (getLexer().is(AsmToken::EndOfStatement))
1788 if (getLexer().isNot(AsmToken::Comma))
1789 return TokError("unexpected token in directive");
1798 /// ParseDirectiveSpace
1799 /// ::= .space expression [ , expression ]
1800 bool AsmParser::ParseDirectiveSpace() {
1801 CheckForValidSection();
1804 if (ParseAbsoluteExpression(NumBytes))
1807 int64_t FillExpr = 0;
1808 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1809 if (getLexer().isNot(AsmToken::Comma))
1810 return TokError("unexpected token in '.space' directive");
1813 if (ParseAbsoluteExpression(FillExpr))
1816 if (getLexer().isNot(AsmToken::EndOfStatement))
1817 return TokError("unexpected token in '.space' directive");
1823 return TokError("invalid number of bytes in '.space' directive");
1825 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1826 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1831 /// ParseDirectiveZero
1832 /// ::= .zero expression
1833 bool AsmParser::ParseDirectiveZero() {
1834 CheckForValidSection();
1837 if (ParseAbsoluteExpression(NumBytes))
1841 if (getLexer().is(AsmToken::Comma)) {
1843 if (ParseAbsoluteExpression(Val))
1847 if (getLexer().isNot(AsmToken::EndOfStatement))
1848 return TokError("unexpected token in '.zero' directive");
1852 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1857 /// ParseDirectiveFill
1858 /// ::= .fill expression , expression , expression
1859 bool AsmParser::ParseDirectiveFill() {
1860 CheckForValidSection();
1863 if (ParseAbsoluteExpression(NumValues))
1866 if (getLexer().isNot(AsmToken::Comma))
1867 return TokError("unexpected token in '.fill' directive");
1871 if (ParseAbsoluteExpression(FillSize))
1874 if (getLexer().isNot(AsmToken::Comma))
1875 return TokError("unexpected token in '.fill' directive");
1879 if (ParseAbsoluteExpression(FillExpr))
1882 if (getLexer().isNot(AsmToken::EndOfStatement))
1883 return TokError("unexpected token in '.fill' directive");
1887 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1888 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1890 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1891 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1896 /// ParseDirectiveOrg
1897 /// ::= .org expression [ , expression ]
1898 bool AsmParser::ParseDirectiveOrg() {
1899 CheckForValidSection();
1901 const MCExpr *Offset;
1902 if (ParseExpression(Offset))
1905 // Parse optional fill expression.
1906 int64_t FillExpr = 0;
1907 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1908 if (getLexer().isNot(AsmToken::Comma))
1909 return TokError("unexpected token in '.org' directive");
1912 if (ParseAbsoluteExpression(FillExpr))
1915 if (getLexer().isNot(AsmToken::EndOfStatement))
1916 return TokError("unexpected token in '.org' directive");
1921 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1922 // has to be relative to the current section.
1923 getStreamer().EmitValueToOffset(Offset, FillExpr);
1928 /// ParseDirectiveAlign
1929 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1930 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1931 CheckForValidSection();
1933 SMLoc AlignmentLoc = getLexer().getLoc();
1935 if (ParseAbsoluteExpression(Alignment))
1939 bool HasFillExpr = false;
1940 int64_t FillExpr = 0;
1941 int64_t MaxBytesToFill = 0;
1942 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1943 if (getLexer().isNot(AsmToken::Comma))
1944 return TokError("unexpected token in directive");
1947 // The fill expression can be omitted while specifying a maximum number of
1948 // alignment bytes, e.g:
1950 if (getLexer().isNot(AsmToken::Comma)) {
1952 if (ParseAbsoluteExpression(FillExpr))
1956 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1957 if (getLexer().isNot(AsmToken::Comma))
1958 return TokError("unexpected token in directive");
1961 MaxBytesLoc = getLexer().getLoc();
1962 if (ParseAbsoluteExpression(MaxBytesToFill))
1965 if (getLexer().isNot(AsmToken::EndOfStatement))
1966 return TokError("unexpected token in directive");
1975 // Compute alignment in bytes.
1977 // FIXME: Diagnose overflow.
1978 if (Alignment >= 32) {
1979 Error(AlignmentLoc, "invalid alignment value");
1983 Alignment = 1ULL << Alignment;
1986 // Diagnose non-sensical max bytes to align.
1987 if (MaxBytesLoc.isValid()) {
1988 if (MaxBytesToFill < 1) {
1989 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1990 "many bytes, ignoring maximum bytes expression");
1994 if (MaxBytesToFill >= Alignment) {
1995 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2001 // Check whether we should use optimal code alignment for this .align
2003 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2004 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2005 ValueSize == 1 && UseCodeAlign) {
2006 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2008 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2009 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2016 /// ParseDirectiveSymbolAttribute
2017 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2018 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2019 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2022 SMLoc Loc = getTok().getLoc();
2024 if (ParseIdentifier(Name))
2025 return Error(Loc, "expected identifier in directive");
2027 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2029 // Assembler local symbols don't make any sense here. Complain loudly.
2030 if (Sym->isTemporary())
2031 return Error(Loc, "non-local symbol required in directive");
2033 getStreamer().EmitSymbolAttribute(Sym, Attr);
2035 if (getLexer().is(AsmToken::EndOfStatement))
2038 if (getLexer().isNot(AsmToken::Comma))
2039 return TokError("unexpected token in directive");
2048 /// ParseDirectiveComm
2049 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2050 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2051 CheckForValidSection();
2053 SMLoc IDLoc = getLexer().getLoc();
2055 if (ParseIdentifier(Name))
2056 return TokError("expected identifier in directive");
2058 // Handle the identifier as the key symbol.
2059 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2061 if (getLexer().isNot(AsmToken::Comma))
2062 return TokError("unexpected token in directive");
2066 SMLoc SizeLoc = getLexer().getLoc();
2067 if (ParseAbsoluteExpression(Size))
2070 int64_t Pow2Alignment = 0;
2071 SMLoc Pow2AlignmentLoc;
2072 if (getLexer().is(AsmToken::Comma)) {
2074 Pow2AlignmentLoc = getLexer().getLoc();
2075 if (ParseAbsoluteExpression(Pow2Alignment))
2078 // If this target takes alignments in bytes (not log) validate and convert.
2079 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2080 if (!isPowerOf2_64(Pow2Alignment))
2081 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2082 Pow2Alignment = Log2_64(Pow2Alignment);
2086 if (getLexer().isNot(AsmToken::EndOfStatement))
2087 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2091 // NOTE: a size of zero for a .comm should create a undefined symbol
2092 // but a size of .lcomm creates a bss symbol of size zero.
2094 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2095 "be less than zero");
2097 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2098 // may internally end up wanting an alignment in bytes.
2099 // FIXME: Diagnose overflow.
2100 if (Pow2Alignment < 0)
2101 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2102 "alignment, can't be less than zero");
2104 if (!Sym->isUndefined())
2105 return Error(IDLoc, "invalid symbol redefinition");
2107 // '.lcomm' is equivalent to '.zerofill'.
2108 // Create the Symbol as a common or local common with Size and Pow2Alignment
2110 getStreamer().EmitZerofill(Ctx.getMachOSection(
2111 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2112 0, SectionKind::getBSS()),
2113 Sym, Size, 1 << Pow2Alignment);
2117 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2121 /// ParseDirectiveAbort
2122 /// ::= .abort [... message ...]
2123 bool AsmParser::ParseDirectiveAbort() {
2124 // FIXME: Use loc from directive.
2125 SMLoc Loc = getLexer().getLoc();
2127 StringRef Str = ParseStringToEndOfStatement();
2128 if (getLexer().isNot(AsmToken::EndOfStatement))
2129 return TokError("unexpected token in '.abort' directive");
2134 Error(Loc, ".abort detected. Assembly stopping.");
2136 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2137 // FIXME: Actually abort assembly here.
2142 /// ParseDirectiveInclude
2143 /// ::= .include "filename"
2144 bool AsmParser::ParseDirectiveInclude() {
2145 if (getLexer().isNot(AsmToken::String))
2146 return TokError("expected string in '.include' directive");
2148 std::string Filename = getTok().getString();
2149 SMLoc IncludeLoc = getLexer().getLoc();
2152 if (getLexer().isNot(AsmToken::EndOfStatement))
2153 return TokError("unexpected token in '.include' directive");
2155 // Strip the quotes.
2156 Filename = Filename.substr(1, Filename.size()-2);
2158 // Attempt to switch the lexer to the included file before consuming the end
2159 // of statement to avoid losing it when we switch.
2160 if (EnterIncludeFile(Filename)) {
2161 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2168 /// ParseDirectiveIf
2169 /// ::= .if expression
2170 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2171 TheCondStack.push_back(TheCondState);
2172 TheCondState.TheCond = AsmCond::IfCond;
2173 if(TheCondState.Ignore) {
2174 EatToEndOfStatement();
2178 if (ParseAbsoluteExpression(ExprValue))
2181 if (getLexer().isNot(AsmToken::EndOfStatement))
2182 return TokError("unexpected token in '.if' directive");
2186 TheCondState.CondMet = ExprValue;
2187 TheCondState.Ignore = !TheCondState.CondMet;
2193 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2195 TheCondStack.push_back(TheCondState);
2196 TheCondState.TheCond = AsmCond::IfCond;
2198 if (TheCondState.Ignore) {
2199 EatToEndOfStatement();
2201 if (ParseIdentifier(Name))
2202 return TokError("expected identifier after '.ifdef'");
2206 MCSymbol *Sym = getContext().LookupSymbol(Name);
2209 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2211 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2212 TheCondState.Ignore = !TheCondState.CondMet;
2218 /// ParseDirectiveElseIf
2219 /// ::= .elseif expression
2220 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2221 if (TheCondState.TheCond != AsmCond::IfCond &&
2222 TheCondState.TheCond != AsmCond::ElseIfCond)
2223 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2225 TheCondState.TheCond = AsmCond::ElseIfCond;
2227 bool LastIgnoreState = false;
2228 if (!TheCondStack.empty())
2229 LastIgnoreState = TheCondStack.back().Ignore;
2230 if (LastIgnoreState || TheCondState.CondMet) {
2231 TheCondState.Ignore = true;
2232 EatToEndOfStatement();
2236 if (ParseAbsoluteExpression(ExprValue))
2239 if (getLexer().isNot(AsmToken::EndOfStatement))
2240 return TokError("unexpected token in '.elseif' directive");
2243 TheCondState.CondMet = ExprValue;
2244 TheCondState.Ignore = !TheCondState.CondMet;
2250 /// ParseDirectiveElse
2252 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2253 if (getLexer().isNot(AsmToken::EndOfStatement))
2254 return TokError("unexpected token in '.else' directive");
2258 if (TheCondState.TheCond != AsmCond::IfCond &&
2259 TheCondState.TheCond != AsmCond::ElseIfCond)
2260 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2262 TheCondState.TheCond = AsmCond::ElseCond;
2263 bool LastIgnoreState = false;
2264 if (!TheCondStack.empty())
2265 LastIgnoreState = TheCondStack.back().Ignore;
2266 if (LastIgnoreState || TheCondState.CondMet)
2267 TheCondState.Ignore = true;
2269 TheCondState.Ignore = false;
2274 /// ParseDirectiveEndIf
2276 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2277 if (getLexer().isNot(AsmToken::EndOfStatement))
2278 return TokError("unexpected token in '.endif' directive");
2282 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2283 TheCondStack.empty())
2284 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2286 if (!TheCondStack.empty()) {
2287 TheCondState = TheCondStack.back();
2288 TheCondStack.pop_back();
2294 /// ParseDirectiveFile
2295 /// ::= .file [number] string
2296 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2297 // FIXME: I'm not sure what this is.
2298 int64_t FileNumber = -1;
2299 SMLoc FileNumberLoc = getLexer().getLoc();
2300 if (getLexer().is(AsmToken::Integer)) {
2301 FileNumber = getTok().getIntVal();
2305 return TokError("file number less than one");
2308 if (getLexer().isNot(AsmToken::String))
2309 return TokError("unexpected token in '.file' directive");
2311 StringRef Filename = getTok().getString();
2312 Filename = Filename.substr(1, Filename.size()-2);
2315 if (getLexer().isNot(AsmToken::EndOfStatement))
2316 return TokError("unexpected token in '.file' directive");
2318 if (FileNumber == -1)
2319 getStreamer().EmitFileDirective(Filename);
2321 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2322 Error(FileNumberLoc, "file number already allocated");
2328 /// ParseDirectiveLine
2329 /// ::= .line [number]
2330 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2331 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2332 if (getLexer().isNot(AsmToken::Integer))
2333 return TokError("unexpected token in '.line' directive");
2335 int64_t LineNumber = getTok().getIntVal();
2339 // FIXME: Do something with the .line.
2342 if (getLexer().isNot(AsmToken::EndOfStatement))
2343 return TokError("unexpected token in '.line' directive");
2349 /// ParseDirectiveLoc
2350 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2351 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2352 /// The first number is a file number, must have been previously assigned with
2353 /// a .file directive, the second number is the line number and optionally the
2354 /// third number is a column position (zero if not specified). The remaining
2355 /// optional items are .loc sub-directives.
2356 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2358 if (getLexer().isNot(AsmToken::Integer))
2359 return TokError("unexpected token in '.loc' directive");
2360 int64_t FileNumber = getTok().getIntVal();
2362 return TokError("file number less than one in '.loc' directive");
2363 if (!getContext().isValidDwarfFileNumber(FileNumber))
2364 return TokError("unassigned file number in '.loc' directive");
2367 int64_t LineNumber = 0;
2368 if (getLexer().is(AsmToken::Integer)) {
2369 LineNumber = getTok().getIntVal();
2371 return TokError("line number less than one in '.loc' directive");
2375 int64_t ColumnPos = 0;
2376 if (getLexer().is(AsmToken::Integer)) {
2377 ColumnPos = getTok().getIntVal();
2379 return TokError("column position less than zero in '.loc' directive");
2383 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2385 int64_t Discriminator = 0;
2386 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2388 if (getLexer().is(AsmToken::EndOfStatement))
2392 SMLoc Loc = getTok().getLoc();
2393 if (getParser().ParseIdentifier(Name))
2394 return TokError("unexpected token in '.loc' directive");
2396 if (Name == "basic_block")
2397 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2398 else if (Name == "prologue_end")
2399 Flags |= DWARF2_FLAG_PROLOGUE_END;
2400 else if (Name == "epilogue_begin")
2401 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2402 else if (Name == "is_stmt") {
2403 SMLoc Loc = getTok().getLoc();
2404 const MCExpr *Value;
2405 if (getParser().ParseExpression(Value))
2407 // The expression must be the constant 0 or 1.
2408 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2409 int Value = MCE->getValue();
2411 Flags &= ~DWARF2_FLAG_IS_STMT;
2412 else if (Value == 1)
2413 Flags |= DWARF2_FLAG_IS_STMT;
2415 return Error(Loc, "is_stmt value not 0 or 1");
2418 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2421 else if (Name == "isa") {
2422 SMLoc Loc = getTok().getLoc();
2423 const MCExpr *Value;
2424 if (getParser().ParseExpression(Value))
2426 // The expression must be a constant greater or equal to 0.
2427 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2428 int Value = MCE->getValue();
2430 return Error(Loc, "isa number less than zero");
2434 return Error(Loc, "isa number not a constant value");
2437 else if (Name == "discriminator") {
2438 if (getParser().ParseAbsoluteExpression(Discriminator))
2442 return Error(Loc, "unknown sub-directive in '.loc' directive");
2445 if (getLexer().is(AsmToken::EndOfStatement))
2450 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2451 Isa, Discriminator, StringRef());
2456 /// ParseDirectiveStabs
2457 /// ::= .stabs string, number, number, number
2458 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2459 SMLoc DirectiveLoc) {
2460 return TokError("unsupported directive '" + Directive + "'");
2463 /// ParseDirectiveCFISections
2464 /// ::= .cfi_sections section [, section]
2465 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2466 SMLoc DirectiveLoc) {
2471 if (getParser().ParseIdentifier(Name))
2472 return TokError("Expected an identifier");
2474 if (Name == ".eh_frame")
2476 else if (Name == ".debug_frame")
2479 if (getLexer().is(AsmToken::Comma)) {
2482 if (getParser().ParseIdentifier(Name))
2483 return TokError("Expected an identifier");
2485 if (Name == ".eh_frame")
2487 else if (Name == ".debug_frame")
2491 getStreamer().EmitCFISections(EH, Debug);
2496 /// ParseDirectiveCFIStartProc
2497 /// ::= .cfi_startproc
2498 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2499 SMLoc DirectiveLoc) {
2500 getStreamer().EmitCFIStartProc();
2504 /// ParseDirectiveCFIEndProc
2505 /// ::= .cfi_endproc
2506 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2507 getStreamer().EmitCFIEndProc();
2511 /// ParseRegisterOrRegisterNumber - parse register name or number.
2512 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2513 SMLoc DirectiveLoc) {
2516 if (getLexer().isNot(AsmToken::Integer)) {
2517 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2520 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2522 return getParser().ParseAbsoluteExpression(Register);
2527 /// ParseDirectiveCFIDefCfa
2528 /// ::= .cfi_def_cfa register, offset
2529 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2530 SMLoc DirectiveLoc) {
2531 int64_t Register = 0;
2532 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2535 if (getLexer().isNot(AsmToken::Comma))
2536 return TokError("unexpected token in directive");
2540 if (getParser().ParseAbsoluteExpression(Offset))
2543 getStreamer().EmitCFIDefCfa(Register, Offset);
2547 /// ParseDirectiveCFIDefCfaOffset
2548 /// ::= .cfi_def_cfa_offset offset
2549 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2550 SMLoc DirectiveLoc) {
2552 if (getParser().ParseAbsoluteExpression(Offset))
2555 getStreamer().EmitCFIDefCfaOffset(Offset);
2559 /// ParseDirectiveCFIAdjustCfaOffset
2560 /// ::= .cfi_adjust_cfa_offset adjustment
2561 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2562 SMLoc DirectiveLoc) {
2563 int64_t Adjustment = 0;
2564 if (getParser().ParseAbsoluteExpression(Adjustment))
2567 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2571 /// ParseDirectiveCFIDefCfaRegister
2572 /// ::= .cfi_def_cfa_register register
2573 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2574 SMLoc DirectiveLoc) {
2575 int64_t Register = 0;
2576 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2579 getStreamer().EmitCFIDefCfaRegister(Register);
2583 /// ParseDirectiveCFIOffset
2584 /// ::= .cfi_offset register, offset
2585 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2586 int64_t Register = 0;
2589 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2592 if (getLexer().isNot(AsmToken::Comma))
2593 return TokError("unexpected token in directive");
2596 if (getParser().ParseAbsoluteExpression(Offset))
2599 getStreamer().EmitCFIOffset(Register, Offset);
2603 /// ParseDirectiveCFIRelOffset
2604 /// ::= .cfi_rel_offset register, offset
2605 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2606 SMLoc DirectiveLoc) {
2607 int64_t Register = 0;
2609 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2612 if (getLexer().isNot(AsmToken::Comma))
2613 return TokError("unexpected token in directive");
2617 if (getParser().ParseAbsoluteExpression(Offset))
2620 getStreamer().EmitCFIRelOffset(Register, Offset);
2624 static bool isValidEncoding(int64_t Encoding) {
2625 if (Encoding & ~0xff)
2628 if (Encoding == dwarf::DW_EH_PE_omit)
2631 const unsigned Format = Encoding & 0xf;
2632 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2633 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2634 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2635 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2638 const unsigned Application = Encoding & 0x70;
2639 if (Application != dwarf::DW_EH_PE_absptr &&
2640 Application != dwarf::DW_EH_PE_pcrel)
2646 /// ParseDirectiveCFIPersonalityOrLsda
2647 /// ::= .cfi_personality encoding, [symbol_name]
2648 /// ::= .cfi_lsda encoding, [symbol_name]
2649 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2650 SMLoc DirectiveLoc) {
2651 int64_t Encoding = 0;
2652 if (getParser().ParseAbsoluteExpression(Encoding))
2654 if (Encoding == dwarf::DW_EH_PE_omit)
2657 if (!isValidEncoding(Encoding))
2658 return TokError("unsupported encoding.");
2660 if (getLexer().isNot(AsmToken::Comma))
2661 return TokError("unexpected token in directive");
2665 if (getParser().ParseIdentifier(Name))
2666 return TokError("expected identifier in directive");
2668 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2670 if (IDVal == ".cfi_personality")
2671 getStreamer().EmitCFIPersonality(Sym, Encoding);
2673 assert(IDVal == ".cfi_lsda");
2674 getStreamer().EmitCFILsda(Sym, Encoding);
2679 /// ParseDirectiveCFIRememberState
2680 /// ::= .cfi_remember_state
2681 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2682 SMLoc DirectiveLoc) {
2683 getStreamer().EmitCFIRememberState();
2687 /// ParseDirectiveCFIRestoreState
2688 /// ::= .cfi_remember_state
2689 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2690 SMLoc DirectiveLoc) {
2691 getStreamer().EmitCFIRestoreState();
2695 /// ParseDirectiveCFISameValue
2696 /// ::= .cfi_same_value register
2697 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2698 SMLoc DirectiveLoc) {
2699 int64_t Register = 0;
2701 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2704 getStreamer().EmitCFISameValue(Register);
2709 /// ParseDirectiveMacrosOnOff
2712 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2713 SMLoc DirectiveLoc) {
2714 if (getLexer().isNot(AsmToken::EndOfStatement))
2715 return Error(getLexer().getLoc(),
2716 "unexpected token in '" + Directive + "' directive");
2718 getParser().MacrosEnabled = Directive == ".macros_on";
2723 /// ParseDirectiveMacro
2724 /// ::= .macro name [parameters]
2725 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2726 SMLoc DirectiveLoc) {
2728 if (getParser().ParseIdentifier(Name))
2729 return TokError("expected identifier in directive");
2731 std::vector<StringRef> Parameters;
2732 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2734 StringRef Parameter;
2735 if (getParser().ParseIdentifier(Parameter))
2736 return TokError("expected identifier in directive");
2737 Parameters.push_back(Parameter);
2739 if (getLexer().isNot(AsmToken::Comma))
2745 if (getLexer().isNot(AsmToken::EndOfStatement))
2746 return TokError("unexpected token in '.macro' directive");
2748 // Eat the end of statement.
2751 AsmToken EndToken, StartToken = getTok();
2753 // Lex the macro definition.
2755 // Check whether we have reached the end of the file.
2756 if (getLexer().is(AsmToken::Eof))
2757 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2759 // Otherwise, check whether we have reach the .endmacro.
2760 if (getLexer().is(AsmToken::Identifier) &&
2761 (getTok().getIdentifier() == ".endm" ||
2762 getTok().getIdentifier() == ".endmacro")) {
2763 EndToken = getTok();
2765 if (getLexer().isNot(AsmToken::EndOfStatement))
2766 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2771 // Otherwise, scan til the end of the statement.
2772 getParser().EatToEndOfStatement();
2775 if (getParser().MacroMap.lookup(Name)) {
2776 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2779 const char *BodyStart = StartToken.getLoc().getPointer();
2780 const char *BodyEnd = EndToken.getLoc().getPointer();
2781 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2782 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2786 /// ParseDirectiveEndMacro
2789 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2790 SMLoc DirectiveLoc) {
2791 if (getLexer().isNot(AsmToken::EndOfStatement))
2792 return TokError("unexpected token in '" + Directive + "' directive");
2794 // If we are inside a macro instantiation, terminate the current
2796 if (!getParser().ActiveMacros.empty()) {
2797 getParser().HandleMacroExit();
2801 // Otherwise, this .endmacro is a stray entry in the file; well formed
2802 // .endmacro directives are handled during the macro definition parsing.
2803 return TokError("unexpected '" + Directive + "' in file, "
2804 "no current macro definition");
2807 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2808 getParser().CheckForValidSection();
2810 const MCExpr *Value;
2812 if (getParser().ParseExpression(Value))
2815 if (getLexer().isNot(AsmToken::EndOfStatement))
2816 return TokError("unexpected token in directive");
2818 if (DirName[1] == 's')
2819 getStreamer().EmitSLEB128Value(Value);
2821 getStreamer().EmitULEB128Value(Value);
2827 /// \brief Create an MCAsmParser instance.
2828 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
2829 MCContext &C, MCStreamer &Out,
2830 const MCAsmInfo &MAI) {
2831 return new AsmParser(SM, C, Out, MAI);