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;
119 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
120 const MCAsmInfo &MAI);
123 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
125 void AddDirectiveHandler(MCAsmParserExtension *Object,
127 DirectiveHandler Handler) {
128 DirectiveMap[Directive] = std::make_pair(Object, Handler);
132 /// @name MCAsmParser Interface
135 virtual SourceMgr &getSourceManager() { return SrcMgr; }
136 virtual MCAsmLexer &getLexer() { return Lexer; }
137 virtual MCContext &getContext() { return Ctx; }
138 virtual MCStreamer &getStreamer() { return Out; }
140 virtual bool Warning(SMLoc L, const Twine &Msg);
141 virtual bool Error(SMLoc L, const Twine &Msg);
143 const AsmToken &Lex();
145 bool ParseExpression(const MCExpr *&Res);
146 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
147 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
148 virtual bool ParseAbsoluteExpression(int64_t &Res);
153 void CheckForValidSection();
155 bool ParseStatement();
156 void EatToEndOfLine();
157 bool ParseCppHashLineFilenameComment(const SMLoc &L);
159 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
160 bool expandMacro(SmallString<256> &Buf, StringRef Body,
161 const std::vector<StringRef> &Parameters,
162 const std::vector<std::vector<AsmToken> > &A,
164 void HandleMacroExit();
166 void PrintMacroInstantiations();
167 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type,
168 bool ShowLine = true) const {
169 SrcMgr.PrintMessage(Loc, Msg, Type, ShowLine);
172 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
173 bool EnterIncludeFile(const std::string &Filename);
175 /// \brief Reset the current lexer position to that given by \arg Loc. The
176 /// current token is not set; clients should ensure Lex() is called
178 void JumpToLoc(SMLoc Loc);
180 void EatToEndOfStatement();
182 /// \brief Parse up to the end of statement and a return the contents from the
183 /// current token until the end of the statement; the current token on exit
184 /// will be either the EndOfStatement or EOF.
185 StringRef ParseStringToEndOfStatement();
187 bool ParseAssignment(StringRef Name, bool allow_redef);
189 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
190 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
191 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
192 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
194 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
195 /// and set \arg Res to the identifier contents.
196 bool ParseIdentifier(StringRef &Res);
198 // Directive Parsing.
200 // ".ascii", ".asciiz", ".string"
201 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
202 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
203 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
204 bool ParseDirectiveFill(); // ".fill"
205 bool ParseDirectiveSpace(); // ".space"
206 bool ParseDirectiveZero(); // ".zero"
207 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
208 bool ParseDirectiveOrg(); // ".org"
209 // ".align{,32}", ".p2align{,w,l}"
210 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
212 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
213 /// accepts a single symbol (which should be a label or an external).
214 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
216 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
218 bool ParseDirectiveAbort(); // ".abort"
219 bool ParseDirectiveInclude(); // ".include"
221 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
222 // ".ifdef" or ".ifndef", depending on expect_defined
223 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
224 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
225 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
226 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
228 /// ParseEscapedString - Parse the current token as a string which may include
229 /// escaped characters and return the string contents.
230 bool ParseEscapedString(std::string &Data);
232 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
233 MCSymbolRefExpr::VariantKind Variant);
236 /// \brief Generic implementations of directive handling, etc. which is shared
237 /// (or the default, at least) for all assembler parser.
238 class GenericAsmParser : public MCAsmParserExtension {
239 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
240 void AddDirectiveHandler(StringRef Directive) {
241 getParser().AddDirectiveHandler(this, Directive,
242 HandleDirective<GenericAsmParser, Handler>);
245 GenericAsmParser() {}
247 AsmParser &getParser() {
248 return (AsmParser&) this->MCAsmParserExtension::getParser();
251 virtual void Initialize(MCAsmParser &Parser) {
252 // Call the base implementation.
253 this->MCAsmParserExtension::Initialize(Parser);
255 // Debugging directives.
256 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
257 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
258 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
259 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
262 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
264 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
266 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
268 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
271 ".cfi_def_cfa_offset");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
273 ".cfi_adjust_cfa_offset");
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
275 ".cfi_def_cfa_register");
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
278 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
281 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
283 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
285 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
287 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
289 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
294 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
296 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
297 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
298 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
300 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
301 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
304 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
306 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
307 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
308 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
309 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
310 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
311 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
312 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
313 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
314 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
315 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
316 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
317 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
318 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
319 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
320 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
321 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
322 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
324 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
325 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
326 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
328 bool ParseDirectiveLEB128(StringRef, SMLoc);
335 extern MCAsmParserExtension *createDarwinAsmParser();
336 extern MCAsmParserExtension *createELFAsmParser();
337 extern MCAsmParserExtension *createCOFFAsmParser();
341 enum { DEFAULT_ADDRSPACE = 0 };
343 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
344 MCStreamer &_Out, const MCAsmInfo &_MAI)
345 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
346 GenericParser(new GenericAsmParser), PlatformParser(0),
347 CurBuffer(0), MacrosEnabled(true) {
348 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
350 // Initialize the generic parser.
351 GenericParser->Initialize(*this);
353 // Initialize the platform / file format parser.
355 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
357 if (_MAI.hasMicrosoftFastStdCallMangling()) {
358 PlatformParser = createCOFFAsmParser();
359 PlatformParser->Initialize(*this);
360 } else if (_MAI.hasSubsectionsViaSymbols()) {
361 PlatformParser = createDarwinAsmParser();
362 PlatformParser->Initialize(*this);
364 PlatformParser = createELFAsmParser();
365 PlatformParser->Initialize(*this);
369 AsmParser::~AsmParser() {
370 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
372 // Destroy any macros.
373 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
374 ie = MacroMap.end(); it != ie; ++it)
375 delete it->getValue();
377 delete PlatformParser;
378 delete GenericParser;
381 void AsmParser::PrintMacroInstantiations() {
382 // Print the active macro instantiation stack.
383 for (std::vector<MacroInstantiation*>::const_reverse_iterator
384 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
385 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
389 bool AsmParser::Warning(SMLoc L, const Twine &Msg) {
390 if (FatalAssemblerWarnings)
391 return Error(L, Msg);
392 PrintMessage(L, Msg, "warning");
393 PrintMacroInstantiations();
397 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
399 PrintMessage(L, Msg, "error");
400 PrintMacroInstantiations();
404 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
405 std::string IncludedFile;
406 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
412 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
417 void AsmParser::JumpToLoc(SMLoc Loc) {
418 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
419 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
422 const AsmToken &AsmParser::Lex() {
423 const AsmToken *tok = &Lexer.Lex();
425 if (tok->is(AsmToken::Eof)) {
426 // If this is the end of an included file, pop the parent file off the
428 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
429 if (ParentIncludeLoc != SMLoc()) {
430 JumpToLoc(ParentIncludeLoc);
435 if (tok->is(AsmToken::Error))
436 Error(Lexer.getErrLoc(), Lexer.getErr());
441 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
442 // Create the initial section, if requested.
443 if (!NoInitialTextSection)
450 AsmCond StartingCondState = TheCondState;
452 // While we have input, parse each statement.
453 while (Lexer.isNot(AsmToken::Eof)) {
454 if (!ParseStatement()) continue;
456 // We had an error, validate that one was emitted and recover by skipping to
458 assert(HadError && "Parse statement returned an error, but none emitted!");
459 EatToEndOfStatement();
462 if (TheCondState.TheCond != StartingCondState.TheCond ||
463 TheCondState.Ignore != StartingCondState.Ignore)
464 return TokError("unmatched .ifs or .elses");
466 // Check to see there are no empty DwarfFile slots.
467 const std::vector<MCDwarfFile *> &MCDwarfFiles =
468 getContext().getMCDwarfFiles();
469 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
470 if (!MCDwarfFiles[i])
471 TokError("unassigned file number: " + Twine(i) + " for .file directives");
474 // Check to see that all assembler local symbols were actually defined.
475 // Targets that don't do subsections via symbols may not want this, though,
476 // so conservatively exclude them. Only do this if we're finalizing, though,
477 // as otherwise we won't necessarilly have seen everything yet.
478 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
479 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
480 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
483 MCSymbol *Sym = i->getValue();
484 // Variable symbols may not be marked as defined, so check those
485 // explicitly. If we know it's a variable, we have a definition for
486 // the purposes of this check.
487 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
488 // FIXME: We would really like to refer back to where the symbol was
489 // first referenced for a source location. We need to add something
490 // to track that. Currently, we just point to the end of the file.
491 PrintMessage(getLexer().getLoc(), "assembler local symbol '" +
492 Sym->getName() + "' not defined", "error", false);
497 // Finalize the output stream if there are no errors and if the client wants
499 if (!HadError && !NoFinalize)
505 void AsmParser::CheckForValidSection() {
506 if (!getStreamer().getCurrentSection()) {
507 TokError("expected section directive before assembly directive");
508 Out.SwitchSection(Ctx.getMachOSection(
510 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
511 0, SectionKind::getText()));
515 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
516 void AsmParser::EatToEndOfStatement() {
517 while (Lexer.isNot(AsmToken::EndOfStatement) &&
518 Lexer.isNot(AsmToken::Eof))
522 if (Lexer.is(AsmToken::EndOfStatement))
526 StringRef AsmParser::ParseStringToEndOfStatement() {
527 const char *Start = getTok().getLoc().getPointer();
529 while (Lexer.isNot(AsmToken::EndOfStatement) &&
530 Lexer.isNot(AsmToken::Eof))
533 const char *End = getTok().getLoc().getPointer();
534 return StringRef(Start, End - Start);
537 /// ParseParenExpr - Parse a paren expression and return it.
538 /// NOTE: This assumes the leading '(' has already been consumed.
540 /// parenexpr ::= expr)
542 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
543 if (ParseExpression(Res)) return true;
544 if (Lexer.isNot(AsmToken::RParen))
545 return TokError("expected ')' in parentheses expression");
546 EndLoc = Lexer.getLoc();
551 /// ParseBracketExpr - Parse a bracket expression and return it.
552 /// NOTE: This assumes the leading '[' has already been consumed.
554 /// bracketexpr ::= expr]
556 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
557 if (ParseExpression(Res)) return true;
558 if (Lexer.isNot(AsmToken::RBrac))
559 return TokError("expected ']' in brackets expression");
560 EndLoc = Lexer.getLoc();
565 /// ParsePrimaryExpr - Parse a primary expression and return it.
566 /// primaryexpr ::= (parenexpr
567 /// primaryexpr ::= symbol
568 /// primaryexpr ::= number
569 /// primaryexpr ::= '.'
570 /// primaryexpr ::= ~,+,- primaryexpr
571 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
572 switch (Lexer.getKind()) {
574 return TokError("unknown token in expression");
575 // If we have an error assume that we've already handled it.
576 case AsmToken::Error:
578 case AsmToken::Exclaim:
579 Lex(); // Eat the operator.
580 if (ParsePrimaryExpr(Res, EndLoc))
582 Res = MCUnaryExpr::CreateLNot(Res, getContext());
584 case AsmToken::Dollar:
585 case AsmToken::String:
586 case AsmToken::Identifier: {
587 EndLoc = Lexer.getLoc();
589 StringRef Identifier;
590 if (ParseIdentifier(Identifier))
593 // This is a symbol reference.
594 std::pair<StringRef, StringRef> Split = Identifier.split('@');
595 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
597 // Lookup the symbol variant if used.
598 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
599 if (Split.first.size() != Identifier.size()) {
600 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
601 if (Variant == MCSymbolRefExpr::VK_Invalid) {
602 Variant = MCSymbolRefExpr::VK_None;
603 return TokError("invalid variant '" + Split.second + "'");
607 // If this is an absolute variable reference, substitute it now to preserve
608 // semantics in the face of reassignment.
609 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
611 return Error(EndLoc, "unexpected modifier on variable reference");
613 Res = Sym->getVariableValue();
617 // Otherwise create a symbol ref.
618 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
621 case AsmToken::Integer: {
622 SMLoc Loc = getTok().getLoc();
623 int64_t IntVal = getTok().getIntVal();
624 Res = MCConstantExpr::Create(IntVal, getContext());
625 EndLoc = Lexer.getLoc();
627 // Look for 'b' or 'f' following an Integer as a directional label
628 if (Lexer.getKind() == AsmToken::Identifier) {
629 StringRef IDVal = getTok().getString();
630 if (IDVal == "f" || IDVal == "b"){
631 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
632 IDVal == "f" ? 1 : 0);
633 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
635 if(IDVal == "b" && Sym->isUndefined())
636 return Error(Loc, "invalid reference to undefined symbol");
637 EndLoc = Lexer.getLoc();
638 Lex(); // Eat identifier.
643 case AsmToken::Real: {
644 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
645 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
646 Res = MCConstantExpr::Create(IntVal, getContext());
650 case AsmToken::Dot: {
651 // This is a '.' reference, which references the current PC. Emit a
652 // temporary label to the streamer and refer to it.
653 MCSymbol *Sym = Ctx.CreateTempSymbol();
655 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
656 EndLoc = Lexer.getLoc();
657 Lex(); // Eat identifier.
660 case AsmToken::LParen:
661 Lex(); // Eat the '('.
662 return ParseParenExpr(Res, EndLoc);
663 case AsmToken::LBrac:
664 if (!PlatformParser->HasBracketExpressions())
665 return TokError("brackets expression not supported on this target");
666 Lex(); // Eat the '['.
667 return ParseBracketExpr(Res, EndLoc);
668 case AsmToken::Minus:
669 Lex(); // Eat the operator.
670 if (ParsePrimaryExpr(Res, EndLoc))
672 Res = MCUnaryExpr::CreateMinus(Res, getContext());
675 Lex(); // Eat the operator.
676 if (ParsePrimaryExpr(Res, EndLoc))
678 Res = MCUnaryExpr::CreatePlus(Res, getContext());
680 case AsmToken::Tilde:
681 Lex(); // Eat the operator.
682 if (ParsePrimaryExpr(Res, EndLoc))
684 Res = MCUnaryExpr::CreateNot(Res, getContext());
689 bool AsmParser::ParseExpression(const MCExpr *&Res) {
691 return ParseExpression(Res, EndLoc);
695 AsmParser::ApplyModifierToExpr(const MCExpr *E,
696 MCSymbolRefExpr::VariantKind Variant) {
697 // Recurse over the given expression, rebuilding it to apply the given variant
698 // if there is exactly one symbol.
699 switch (E->getKind()) {
701 case MCExpr::Constant:
704 case MCExpr::SymbolRef: {
705 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
707 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
708 TokError("invalid variant on expression '" +
709 getTok().getIdentifier() + "' (already modified)");
713 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
716 case MCExpr::Unary: {
717 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
718 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
721 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
724 case MCExpr::Binary: {
725 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
726 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
727 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
732 if (!LHS) LHS = BE->getLHS();
733 if (!RHS) RHS = BE->getRHS();
735 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
739 assert(0 && "Invalid expression kind!");
743 /// ParseExpression - Parse an expression and return it.
745 /// expr ::= expr &&,|| expr -> lowest.
746 /// expr ::= expr |,^,&,! expr
747 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
748 /// expr ::= expr <<,>> expr
749 /// expr ::= expr +,- expr
750 /// expr ::= expr *,/,% expr -> highest.
751 /// expr ::= primaryexpr
753 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
754 // Parse the expression.
756 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
759 // As a special case, we support 'a op b @ modifier' by rewriting the
760 // expression to include the modifier. This is inefficient, but in general we
761 // expect users to use 'a@modifier op b'.
762 if (Lexer.getKind() == AsmToken::At) {
765 if (Lexer.isNot(AsmToken::Identifier))
766 return TokError("unexpected symbol modifier following '@'");
768 MCSymbolRefExpr::VariantKind Variant =
769 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
770 if (Variant == MCSymbolRefExpr::VK_Invalid)
771 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
773 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
775 return TokError("invalid modifier '" + getTok().getIdentifier() +
776 "' (no symbols present)");
784 // Try to constant fold it up front, if possible.
786 if (Res->EvaluateAsAbsolute(Value))
787 Res = MCConstantExpr::Create(Value, getContext());
792 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
794 return ParseParenExpr(Res, EndLoc) ||
795 ParseBinOpRHS(1, Res, EndLoc);
798 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
801 SMLoc StartLoc = Lexer.getLoc();
802 if (ParseExpression(Expr))
805 if (!Expr->EvaluateAsAbsolute(Res))
806 return Error(StartLoc, "expected absolute expression");
811 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
812 MCBinaryExpr::Opcode &Kind) {
815 return 0; // not a binop.
817 // Lowest Precedence: &&, ||
818 case AsmToken::AmpAmp:
819 Kind = MCBinaryExpr::LAnd;
821 case AsmToken::PipePipe:
822 Kind = MCBinaryExpr::LOr;
826 // Low Precedence: |, &, ^
828 // FIXME: gas seems to support '!' as an infix operator?
830 Kind = MCBinaryExpr::Or;
832 case AsmToken::Caret:
833 Kind = MCBinaryExpr::Xor;
836 Kind = MCBinaryExpr::And;
839 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
840 case AsmToken::EqualEqual:
841 Kind = MCBinaryExpr::EQ;
843 case AsmToken::ExclaimEqual:
844 case AsmToken::LessGreater:
845 Kind = MCBinaryExpr::NE;
848 Kind = MCBinaryExpr::LT;
850 case AsmToken::LessEqual:
851 Kind = MCBinaryExpr::LTE;
853 case AsmToken::Greater:
854 Kind = MCBinaryExpr::GT;
856 case AsmToken::GreaterEqual:
857 Kind = MCBinaryExpr::GTE;
860 // Intermediate Precedence: <<, >>
861 case AsmToken::LessLess:
862 Kind = MCBinaryExpr::Shl;
864 case AsmToken::GreaterGreater:
865 Kind = MCBinaryExpr::Shr;
868 // High Intermediate Precedence: +, -
870 Kind = MCBinaryExpr::Add;
872 case AsmToken::Minus:
873 Kind = MCBinaryExpr::Sub;
876 // Highest Precedence: *, /, %
878 Kind = MCBinaryExpr::Mul;
880 case AsmToken::Slash:
881 Kind = MCBinaryExpr::Div;
883 case AsmToken::Percent:
884 Kind = MCBinaryExpr::Mod;
890 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
891 /// Res contains the LHS of the expression on input.
892 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
895 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
896 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
898 // If the next token is lower precedence than we are allowed to eat, return
899 // successfully with what we ate already.
900 if (TokPrec < Precedence)
905 // Eat the next primary expression.
907 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
909 // If BinOp binds less tightly with RHS than the operator after RHS, let
910 // the pending operator take RHS as its LHS.
911 MCBinaryExpr::Opcode Dummy;
912 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
913 if (TokPrec < NextTokPrec) {
914 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
917 // Merge LHS and RHS according to operator.
918 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
926 /// ::= EndOfStatement
927 /// ::= Label* Directive ...Operands... EndOfStatement
928 /// ::= Label* Identifier OperandList* EndOfStatement
929 bool AsmParser::ParseStatement() {
930 if (Lexer.is(AsmToken::EndOfStatement)) {
936 // Statements always start with an identifier or are a full line comment.
937 AsmToken ID = getTok();
938 SMLoc IDLoc = ID.getLoc();
940 int64_t LocalLabelVal = -1;
941 // A full line comment is a '#' as the first token.
942 if (Lexer.is(AsmToken::Hash))
943 return ParseCppHashLineFilenameComment(IDLoc);
945 // Allow an integer followed by a ':' as a directional local label.
946 if (Lexer.is(AsmToken::Integer)) {
947 LocalLabelVal = getTok().getIntVal();
948 if (LocalLabelVal < 0) {
949 if (!TheCondState.Ignore)
950 return TokError("unexpected token at start of statement");
954 IDVal = getTok().getString();
955 Lex(); // Consume the integer token to be used as an identifier token.
956 if (Lexer.getKind() != AsmToken::Colon) {
957 if (!TheCondState.Ignore)
958 return TokError("unexpected token at start of statement");
962 } else if (Lexer.is(AsmToken::Dot)) {
963 // Treat '.' as a valid identifier in this context.
967 } else if (ParseIdentifier(IDVal)) {
968 if (!TheCondState.Ignore)
969 return TokError("unexpected token at start of statement");
974 // Handle conditional assembly here before checking for skipping. We
975 // have to do this so that .endif isn't skipped in a ".if 0" block for
978 return ParseDirectiveIf(IDLoc);
979 if (IDVal == ".ifdef")
980 return ParseDirectiveIfdef(IDLoc, true);
981 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
982 return ParseDirectiveIfdef(IDLoc, false);
983 if (IDVal == ".elseif")
984 return ParseDirectiveElseIf(IDLoc);
985 if (IDVal == ".else")
986 return ParseDirectiveElse(IDLoc);
987 if (IDVal == ".endif")
988 return ParseDirectiveEndIf(IDLoc);
990 // If we are in a ".if 0" block, ignore this statement.
991 if (TheCondState.Ignore) {
992 EatToEndOfStatement();
996 // FIXME: Recurse on local labels?
998 // See what kind of statement we have.
999 switch (Lexer.getKind()) {
1000 case AsmToken::Colon: {
1001 CheckForValidSection();
1003 // identifier ':' -> Label.
1006 // Diagnose attempt to use '.' as a label.
1008 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1010 // Diagnose attempt to use a variable as a label.
1012 // FIXME: Diagnostics. Note the location of the definition as a label.
1013 // FIXME: This doesn't diagnose assignment to a symbol which has been
1014 // implicitly marked as external.
1016 if (LocalLabelVal == -1)
1017 Sym = getContext().GetOrCreateSymbol(IDVal);
1019 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1020 if (!Sym->isUndefined() || Sym->isVariable())
1021 return Error(IDLoc, "invalid symbol redefinition");
1026 // Consume any end of statement token, if present, to avoid spurious
1027 // AddBlankLine calls().
1028 if (Lexer.is(AsmToken::EndOfStatement)) {
1030 if (Lexer.is(AsmToken::Eof))
1034 return ParseStatement();
1037 case AsmToken::Equal:
1038 // identifier '=' ... -> assignment statement
1041 return ParseAssignment(IDVal, true);
1043 default: // Normal instruction or directive.
1047 // If macros are enabled, check to see if this is a macro instantiation.
1049 if (const Macro *M = MacroMap.lookup(IDVal))
1050 return HandleMacroEntry(IDVal, IDLoc, M);
1052 // Otherwise, we have a normal instruction or directive.
1053 if (IDVal[0] == '.' && IDVal != ".") {
1054 // Assembler features
1055 if (IDVal == ".set" || IDVal == ".equ")
1056 return ParseDirectiveSet(IDVal, true);
1057 if (IDVal == ".equiv")
1058 return ParseDirectiveSet(IDVal, false);
1062 if (IDVal == ".ascii")
1063 return ParseDirectiveAscii(IDVal, false);
1064 if (IDVal == ".asciz" || IDVal == ".string")
1065 return ParseDirectiveAscii(IDVal, true);
1067 if (IDVal == ".byte")
1068 return ParseDirectiveValue(1);
1069 if (IDVal == ".short")
1070 return ParseDirectiveValue(2);
1071 if (IDVal == ".value")
1072 return ParseDirectiveValue(2);
1073 if (IDVal == ".2byte")
1074 return ParseDirectiveValue(2);
1075 if (IDVal == ".long")
1076 return ParseDirectiveValue(4);
1077 if (IDVal == ".int")
1078 return ParseDirectiveValue(4);
1079 if (IDVal == ".4byte")
1080 return ParseDirectiveValue(4);
1081 if (IDVal == ".quad")
1082 return ParseDirectiveValue(8);
1083 if (IDVal == ".8byte")
1084 return ParseDirectiveValue(8);
1085 if (IDVal == ".single" || IDVal == ".float")
1086 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1087 if (IDVal == ".double")
1088 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1090 if (IDVal == ".align") {
1091 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1092 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1094 if (IDVal == ".align32") {
1095 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1096 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1098 if (IDVal == ".balign")
1099 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1100 if (IDVal == ".balignw")
1101 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1102 if (IDVal == ".balignl")
1103 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1104 if (IDVal == ".p2align")
1105 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1106 if (IDVal == ".p2alignw")
1107 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1108 if (IDVal == ".p2alignl")
1109 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1111 if (IDVal == ".org")
1112 return ParseDirectiveOrg();
1114 if (IDVal == ".fill")
1115 return ParseDirectiveFill();
1116 if (IDVal == ".space" || IDVal == ".skip")
1117 return ParseDirectiveSpace();
1118 if (IDVal == ".zero")
1119 return ParseDirectiveZero();
1121 // Symbol attribute directives
1123 if (IDVal == ".globl" || IDVal == ".global")
1124 return ParseDirectiveSymbolAttribute(MCSA_Global);
1125 if (IDVal == ".indirect_symbol")
1126 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1127 if (IDVal == ".lazy_reference")
1128 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1129 if (IDVal == ".no_dead_strip")
1130 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1131 if (IDVal == ".symbol_resolver")
1132 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1133 if (IDVal == ".private_extern")
1134 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1135 if (IDVal == ".reference")
1136 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1137 if (IDVal == ".weak_definition")
1138 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1139 if (IDVal == ".weak_reference")
1140 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1141 if (IDVal == ".weak_def_can_be_hidden")
1142 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1144 if (IDVal == ".comm" || IDVal == ".common")
1145 return ParseDirectiveComm(/*IsLocal=*/false);
1146 if (IDVal == ".lcomm")
1147 return ParseDirectiveComm(/*IsLocal=*/true);
1149 if (IDVal == ".abort")
1150 return ParseDirectiveAbort();
1151 if (IDVal == ".include")
1152 return ParseDirectiveInclude();
1154 if (IDVal == ".code16")
1155 return TokError(Twine(IDVal) + " not supported yet");
1157 // Look up the handler in the handler table.
1158 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1159 DirectiveMap.lookup(IDVal);
1161 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1163 // Target hook for parsing target specific directives.
1164 if (!getTargetParser().ParseDirective(ID))
1167 bool retval = Warning(IDLoc, "ignoring directive for now");
1168 EatToEndOfStatement();
1172 CheckForValidSection();
1174 // Canonicalize the opcode to lower case.
1175 SmallString<128> Opcode;
1176 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1177 Opcode.push_back(tolower(IDVal[i]));
1179 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1180 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1183 // Dump the parsed representation, if requested.
1184 if (getShowParsedOperands()) {
1185 SmallString<256> Str;
1186 raw_svector_ostream OS(Str);
1187 OS << "parsed instruction: [";
1188 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1191 ParsedOperands[i]->print(OS);
1195 PrintMessage(IDLoc, OS.str(), "note");
1198 // If parsing succeeded, match the instruction.
1200 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1203 // Free any parsed operands.
1204 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1205 delete ParsedOperands[i];
1207 // Don't skip the rest of the line, the instruction parser is responsible for
1212 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1213 /// since they may not be able to be tokenized to get to the end of line token.
1214 void AsmParser::EatToEndOfLine() {
1215 Lexer.LexUntilEndOfLine();
1220 /// ParseCppHashLineFilenameComment as this:
1221 /// ::= # number "filename"
1222 /// or just as a full line comment if it doesn't have a number and a string.
1223 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1224 Lex(); // Eat the hash token.
1226 if (getLexer().isNot(AsmToken::Integer)) {
1227 // Consume the line since in cases it is not a well-formed line directive,
1228 // as if were simply a full line comment.
1233 int64_t LineNumber = getTok().getIntVal();
1234 // FIXME: remember to remove this line that is silencing a warning for now.
1238 if (getLexer().isNot(AsmToken::String)) {
1243 StringRef Filename = getTok().getString();
1244 // Get rid of the enclosing quotes.
1245 Filename = Filename.substr(1, Filename.size()-2);
1247 // TODO: Now with the Filename, LineNumber set up a mapping to the SMLoc for
1248 // later use by diagnostics.
1250 // Ignore any trailing characters, they're just comment.
1255 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1256 const std::vector<StringRef> &Parameters,
1257 const std::vector<std::vector<AsmToken> > &A,
1259 raw_svector_ostream OS(Buf);
1260 unsigned NParameters = Parameters.size();
1261 if (NParameters != 0 && NParameters != A.size())
1262 return Error(L, "Wrong number of arguments");
1264 while (!Body.empty()) {
1265 // Scan for the next substitution.
1266 std::size_t End = Body.size(), Pos = 0;
1267 for (; Pos != End; ++Pos) {
1268 // Check for a substitution or escape.
1270 // This macro has no parameters, look for $0, $1, etc.
1271 if (Body[Pos] != '$' || Pos + 1 == End)
1274 char Next = Body[Pos + 1];
1275 if (Next == '$' || Next == 'n' || isdigit(Next))
1278 // This macro has parameters, look for \foo, \bar, etc.
1279 if (Body[Pos] == '\\' && Pos + 1 != End)
1285 OS << Body.slice(0, Pos);
1287 // Check if we reached the end.
1292 switch (Body[Pos+1]) {
1298 // $n => number of arguments
1303 // $[0-9] => argument
1305 // Missing arguments are ignored.
1306 unsigned Index = Body[Pos+1] - '0';
1307 if (Index >= A.size())
1310 // Otherwise substitute with the token values, with spaces eliminated.
1311 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1312 ie = A[Index].end(); it != ie; ++it)
1313 OS << it->getString();
1319 unsigned I = Pos + 1;
1320 while (isalnum(Body[I]) && I + 1 != End)
1323 const char *Begin = Body.data() + Pos +1;
1324 StringRef Argument(Begin, I - (Pos +1));
1326 for (; Index < NParameters; ++Index)
1327 if (Parameters[Index] == Argument)
1330 // FIXME: We should error at the macro definition.
1331 if (Index == NParameters)
1332 return Error(L, "Parameter not found");
1334 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1335 ie = A[Index].end(); it != ie; ++it)
1336 OS << it->getString();
1338 Pos += 1 + Argument.size();
1340 // Update the scan point.
1341 Body = Body.substr(Pos);
1344 // We include the .endmacro in the buffer as our queue to exit the macro
1346 OS << ".endmacro\n";
1350 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1352 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1356 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1358 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1359 // this, although we should protect against infinite loops.
1360 if (ActiveMacros.size() == 20)
1361 return TokError("macros cannot be nested more than 20 levels deep");
1363 // Parse the macro instantiation arguments.
1364 std::vector<std::vector<AsmToken> > MacroArguments;
1365 MacroArguments.push_back(std::vector<AsmToken>());
1366 unsigned ParenLevel = 0;
1368 if (Lexer.is(AsmToken::Eof))
1369 return TokError("unexpected token in macro instantiation");
1370 if (Lexer.is(AsmToken::EndOfStatement))
1373 // If we aren't inside parentheses and this is a comma, start a new token
1375 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1376 MacroArguments.push_back(std::vector<AsmToken>());
1378 // Adjust the current parentheses level.
1379 if (Lexer.is(AsmToken::LParen))
1381 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1384 // Append the token to the current argument list.
1385 MacroArguments.back().push_back(getTok());
1390 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1391 // to hold the macro body with substitutions.
1392 SmallString<256> Buf;
1393 StringRef Body = M->Body;
1395 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1398 MemoryBuffer *Instantiation =
1399 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1401 // Create the macro instantiation object and add to the current macro
1402 // instantiation stack.
1403 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1406 ActiveMacros.push_back(MI);
1408 // Jump to the macro instantiation and prime the lexer.
1409 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1410 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1416 void AsmParser::HandleMacroExit() {
1417 // Jump to the EndOfStatement we should return to, and consume it.
1418 JumpToLoc(ActiveMacros.back()->ExitLoc);
1421 // Pop the instantiation entry.
1422 delete ActiveMacros.back();
1423 ActiveMacros.pop_back();
1426 static void MarkUsed(const MCExpr *Value) {
1427 switch (Value->getKind()) {
1428 case MCExpr::Binary:
1429 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1430 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1432 case MCExpr::Target:
1433 case MCExpr::Constant:
1435 case MCExpr::SymbolRef: {
1436 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1440 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1445 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1446 // FIXME: Use better location, we should use proper tokens.
1447 SMLoc EqualLoc = Lexer.getLoc();
1449 const MCExpr *Value;
1450 if (ParseExpression(Value))
1455 if (Lexer.isNot(AsmToken::EndOfStatement))
1456 return TokError("unexpected token in assignment");
1458 // Error on assignment to '.'.
1460 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1461 "(use '.space' or '.org').)"));
1464 // Eat the end of statement marker.
1467 // Validate that the LHS is allowed to be a variable (either it has not been
1468 // used as a symbol, or it is an absolute symbol).
1469 MCSymbol *Sym = getContext().LookupSymbol(Name);
1471 // Diagnose assignment to a label.
1473 // FIXME: Diagnostics. Note the location of the definition as a label.
1474 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1475 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1476 ; // Allow redefinitions of undefined symbols only used in directives.
1477 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1478 return Error(EqualLoc, "redefinition of '" + Name + "'");
1479 else if (!Sym->isVariable())
1480 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1481 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1482 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1485 // Don't count these checks as uses.
1486 Sym->setUsed(false);
1488 Sym = getContext().GetOrCreateSymbol(Name);
1490 // FIXME: Handle '.'.
1492 // Do the assignment.
1493 Out.EmitAssignment(Sym, Value);
1498 /// ParseIdentifier:
1501 bool AsmParser::ParseIdentifier(StringRef &Res) {
1502 // The assembler has relaxed rules for accepting identifiers, in particular we
1503 // allow things like '.globl $foo', which would normally be separate
1504 // tokens. At this level, we have already lexed so we cannot (currently)
1505 // handle this as a context dependent token, instead we detect adjacent tokens
1506 // and return the combined identifier.
1507 if (Lexer.is(AsmToken::Dollar)) {
1508 SMLoc DollarLoc = getLexer().getLoc();
1510 // Consume the dollar sign, and check for a following identifier.
1512 if (Lexer.isNot(AsmToken::Identifier))
1515 // We have a '$' followed by an identifier, make sure they are adjacent.
1516 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1519 // Construct the joined identifier and consume the token.
1520 Res = StringRef(DollarLoc.getPointer(),
1521 getTok().getIdentifier().size() + 1);
1526 if (Lexer.isNot(AsmToken::Identifier) &&
1527 Lexer.isNot(AsmToken::String))
1530 Res = getTok().getIdentifier();
1532 Lex(); // Consume the identifier token.
1537 /// ParseDirectiveSet:
1538 /// ::= .equ identifier ',' expression
1539 /// ::= .equiv identifier ',' expression
1540 /// ::= .set identifier ',' expression
1541 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1544 if (ParseIdentifier(Name))
1545 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1547 if (getLexer().isNot(AsmToken::Comma))
1548 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1551 return ParseAssignment(Name, allow_redef);
1554 bool AsmParser::ParseEscapedString(std::string &Data) {
1555 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1558 StringRef Str = getTok().getStringContents();
1559 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1560 if (Str[i] != '\\') {
1565 // Recognize escaped characters. Note that this escape semantics currently
1566 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1569 return TokError("unexpected backslash at end of string");
1571 // Recognize octal sequences.
1572 if ((unsigned) (Str[i] - '0') <= 7) {
1573 // Consume up to three octal characters.
1574 unsigned Value = Str[i] - '0';
1576 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1578 Value = Value * 8 + (Str[i] - '0');
1580 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1582 Value = Value * 8 + (Str[i] - '0');
1587 return TokError("invalid octal escape sequence (out of range)");
1589 Data += (unsigned char) Value;
1593 // Otherwise recognize individual escapes.
1596 // Just reject invalid escape sequences for now.
1597 return TokError("invalid escape sequence (unrecognized character)");
1599 case 'b': Data += '\b'; break;
1600 case 'f': Data += '\f'; break;
1601 case 'n': Data += '\n'; break;
1602 case 'r': Data += '\r'; break;
1603 case 't': Data += '\t'; break;
1604 case '"': Data += '"'; break;
1605 case '\\': Data += '\\'; break;
1612 /// ParseDirectiveAscii:
1613 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1614 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1615 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1616 CheckForValidSection();
1619 if (getLexer().isNot(AsmToken::String))
1620 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1623 if (ParseEscapedString(Data))
1626 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1628 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1632 if (getLexer().is(AsmToken::EndOfStatement))
1635 if (getLexer().isNot(AsmToken::Comma))
1636 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1645 /// ParseDirectiveValue
1646 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1647 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1648 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1649 CheckForValidSection();
1652 const MCExpr *Value;
1653 SMLoc ExprLoc = getLexer().getLoc();
1654 if (ParseExpression(Value))
1657 // Special case constant expressions to match code generator.
1658 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1659 assert(Size <= 8 && "Invalid size");
1660 uint64_t IntValue = MCE->getValue();
1661 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1662 return Error(ExprLoc, "literal value out of range for directive");
1663 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1665 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1667 if (getLexer().is(AsmToken::EndOfStatement))
1670 // FIXME: Improve diagnostic.
1671 if (getLexer().isNot(AsmToken::Comma))
1672 return TokError("unexpected token in directive");
1681 /// ParseDirectiveRealValue
1682 /// ::= (.single | .double) [ expression (, expression)* ]
1683 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1684 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1685 CheckForValidSection();
1688 // We don't truly support arithmetic on floating point expressions, so we
1689 // have to manually parse unary prefixes.
1691 if (getLexer().is(AsmToken::Minus)) {
1694 } else if (getLexer().is(AsmToken::Plus))
1697 if (getLexer().isNot(AsmToken::Integer) &&
1698 getLexer().isNot(AsmToken::Real) &&
1699 getLexer().isNot(AsmToken::Identifier))
1700 return TokError("unexpected token in directive");
1702 // Convert to an APFloat.
1703 APFloat Value(Semantics);
1704 StringRef IDVal = getTok().getString();
1705 if (getLexer().is(AsmToken::Identifier)) {
1706 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1707 Value = APFloat::getInf(Semantics);
1708 else if (!IDVal.compare_lower("nan"))
1709 Value = APFloat::getNaN(Semantics, false, ~0);
1711 return TokError("invalid floating point literal");
1712 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1713 APFloat::opInvalidOp)
1714 return TokError("invalid floating point literal");
1718 // Consume the numeric token.
1721 // Emit the value as an integer.
1722 APInt AsInt = Value.bitcastToAPInt();
1723 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1724 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1726 if (getLexer().is(AsmToken::EndOfStatement))
1729 if (getLexer().isNot(AsmToken::Comma))
1730 return TokError("unexpected token in directive");
1739 /// ParseDirectiveSpace
1740 /// ::= .space expression [ , expression ]
1741 bool AsmParser::ParseDirectiveSpace() {
1742 CheckForValidSection();
1745 if (ParseAbsoluteExpression(NumBytes))
1748 int64_t FillExpr = 0;
1749 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1750 if (getLexer().isNot(AsmToken::Comma))
1751 return TokError("unexpected token in '.space' directive");
1754 if (ParseAbsoluteExpression(FillExpr))
1757 if (getLexer().isNot(AsmToken::EndOfStatement))
1758 return TokError("unexpected token in '.space' directive");
1764 return TokError("invalid number of bytes in '.space' directive");
1766 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1767 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1772 /// ParseDirectiveZero
1773 /// ::= .zero expression
1774 bool AsmParser::ParseDirectiveZero() {
1775 CheckForValidSection();
1778 if (ParseAbsoluteExpression(NumBytes))
1782 if (getLexer().is(AsmToken::Comma)) {
1784 if (ParseAbsoluteExpression(Val))
1788 if (getLexer().isNot(AsmToken::EndOfStatement))
1789 return TokError("unexpected token in '.zero' directive");
1793 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1798 /// ParseDirectiveFill
1799 /// ::= .fill expression , expression , expression
1800 bool AsmParser::ParseDirectiveFill() {
1801 CheckForValidSection();
1804 if (ParseAbsoluteExpression(NumValues))
1807 if (getLexer().isNot(AsmToken::Comma))
1808 return TokError("unexpected token in '.fill' directive");
1812 if (ParseAbsoluteExpression(FillSize))
1815 if (getLexer().isNot(AsmToken::Comma))
1816 return TokError("unexpected token in '.fill' directive");
1820 if (ParseAbsoluteExpression(FillExpr))
1823 if (getLexer().isNot(AsmToken::EndOfStatement))
1824 return TokError("unexpected token in '.fill' directive");
1828 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1829 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1831 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1832 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1837 /// ParseDirectiveOrg
1838 /// ::= .org expression [ , expression ]
1839 bool AsmParser::ParseDirectiveOrg() {
1840 CheckForValidSection();
1842 const MCExpr *Offset;
1843 if (ParseExpression(Offset))
1846 // Parse optional fill expression.
1847 int64_t FillExpr = 0;
1848 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1849 if (getLexer().isNot(AsmToken::Comma))
1850 return TokError("unexpected token in '.org' directive");
1853 if (ParseAbsoluteExpression(FillExpr))
1856 if (getLexer().isNot(AsmToken::EndOfStatement))
1857 return TokError("unexpected token in '.org' directive");
1862 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1863 // has to be relative to the current section.
1864 getStreamer().EmitValueToOffset(Offset, FillExpr);
1869 /// ParseDirectiveAlign
1870 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1871 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1872 CheckForValidSection();
1874 SMLoc AlignmentLoc = getLexer().getLoc();
1876 if (ParseAbsoluteExpression(Alignment))
1880 bool HasFillExpr = false;
1881 int64_t FillExpr = 0;
1882 int64_t MaxBytesToFill = 0;
1883 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1884 if (getLexer().isNot(AsmToken::Comma))
1885 return TokError("unexpected token in directive");
1888 // The fill expression can be omitted while specifying a maximum number of
1889 // alignment bytes, e.g:
1891 if (getLexer().isNot(AsmToken::Comma)) {
1893 if (ParseAbsoluteExpression(FillExpr))
1897 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1898 if (getLexer().isNot(AsmToken::Comma))
1899 return TokError("unexpected token in directive");
1902 MaxBytesLoc = getLexer().getLoc();
1903 if (ParseAbsoluteExpression(MaxBytesToFill))
1906 if (getLexer().isNot(AsmToken::EndOfStatement))
1907 return TokError("unexpected token in directive");
1916 // Compute alignment in bytes.
1918 // FIXME: Diagnose overflow.
1919 if (Alignment >= 32) {
1920 Error(AlignmentLoc, "invalid alignment value");
1924 Alignment = 1ULL << Alignment;
1927 // Diagnose non-sensical max bytes to align.
1928 if (MaxBytesLoc.isValid()) {
1929 if (MaxBytesToFill < 1) {
1930 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1931 "many bytes, ignoring maximum bytes expression");
1935 if (MaxBytesToFill >= Alignment) {
1936 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1942 // Check whether we should use optimal code alignment for this .align
1944 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1945 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1946 ValueSize == 1 && UseCodeAlign) {
1947 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1949 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1950 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1957 /// ParseDirectiveSymbolAttribute
1958 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1959 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1960 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1963 SMLoc Loc = getTok().getLoc();
1965 if (ParseIdentifier(Name))
1966 return Error(Loc, "expected identifier in directive");
1968 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1970 // Assembler local symbols don't make any sense here. Complain loudly.
1971 if (Sym->isTemporary())
1972 return Error(Loc, "non-local symbol required in directive");
1974 getStreamer().EmitSymbolAttribute(Sym, Attr);
1976 if (getLexer().is(AsmToken::EndOfStatement))
1979 if (getLexer().isNot(AsmToken::Comma))
1980 return TokError("unexpected token in directive");
1989 /// ParseDirectiveComm
1990 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1991 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1992 CheckForValidSection();
1994 SMLoc IDLoc = getLexer().getLoc();
1996 if (ParseIdentifier(Name))
1997 return TokError("expected identifier in directive");
1999 // Handle the identifier as the key symbol.
2000 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2002 if (getLexer().isNot(AsmToken::Comma))
2003 return TokError("unexpected token in directive");
2007 SMLoc SizeLoc = getLexer().getLoc();
2008 if (ParseAbsoluteExpression(Size))
2011 int64_t Pow2Alignment = 0;
2012 SMLoc Pow2AlignmentLoc;
2013 if (getLexer().is(AsmToken::Comma)) {
2015 Pow2AlignmentLoc = getLexer().getLoc();
2016 if (ParseAbsoluteExpression(Pow2Alignment))
2019 // If this target takes alignments in bytes (not log) validate and convert.
2020 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2021 if (!isPowerOf2_64(Pow2Alignment))
2022 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2023 Pow2Alignment = Log2_64(Pow2Alignment);
2027 if (getLexer().isNot(AsmToken::EndOfStatement))
2028 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2032 // NOTE: a size of zero for a .comm should create a undefined symbol
2033 // but a size of .lcomm creates a bss symbol of size zero.
2035 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2036 "be less than zero");
2038 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2039 // may internally end up wanting an alignment in bytes.
2040 // FIXME: Diagnose overflow.
2041 if (Pow2Alignment < 0)
2042 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2043 "alignment, can't be less than zero");
2045 if (!Sym->isUndefined())
2046 return Error(IDLoc, "invalid symbol redefinition");
2048 // '.lcomm' is equivalent to '.zerofill'.
2049 // Create the Symbol as a common or local common with Size and Pow2Alignment
2051 getStreamer().EmitZerofill(Ctx.getMachOSection(
2052 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2053 0, SectionKind::getBSS()),
2054 Sym, Size, 1 << Pow2Alignment);
2058 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2062 /// ParseDirectiveAbort
2063 /// ::= .abort [... message ...]
2064 bool AsmParser::ParseDirectiveAbort() {
2065 // FIXME: Use loc from directive.
2066 SMLoc Loc = getLexer().getLoc();
2068 StringRef Str = ParseStringToEndOfStatement();
2069 if (getLexer().isNot(AsmToken::EndOfStatement))
2070 return TokError("unexpected token in '.abort' directive");
2075 Error(Loc, ".abort detected. Assembly stopping.");
2077 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2078 // FIXME: Actually abort assembly here.
2083 /// ParseDirectiveInclude
2084 /// ::= .include "filename"
2085 bool AsmParser::ParseDirectiveInclude() {
2086 if (getLexer().isNot(AsmToken::String))
2087 return TokError("expected string in '.include' directive");
2089 std::string Filename = getTok().getString();
2090 SMLoc IncludeLoc = getLexer().getLoc();
2093 if (getLexer().isNot(AsmToken::EndOfStatement))
2094 return TokError("unexpected token in '.include' directive");
2096 // Strip the quotes.
2097 Filename = Filename.substr(1, Filename.size()-2);
2099 // Attempt to switch the lexer to the included file before consuming the end
2100 // of statement to avoid losing it when we switch.
2101 if (EnterIncludeFile(Filename)) {
2102 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2109 /// ParseDirectiveIf
2110 /// ::= .if expression
2111 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2112 TheCondStack.push_back(TheCondState);
2113 TheCondState.TheCond = AsmCond::IfCond;
2114 if(TheCondState.Ignore) {
2115 EatToEndOfStatement();
2119 if (ParseAbsoluteExpression(ExprValue))
2122 if (getLexer().isNot(AsmToken::EndOfStatement))
2123 return TokError("unexpected token in '.if' directive");
2127 TheCondState.CondMet = ExprValue;
2128 TheCondState.Ignore = !TheCondState.CondMet;
2134 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2136 TheCondStack.push_back(TheCondState);
2137 TheCondState.TheCond = AsmCond::IfCond;
2139 if (TheCondState.Ignore) {
2140 EatToEndOfStatement();
2142 if (ParseIdentifier(Name))
2143 return TokError("expected identifier after '.ifdef'");
2147 MCSymbol *Sym = getContext().LookupSymbol(Name);
2150 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2152 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2153 TheCondState.Ignore = !TheCondState.CondMet;
2159 /// ParseDirectiveElseIf
2160 /// ::= .elseif expression
2161 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2162 if (TheCondState.TheCond != AsmCond::IfCond &&
2163 TheCondState.TheCond != AsmCond::ElseIfCond)
2164 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2166 TheCondState.TheCond = AsmCond::ElseIfCond;
2168 bool LastIgnoreState = false;
2169 if (!TheCondStack.empty())
2170 LastIgnoreState = TheCondStack.back().Ignore;
2171 if (LastIgnoreState || TheCondState.CondMet) {
2172 TheCondState.Ignore = true;
2173 EatToEndOfStatement();
2177 if (ParseAbsoluteExpression(ExprValue))
2180 if (getLexer().isNot(AsmToken::EndOfStatement))
2181 return TokError("unexpected token in '.elseif' directive");
2184 TheCondState.CondMet = ExprValue;
2185 TheCondState.Ignore = !TheCondState.CondMet;
2191 /// ParseDirectiveElse
2193 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2194 if (getLexer().isNot(AsmToken::EndOfStatement))
2195 return TokError("unexpected token in '.else' directive");
2199 if (TheCondState.TheCond != AsmCond::IfCond &&
2200 TheCondState.TheCond != AsmCond::ElseIfCond)
2201 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2203 TheCondState.TheCond = AsmCond::ElseCond;
2204 bool LastIgnoreState = false;
2205 if (!TheCondStack.empty())
2206 LastIgnoreState = TheCondStack.back().Ignore;
2207 if (LastIgnoreState || TheCondState.CondMet)
2208 TheCondState.Ignore = true;
2210 TheCondState.Ignore = false;
2215 /// ParseDirectiveEndIf
2217 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2218 if (getLexer().isNot(AsmToken::EndOfStatement))
2219 return TokError("unexpected token in '.endif' directive");
2223 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2224 TheCondStack.empty())
2225 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2227 if (!TheCondStack.empty()) {
2228 TheCondState = TheCondStack.back();
2229 TheCondStack.pop_back();
2235 /// ParseDirectiveFile
2236 /// ::= .file [number] string
2237 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2238 // FIXME: I'm not sure what this is.
2239 int64_t FileNumber = -1;
2240 SMLoc FileNumberLoc = getLexer().getLoc();
2241 if (getLexer().is(AsmToken::Integer)) {
2242 FileNumber = getTok().getIntVal();
2246 return TokError("file number less than one");
2249 if (getLexer().isNot(AsmToken::String))
2250 return TokError("unexpected token in '.file' directive");
2252 StringRef Filename = getTok().getString();
2253 Filename = Filename.substr(1, Filename.size()-2);
2256 if (getLexer().isNot(AsmToken::EndOfStatement))
2257 return TokError("unexpected token in '.file' directive");
2259 if (FileNumber == -1)
2260 getStreamer().EmitFileDirective(Filename);
2262 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2263 Error(FileNumberLoc, "file number already allocated");
2269 /// ParseDirectiveLine
2270 /// ::= .line [number]
2271 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2272 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2273 if (getLexer().isNot(AsmToken::Integer))
2274 return TokError("unexpected token in '.line' directive");
2276 int64_t LineNumber = getTok().getIntVal();
2280 // FIXME: Do something with the .line.
2283 if (getLexer().isNot(AsmToken::EndOfStatement))
2284 return TokError("unexpected token in '.line' directive");
2290 /// ParseDirectiveLoc
2291 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2292 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2293 /// The first number is a file number, must have been previously assigned with
2294 /// a .file directive, the second number is the line number and optionally the
2295 /// third number is a column position (zero if not specified). The remaining
2296 /// optional items are .loc sub-directives.
2297 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2299 if (getLexer().isNot(AsmToken::Integer))
2300 return TokError("unexpected token in '.loc' directive");
2301 int64_t FileNumber = getTok().getIntVal();
2303 return TokError("file number less than one in '.loc' directive");
2304 if (!getContext().isValidDwarfFileNumber(FileNumber))
2305 return TokError("unassigned file number in '.loc' directive");
2308 int64_t LineNumber = 0;
2309 if (getLexer().is(AsmToken::Integer)) {
2310 LineNumber = getTok().getIntVal();
2312 return TokError("line number less than one in '.loc' directive");
2316 int64_t ColumnPos = 0;
2317 if (getLexer().is(AsmToken::Integer)) {
2318 ColumnPos = getTok().getIntVal();
2320 return TokError("column position less than zero in '.loc' directive");
2324 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2326 int64_t Discriminator = 0;
2327 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2329 if (getLexer().is(AsmToken::EndOfStatement))
2333 SMLoc Loc = getTok().getLoc();
2334 if (getParser().ParseIdentifier(Name))
2335 return TokError("unexpected token in '.loc' directive");
2337 if (Name == "basic_block")
2338 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2339 else if (Name == "prologue_end")
2340 Flags |= DWARF2_FLAG_PROLOGUE_END;
2341 else if (Name == "epilogue_begin")
2342 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2343 else if (Name == "is_stmt") {
2344 SMLoc Loc = getTok().getLoc();
2345 const MCExpr *Value;
2346 if (getParser().ParseExpression(Value))
2348 // The expression must be the constant 0 or 1.
2349 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2350 int Value = MCE->getValue();
2352 Flags &= ~DWARF2_FLAG_IS_STMT;
2353 else if (Value == 1)
2354 Flags |= DWARF2_FLAG_IS_STMT;
2356 return Error(Loc, "is_stmt value not 0 or 1");
2359 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2362 else if (Name == "isa") {
2363 SMLoc Loc = getTok().getLoc();
2364 const MCExpr *Value;
2365 if (getParser().ParseExpression(Value))
2367 // The expression must be a constant greater or equal to 0.
2368 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2369 int Value = MCE->getValue();
2371 return Error(Loc, "isa number less than zero");
2375 return Error(Loc, "isa number not a constant value");
2378 else if (Name == "discriminator") {
2379 if (getParser().ParseAbsoluteExpression(Discriminator))
2383 return Error(Loc, "unknown sub-directive in '.loc' directive");
2386 if (getLexer().is(AsmToken::EndOfStatement))
2391 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2392 Isa, Discriminator, StringRef());
2397 /// ParseDirectiveStabs
2398 /// ::= .stabs string, number, number, number
2399 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2400 SMLoc DirectiveLoc) {
2401 return TokError("unsupported directive '" + Directive + "'");
2404 /// ParseDirectiveCFISections
2405 /// ::= .cfi_sections section [, section]
2406 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2407 SMLoc DirectiveLoc) {
2412 if (getParser().ParseIdentifier(Name))
2413 return TokError("Expected an identifier");
2415 if (Name == ".eh_frame")
2417 else if (Name == ".debug_frame")
2420 if (getLexer().is(AsmToken::Comma)) {
2423 if (getParser().ParseIdentifier(Name))
2424 return TokError("Expected an identifier");
2426 if (Name == ".eh_frame")
2428 else if (Name == ".debug_frame")
2432 getStreamer().EmitCFISections(EH, Debug);
2437 /// ParseDirectiveCFIStartProc
2438 /// ::= .cfi_startproc
2439 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2440 SMLoc DirectiveLoc) {
2441 getStreamer().EmitCFIStartProc();
2445 /// ParseDirectiveCFIEndProc
2446 /// ::= .cfi_endproc
2447 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2448 getStreamer().EmitCFIEndProc();
2452 /// ParseRegisterOrRegisterNumber - parse register name or number.
2453 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2454 SMLoc DirectiveLoc) {
2457 if (getLexer().isNot(AsmToken::Integer)) {
2458 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2461 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2463 return getParser().ParseAbsoluteExpression(Register);
2468 /// ParseDirectiveCFIDefCfa
2469 /// ::= .cfi_def_cfa register, offset
2470 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2471 SMLoc DirectiveLoc) {
2472 int64_t Register = 0;
2473 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2476 if (getLexer().isNot(AsmToken::Comma))
2477 return TokError("unexpected token in directive");
2481 if (getParser().ParseAbsoluteExpression(Offset))
2484 getStreamer().EmitCFIDefCfa(Register, Offset);
2488 /// ParseDirectiveCFIDefCfaOffset
2489 /// ::= .cfi_def_cfa_offset offset
2490 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2491 SMLoc DirectiveLoc) {
2493 if (getParser().ParseAbsoluteExpression(Offset))
2496 getStreamer().EmitCFIDefCfaOffset(Offset);
2500 /// ParseDirectiveCFIAdjustCfaOffset
2501 /// ::= .cfi_adjust_cfa_offset adjustment
2502 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2503 SMLoc DirectiveLoc) {
2504 int64_t Adjustment = 0;
2505 if (getParser().ParseAbsoluteExpression(Adjustment))
2508 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2512 /// ParseDirectiveCFIDefCfaRegister
2513 /// ::= .cfi_def_cfa_register register
2514 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2515 SMLoc DirectiveLoc) {
2516 int64_t Register = 0;
2517 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2520 getStreamer().EmitCFIDefCfaRegister(Register);
2524 /// ParseDirectiveCFIOffset
2525 /// ::= .cfi_offset register, offset
2526 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2527 int64_t Register = 0;
2530 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2533 if (getLexer().isNot(AsmToken::Comma))
2534 return TokError("unexpected token in directive");
2537 if (getParser().ParseAbsoluteExpression(Offset))
2540 getStreamer().EmitCFIOffset(Register, Offset);
2544 /// ParseDirectiveCFIRelOffset
2545 /// ::= .cfi_rel_offset register, offset
2546 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2547 SMLoc DirectiveLoc) {
2548 int64_t Register = 0;
2550 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2553 if (getLexer().isNot(AsmToken::Comma))
2554 return TokError("unexpected token in directive");
2558 if (getParser().ParseAbsoluteExpression(Offset))
2561 getStreamer().EmitCFIRelOffset(Register, Offset);
2565 static bool isValidEncoding(int64_t Encoding) {
2566 if (Encoding & ~0xff)
2569 if (Encoding == dwarf::DW_EH_PE_omit)
2572 const unsigned Format = Encoding & 0xf;
2573 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2574 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2575 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2576 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2579 const unsigned Application = Encoding & 0x70;
2580 if (Application != dwarf::DW_EH_PE_absptr &&
2581 Application != dwarf::DW_EH_PE_pcrel)
2587 /// ParseDirectiveCFIPersonalityOrLsda
2588 /// ::= .cfi_personality encoding, [symbol_name]
2589 /// ::= .cfi_lsda encoding, [symbol_name]
2590 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2591 SMLoc DirectiveLoc) {
2592 int64_t Encoding = 0;
2593 if (getParser().ParseAbsoluteExpression(Encoding))
2595 if (Encoding == dwarf::DW_EH_PE_omit)
2598 if (!isValidEncoding(Encoding))
2599 return TokError("unsupported encoding.");
2601 if (getLexer().isNot(AsmToken::Comma))
2602 return TokError("unexpected token in directive");
2606 if (getParser().ParseIdentifier(Name))
2607 return TokError("expected identifier in directive");
2609 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2611 if (IDVal == ".cfi_personality")
2612 getStreamer().EmitCFIPersonality(Sym, Encoding);
2614 assert(IDVal == ".cfi_lsda");
2615 getStreamer().EmitCFILsda(Sym, Encoding);
2620 /// ParseDirectiveCFIRememberState
2621 /// ::= .cfi_remember_state
2622 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2623 SMLoc DirectiveLoc) {
2624 getStreamer().EmitCFIRememberState();
2628 /// ParseDirectiveCFIRestoreState
2629 /// ::= .cfi_remember_state
2630 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2631 SMLoc DirectiveLoc) {
2632 getStreamer().EmitCFIRestoreState();
2636 /// ParseDirectiveCFISameValue
2637 /// ::= .cfi_same_value register
2638 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2639 SMLoc DirectiveLoc) {
2640 int64_t Register = 0;
2642 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2645 getStreamer().EmitCFISameValue(Register);
2650 /// ParseDirectiveMacrosOnOff
2653 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2654 SMLoc DirectiveLoc) {
2655 if (getLexer().isNot(AsmToken::EndOfStatement))
2656 return Error(getLexer().getLoc(),
2657 "unexpected token in '" + Directive + "' directive");
2659 getParser().MacrosEnabled = Directive == ".macros_on";
2664 /// ParseDirectiveMacro
2665 /// ::= .macro name [parameters]
2666 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2667 SMLoc DirectiveLoc) {
2669 if (getParser().ParseIdentifier(Name))
2670 return TokError("expected identifier in directive");
2672 std::vector<StringRef> Parameters;
2673 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2675 StringRef Parameter;
2676 if (getParser().ParseIdentifier(Parameter))
2677 return TokError("expected identifier in directive");
2678 Parameters.push_back(Parameter);
2680 if (getLexer().isNot(AsmToken::Comma))
2686 if (getLexer().isNot(AsmToken::EndOfStatement))
2687 return TokError("unexpected token in '.macro' directive");
2689 // Eat the end of statement.
2692 AsmToken EndToken, StartToken = getTok();
2694 // Lex the macro definition.
2696 // Check whether we have reached the end of the file.
2697 if (getLexer().is(AsmToken::Eof))
2698 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2700 // Otherwise, check whether we have reach the .endmacro.
2701 if (getLexer().is(AsmToken::Identifier) &&
2702 (getTok().getIdentifier() == ".endm" ||
2703 getTok().getIdentifier() == ".endmacro")) {
2704 EndToken = getTok();
2706 if (getLexer().isNot(AsmToken::EndOfStatement))
2707 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2712 // Otherwise, scan til the end of the statement.
2713 getParser().EatToEndOfStatement();
2716 if (getParser().MacroMap.lookup(Name)) {
2717 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2720 const char *BodyStart = StartToken.getLoc().getPointer();
2721 const char *BodyEnd = EndToken.getLoc().getPointer();
2722 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2723 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2727 /// ParseDirectiveEndMacro
2730 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2731 SMLoc DirectiveLoc) {
2732 if (getLexer().isNot(AsmToken::EndOfStatement))
2733 return TokError("unexpected token in '" + Directive + "' directive");
2735 // If we are inside a macro instantiation, terminate the current
2737 if (!getParser().ActiveMacros.empty()) {
2738 getParser().HandleMacroExit();
2742 // Otherwise, this .endmacro is a stray entry in the file; well formed
2743 // .endmacro directives are handled during the macro definition parsing.
2744 return TokError("unexpected '" + Directive + "' in file, "
2745 "no current macro definition");
2748 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2749 getParser().CheckForValidSection();
2751 const MCExpr *Value;
2753 if (getParser().ParseExpression(Value))
2756 if (getLexer().isNot(AsmToken::EndOfStatement))
2757 return TokError("unexpected token in directive");
2759 if (DirName[1] == 's')
2760 getStreamer().EmitSLEB128Value(Value);
2762 getStreamer().EmitULEB128Value(Value);
2768 /// \brief Create an MCAsmParser instance.
2769 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
2770 MCContext &C, MCStreamer &Out,
2771 const MCAsmInfo &MAI) {
2772 return new AsmParser(SM, C, Out, MAI);