Home | History | Annotate | Download | only in MCParser
      1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This class implements the parser for assembly files.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "llvm/ADT/APFloat.h"
     15 #include "llvm/ADT/SmallString.h"
     16 #include "llvm/ADT/STLExtras.h"
     17 #include "llvm/ADT/StringMap.h"
     18 #include "llvm/ADT/Twine.h"
     19 #include "llvm/MC/MCAsmInfo.h"
     20 #include "llvm/MC/MCContext.h"
     21 #include "llvm/MC/MCDwarf.h"
     22 #include "llvm/MC/MCExpr.h"
     23 #include "llvm/MC/MCInstPrinter.h"
     24 #include "llvm/MC/MCInstrInfo.h"
     25 #include "llvm/MC/MCParser/AsmCond.h"
     26 #include "llvm/MC/MCParser/AsmLexer.h"
     27 #include "llvm/MC/MCParser/MCAsmParser.h"
     28 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
     29 #include "llvm/MC/MCRegisterInfo.h"
     30 #include "llvm/MC/MCSectionMachO.h"
     31 #include "llvm/MC/MCStreamer.h"
     32 #include "llvm/MC/MCSymbol.h"
     33 #include "llvm/MC/MCTargetAsmParser.h"
     34 #include "llvm/Support/CommandLine.h"
     35 #include "llvm/Support/ErrorHandling.h"
     36 #include "llvm/Support/MathExtras.h"
     37 #include "llvm/Support/MemoryBuffer.h"
     38 #include "llvm/Support/SourceMgr.h"
     39 #include "llvm/Support/raw_ostream.h"
     40 #include <cctype>
     41 #include <set>
     42 #include <string>
     43 #include <vector>
     44 using namespace llvm;
     45 
     46 static cl::opt<bool>
     47 FatalAssemblerWarnings("fatal-assembler-warnings",
     48                        cl::desc("Consider warnings as error"));
     49 
     50 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
     51 
     52 namespace {
     53 
     54 /// \brief Helper types for tracking macro definitions.
     55 typedef std::vector<AsmToken> MCAsmMacroArgument;
     56 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
     57 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
     58 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
     59 
     60 struct MCAsmMacro {
     61   StringRef Name;
     62   StringRef Body;
     63   MCAsmMacroParameters Parameters;
     64 
     65 public:
     66   MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
     67     Name(N), Body(B), Parameters(P) {}
     68 
     69   MCAsmMacro(const MCAsmMacro& Other)
     70     : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
     71 };
     72 
     73 /// \brief Helper class for storing information about an active macro
     74 /// instantiation.
     75 struct MacroInstantiation {
     76   /// The macro being instantiated.
     77   const MCAsmMacro *TheMacro;
     78 
     79   /// The macro instantiation with substitutions.
     80   MemoryBuffer *Instantiation;
     81 
     82   /// The location of the instantiation.
     83   SMLoc InstantiationLoc;
     84 
     85   /// The buffer where parsing should resume upon instantiation completion.
     86   int ExitBuffer;
     87 
     88   /// The location where parsing should resume upon instantiation completion.
     89   SMLoc ExitLoc;
     90 
     91 public:
     92   MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
     93                      MemoryBuffer *I);
     94 };
     95 
     96 struct ParseStatementInfo {
     97   /// ParsedOperands - The parsed operands from the last parsed statement.
     98   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
     99 
    100   /// Opcode - The opcode from the last parsed instruction.
    101   unsigned Opcode;
    102 
    103   /// Error - Was there an error parsing the inline assembly?
    104   bool ParseError;
    105 
    106   SmallVectorImpl<AsmRewrite> *AsmRewrites;
    107 
    108   ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
    109   ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
    110     : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
    111 
    112   ~ParseStatementInfo() {
    113     // Free any parsed operands.
    114     for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
    115       delete ParsedOperands[i];
    116     ParsedOperands.clear();
    117   }
    118 };
    119 
    120 /// \brief The concrete assembly parser instance.
    121 class AsmParser : public MCAsmParser {
    122   AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
    123   void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
    124 private:
    125   AsmLexer Lexer;
    126   MCContext &Ctx;
    127   MCStreamer &Out;
    128   const MCAsmInfo &MAI;
    129   SourceMgr &SrcMgr;
    130   SourceMgr::DiagHandlerTy SavedDiagHandler;
    131   void *SavedDiagContext;
    132   MCAsmParserExtension *PlatformParser;
    133 
    134   /// This is the current buffer index we're lexing from as managed by the
    135   /// SourceMgr object.
    136   int CurBuffer;
    137 
    138   AsmCond TheCondState;
    139   std::vector<AsmCond> TheCondStack;
    140 
    141   /// ExtensionDirectiveMap - maps directive names to handler methods in parser
    142   /// extensions. Extensions register themselves in this map by calling
    143   /// addDirectiveHandler.
    144   StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
    145 
    146   /// MacroMap - Map of currently defined macros.
    147   StringMap<MCAsmMacro*> MacroMap;
    148 
    149   /// ActiveMacros - Stack of active macro instantiations.
    150   std::vector<MacroInstantiation*> ActiveMacros;
    151 
    152   /// Boolean tracking whether macro substitution is enabled.
    153   unsigned MacrosEnabledFlag : 1;
    154 
    155   /// Flag tracking whether any errors have been encountered.
    156   unsigned HadError : 1;
    157 
    158   /// The values from the last parsed cpp hash file line comment if any.
    159   StringRef CppHashFilename;
    160   int64_t CppHashLineNumber;
    161   SMLoc CppHashLoc;
    162   int CppHashBuf;
    163 
    164   /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
    165   unsigned AssemblerDialect;
    166 
    167   /// IsDarwin - is Darwin compatibility enabled?
    168   bool IsDarwin;
    169 
    170   /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
    171   bool ParsingInlineAsm;
    172 
    173 public:
    174   AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
    175             const MCAsmInfo &MAI);
    176   virtual ~AsmParser();
    177 
    178   virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
    179 
    180   virtual void addDirectiveHandler(StringRef Directive,
    181                                    ExtensionDirectiveHandler Handler) {
    182     ExtensionDirectiveMap[Directive] = Handler;
    183   }
    184 
    185 public:
    186   /// @name MCAsmParser Interface
    187   /// {
    188 
    189   virtual SourceMgr &getSourceManager() { return SrcMgr; }
    190   virtual MCAsmLexer &getLexer() { return Lexer; }
    191   virtual MCContext &getContext() { return Ctx; }
    192   virtual MCStreamer &getStreamer() { return Out; }
    193   virtual unsigned getAssemblerDialect() {
    194     if (AssemblerDialect == ~0U)
    195       return MAI.getAssemblerDialect();
    196     else
    197       return AssemblerDialect;
    198   }
    199   virtual void setAssemblerDialect(unsigned i) {
    200     AssemblerDialect = i;
    201   }
    202 
    203   virtual bool Warning(SMLoc L, const Twine &Msg,
    204                        ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
    205   virtual bool Error(SMLoc L, const Twine &Msg,
    206                      ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
    207 
    208   virtual const AsmToken &Lex();
    209 
    210   void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
    211   bool isParsingInlineAsm() { return ParsingInlineAsm; }
    212 
    213   bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
    214                         unsigned &NumOutputs, unsigned &NumInputs,
    215                         SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
    216                         SmallVectorImpl<std::string> &Constraints,
    217                         SmallVectorImpl<std::string> &Clobbers,
    218                         const MCInstrInfo *MII,
    219                         const MCInstPrinter *IP,
    220                         MCAsmParserSemaCallback &SI);
    221 
    222   bool parseExpression(const MCExpr *&Res);
    223   virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
    224   virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
    225   virtual bool parseAbsoluteExpression(int64_t &Res);
    226 
    227   /// parseIdentifier - Parse an identifier or string (as a quoted identifier)
    228   /// and set \p Res to the identifier contents.
    229   virtual bool parseIdentifier(StringRef &Res);
    230   virtual void eatToEndOfStatement();
    231 
    232   virtual void checkForValidSection();
    233   /// }
    234 
    235 private:
    236 
    237   bool ParseStatement(ParseStatementInfo &Info);
    238   void EatToEndOfLine();
    239   bool ParseCppHashLineFilenameComment(const SMLoc &L);
    240 
    241   void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
    242                         MCAsmMacroParameters Parameters);
    243   bool expandMacro(raw_svector_ostream &OS, StringRef Body,
    244                    const MCAsmMacroParameters &Parameters,
    245                    const MCAsmMacroArguments &A,
    246                    const SMLoc &L);
    247 
    248   /// \brief Are macros enabled in the parser?
    249   bool MacrosEnabled() {return MacrosEnabledFlag;}
    250 
    251   /// \brief Control a flag in the parser that enables or disables macros.
    252   void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
    253 
    254   /// \brief Lookup a previously defined macro.
    255   /// \param Name Macro name.
    256   /// \returns Pointer to macro. NULL if no such macro was defined.
    257   const MCAsmMacro* LookupMacro(StringRef Name);
    258 
    259   /// \brief Define a new macro with the given name and information.
    260   void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
    261 
    262   /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
    263   void UndefineMacro(StringRef Name);
    264 
    265   /// \brief Are we inside a macro instantiation?
    266   bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
    267 
    268   /// \brief Handle entry to macro instantiation.
    269   ///
    270   /// \param M The macro.
    271   /// \param NameLoc Instantiation location.
    272   bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
    273 
    274   /// \brief Handle exit from macro instantiation.
    275   void HandleMacroExit();
    276 
    277   /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
    278   /// is initially unknown, set it to AsmToken::Eof. It will be set to the
    279   /// correct delimiter by the method.
    280   bool ParseMacroArgument(MCAsmMacroArgument &MA,
    281                           AsmToken::TokenKind &ArgumentDelimiter);
    282 
    283   /// \brief Parse all macro arguments for a given macro.
    284   bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
    285 
    286   void PrintMacroInstantiations();
    287   void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
    288                     ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
    289     SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
    290   }
    291   static void DiagHandler(const SMDiagnostic &Diag, void *Context);
    292 
    293   /// EnterIncludeFile - Enter the specified file. This returns true on failure.
    294   bool EnterIncludeFile(const std::string &Filename);
    295   /// ProcessIncbinFile - Process the specified file for the .incbin directive.
    296   /// This returns true on failure.
    297   bool ProcessIncbinFile(const std::string &Filename);
    298 
    299   /// \brief Reset the current lexer position to that given by \p Loc. The
    300   /// current token is not set; clients should ensure Lex() is called
    301   /// subsequently.
    302   ///
    303   /// \param InBuffer If not -1, should be the known buffer id that contains the
    304   /// location.
    305   void JumpToLoc(SMLoc Loc, int InBuffer=-1);
    306 
    307   /// \brief Parse up to the end of statement and a return the contents from the
    308   /// current token until the end of the statement; the current token on exit
    309   /// will be either the EndOfStatement or EOF.
    310   virtual StringRef parseStringToEndOfStatement();
    311 
    312   /// \brief Parse until the end of a statement or a comma is encountered,
    313   /// return the contents from the current token up to the end or comma.
    314   StringRef ParseStringToComma();
    315 
    316   bool ParseAssignment(StringRef Name, bool allow_redef,
    317                        bool NoDeadStrip = false);
    318 
    319   bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
    320   bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
    321   bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
    322   bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
    323 
    324   bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
    325 
    326   // Generic (target and platform independent) directive parsing.
    327   enum DirectiveKind {
    328     DK_NO_DIRECTIVE, // Placeholder
    329     DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
    330     DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
    331     DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
    332     DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
    333     DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
    334     DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
    335     DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
    336     DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
    337     DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
    338     DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
    339     DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
    340     DK_ELSEIF, DK_ELSE, DK_ENDIF,
    341     DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
    342     DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
    343     DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
    344     DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
    345     DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
    346     DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
    347     DK_CFI_REGISTER,
    348     DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
    349     DK_SLEB128, DK_ULEB128
    350   };
    351 
    352   /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
    353   /// directives parsed by this class.
    354   StringMap<DirectiveKind> DirectiveKindMap;
    355 
    356   // ".ascii", ".asciz", ".string"
    357   bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
    358   bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
    359   bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
    360   bool ParseDirectiveFill(); // ".fill"
    361   bool ParseDirectiveZero(); // ".zero"
    362   // ".set", ".equ", ".equiv"
    363   bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
    364   bool ParseDirectiveOrg(); // ".org"
    365   // ".align{,32}", ".p2align{,w,l}"
    366   bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
    367 
    368   // ".file", ".line", ".loc", ".stabs"
    369   bool ParseDirectiveFile(SMLoc DirectiveLoc);
    370   bool ParseDirectiveLine();
    371   bool ParseDirectiveLoc();
    372   bool ParseDirectiveStabs();
    373 
    374   // .cfi directives
    375   bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
    376   bool ParseDirectiveCFISections();
    377   bool ParseDirectiveCFIStartProc();
    378   bool ParseDirectiveCFIEndProc();
    379   bool ParseDirectiveCFIDefCfaOffset();
    380   bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
    381   bool ParseDirectiveCFIAdjustCfaOffset();
    382   bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
    383   bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
    384   bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
    385   bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
    386   bool ParseDirectiveCFIRememberState();
    387   bool ParseDirectiveCFIRestoreState();
    388   bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
    389   bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
    390   bool ParseDirectiveCFIEscape();
    391   bool ParseDirectiveCFISignalFrame();
    392   bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
    393 
    394   // macro directives
    395   bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
    396   bool ParseDirectiveEndMacro(StringRef Directive);
    397   bool ParseDirectiveMacro(SMLoc DirectiveLoc);
    398   bool ParseDirectiveMacrosOnOff(StringRef Directive);
    399 
    400   // ".bundle_align_mode"
    401   bool ParseDirectiveBundleAlignMode();
    402   // ".bundle_lock"
    403   bool ParseDirectiveBundleLock();
    404   // ".bundle_unlock"
    405   bool ParseDirectiveBundleUnlock();
    406 
    407   // ".space", ".skip"
    408   bool ParseDirectiveSpace(StringRef IDVal);
    409 
    410   // .sleb128 (Signed=true) and .uleb128 (Signed=false)
    411   bool ParseDirectiveLEB128(bool Signed);
    412 
    413   /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
    414   /// accepts a single symbol (which should be a label or an external).
    415   bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
    416 
    417   bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
    418 
    419   bool ParseDirectiveAbort(); // ".abort"
    420   bool ParseDirectiveInclude(); // ".include"
    421   bool ParseDirectiveIncbin(); // ".incbin"
    422 
    423   bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
    424   // ".ifb" or ".ifnb", depending on ExpectBlank.
    425   bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
    426   // ".ifc" or ".ifnc", depending on ExpectEqual.
    427   bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
    428   // ".ifdef" or ".ifndef", depending on expect_defined
    429   bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
    430   bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
    431   bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
    432   bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
    433   virtual bool parseEscapedString(std::string &Data);
    434 
    435   const MCExpr *ApplyModifierToExpr(const MCExpr *E,
    436                                     MCSymbolRefExpr::VariantKind Variant);
    437 
    438   // Macro-like directives
    439   MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
    440   void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
    441                                 raw_svector_ostream &OS);
    442   bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
    443   bool ParseDirectiveIrp(SMLoc DirectiveLoc);  // ".irp"
    444   bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
    445   bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
    446 
    447   // "_emit" or "__emit"
    448   bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
    449                             size_t Len);
    450 
    451   // "align"
    452   bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
    453 
    454   void initializeDirectiveKindMap();
    455 };
    456 }
    457 
    458 namespace llvm {
    459 
    460 extern MCAsmParserExtension *createDarwinAsmParser();
    461 extern MCAsmParserExtension *createELFAsmParser();
    462 extern MCAsmParserExtension *createCOFFAsmParser();
    463 
    464 }
    465 
    466 enum { DEFAULT_ADDRSPACE = 0 };
    467 
    468 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
    469                      MCStreamer &_Out, const MCAsmInfo &_MAI)
    470   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
    471     PlatformParser(0),
    472     CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
    473     AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
    474   // Save the old handler.
    475   SavedDiagHandler = SrcMgr.getDiagHandler();
    476   SavedDiagContext = SrcMgr.getDiagContext();
    477   // Set our own handler which calls the saved handler.
    478   SrcMgr.setDiagHandler(DiagHandler, this);
    479   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
    480 
    481   // Initialize the platform / file format parser.
    482   //
    483   // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
    484   // created.
    485   if (_MAI.hasMicrosoftFastStdCallMangling()) {
    486     PlatformParser = createCOFFAsmParser();
    487     PlatformParser->Initialize(*this);
    488   } else if (_MAI.hasSubsectionsViaSymbols()) {
    489     PlatformParser = createDarwinAsmParser();
    490     PlatformParser->Initialize(*this);
    491     IsDarwin = true;
    492   } else {
    493     PlatformParser = createELFAsmParser();
    494     PlatformParser->Initialize(*this);
    495   }
    496 
    497   initializeDirectiveKindMap();
    498 }
    499 
    500 AsmParser::~AsmParser() {
    501   assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
    502 
    503   // Destroy any macros.
    504   for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
    505          ie = MacroMap.end(); it != ie; ++it)
    506     delete it->getValue();
    507 
    508   delete PlatformParser;
    509 }
    510 
    511 void AsmParser::PrintMacroInstantiations() {
    512   // Print the active macro instantiation stack.
    513   for (std::vector<MacroInstantiation*>::const_reverse_iterator
    514          it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
    515     PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
    516                  "while in macro instantiation");
    517 }
    518 
    519 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
    520   if (FatalAssemblerWarnings)
    521     return Error(L, Msg, Ranges);
    522   PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
    523   PrintMacroInstantiations();
    524   return false;
    525 }
    526 
    527 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
    528   HadError = true;
    529   PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
    530   PrintMacroInstantiations();
    531   return true;
    532 }
    533 
    534 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
    535   std::string IncludedFile;
    536   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
    537   if (NewBuf == -1)
    538     return true;
    539 
    540   CurBuffer = NewBuf;
    541 
    542   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
    543 
    544   return false;
    545 }
    546 
    547 /// Process the specified .incbin file by seaching for it in the include paths
    548 /// then just emitting the byte contents of the file to the streamer. This
    549 /// returns true on failure.
    550 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
    551   std::string IncludedFile;
    552   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
    553   if (NewBuf == -1)
    554     return true;
    555 
    556   // Pick up the bytes from the file and emit them.
    557   getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
    558                           DEFAULT_ADDRSPACE);
    559   return false;
    560 }
    561 
    562 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
    563   if (InBuffer != -1) {
    564     CurBuffer = InBuffer;
    565   } else {
    566     CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
    567   }
    568   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
    569 }
    570 
    571 const AsmToken &AsmParser::Lex() {
    572   const AsmToken *tok = &Lexer.Lex();
    573 
    574   if (tok->is(AsmToken::Eof)) {
    575     // If this is the end of an included file, pop the parent file off the
    576     // include stack.
    577     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
    578     if (ParentIncludeLoc != SMLoc()) {
    579       JumpToLoc(ParentIncludeLoc);
    580       tok = &Lexer.Lex();
    581     }
    582   }
    583 
    584   if (tok->is(AsmToken::Error))
    585     Error(Lexer.getErrLoc(), Lexer.getErr());
    586 
    587   return *tok;
    588 }
    589 
    590 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
    591   // Create the initial section, if requested.
    592   if (!NoInitialTextSection)
    593     Out.InitSections();
    594 
    595   // Prime the lexer.
    596   Lex();
    597 
    598   HadError = false;
    599   AsmCond StartingCondState = TheCondState;
    600 
    601   // If we are generating dwarf for assembly source files save the initial text
    602   // section and generate a .file directive.
    603   if (getContext().getGenDwarfForAssembly()) {
    604     getContext().setGenDwarfSection(getStreamer().getCurrentSection());
    605     MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
    606     getStreamer().EmitLabel(SectionStartSym);
    607     getContext().setGenDwarfSectionStartSym(SectionStartSym);
    608     getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
    609                                          StringRef(),
    610                                          getContext().getMainFileName());
    611   }
    612 
    613   // While we have input, parse each statement.
    614   while (Lexer.isNot(AsmToken::Eof)) {
    615     ParseStatementInfo Info;
    616     if (!ParseStatement(Info)) continue;
    617 
    618     // We had an error, validate that one was emitted and recover by skipping to
    619     // the next line.
    620     assert(HadError && "Parse statement returned an error, but none emitted!");
    621     eatToEndOfStatement();
    622   }
    623 
    624   if (TheCondState.TheCond != StartingCondState.TheCond ||
    625       TheCondState.Ignore != StartingCondState.Ignore)
    626     return TokError("unmatched .ifs or .elses");
    627 
    628   // Check to see there are no empty DwarfFile slots.
    629   const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
    630     getContext().getMCDwarfFiles();
    631   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
    632     if (!MCDwarfFiles[i])
    633       TokError("unassigned file number: " + Twine(i) + " for .file directives");
    634   }
    635 
    636   // Check to see that all assembler local symbols were actually defined.
    637   // Targets that don't do subsections via symbols may not want this, though,
    638   // so conservatively exclude them. Only do this if we're finalizing, though,
    639   // as otherwise we won't necessarilly have seen everything yet.
    640   if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
    641     const MCContext::SymbolTable &Symbols = getContext().getSymbols();
    642     for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
    643          e = Symbols.end();
    644          i != e; ++i) {
    645       MCSymbol *Sym = i->getValue();
    646       // Variable symbols may not be marked as defined, so check those
    647       // explicitly. If we know it's a variable, we have a definition for
    648       // the purposes of this check.
    649       if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
    650         // FIXME: We would really like to refer back to where the symbol was
    651         // first referenced for a source location. We need to add something
    652         // to track that. Currently, we just point to the end of the file.
    653         PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
    654                      "assembler local symbol '" + Sym->getName() +
    655                      "' not defined");
    656     }
    657   }
    658 
    659 
    660   // Finalize the output stream if there are no errors and if the client wants
    661   // us to.
    662   if (!HadError && !NoFinalize)
    663     Out.Finish();
    664 
    665   return HadError;
    666 }
    667 
    668 void AsmParser::checkForValidSection() {
    669   if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
    670     TokError("expected section directive before assembly directive");
    671     Out.InitToTextSection();
    672   }
    673 }
    674 
    675 /// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
    676 void AsmParser::eatToEndOfStatement() {
    677   while (Lexer.isNot(AsmToken::EndOfStatement) &&
    678          Lexer.isNot(AsmToken::Eof))
    679     Lex();
    680 
    681   // Eat EOL.
    682   if (Lexer.is(AsmToken::EndOfStatement))
    683     Lex();
    684 }
    685 
    686 StringRef AsmParser::parseStringToEndOfStatement() {
    687   const char *Start = getTok().getLoc().getPointer();
    688 
    689   while (Lexer.isNot(AsmToken::EndOfStatement) &&
    690          Lexer.isNot(AsmToken::Eof))
    691     Lex();
    692 
    693   const char *End = getTok().getLoc().getPointer();
    694   return StringRef(Start, End - Start);
    695 }
    696 
    697 StringRef AsmParser::ParseStringToComma() {
    698   const char *Start = getTok().getLoc().getPointer();
    699 
    700   while (Lexer.isNot(AsmToken::EndOfStatement) &&
    701          Lexer.isNot(AsmToken::Comma) &&
    702          Lexer.isNot(AsmToken::Eof))
    703     Lex();
    704 
    705   const char *End = getTok().getLoc().getPointer();
    706   return StringRef(Start, End - Start);
    707 }
    708 
    709 /// ParseParenExpr - Parse a paren expression and return it.
    710 /// NOTE: This assumes the leading '(' has already been consumed.
    711 ///
    712 /// parenexpr ::= expr)
    713 ///
    714 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
    715   if (parseExpression(Res)) return true;
    716   if (Lexer.isNot(AsmToken::RParen))
    717     return TokError("expected ')' in parentheses expression");
    718   EndLoc = Lexer.getTok().getEndLoc();
    719   Lex();
    720   return false;
    721 }
    722 
    723 /// ParseBracketExpr - Parse a bracket expression and return it.
    724 /// NOTE: This assumes the leading '[' has already been consumed.
    725 ///
    726 /// bracketexpr ::= expr]
    727 ///
    728 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
    729   if (parseExpression(Res)) return true;
    730   if (Lexer.isNot(AsmToken::RBrac))
    731     return TokError("expected ']' in brackets expression");
    732   EndLoc = Lexer.getTok().getEndLoc();
    733   Lex();
    734   return false;
    735 }
    736 
    737 /// ParsePrimaryExpr - Parse a primary expression and return it.
    738 ///  primaryexpr ::= (parenexpr
    739 ///  primaryexpr ::= symbol
    740 ///  primaryexpr ::= number
    741 ///  primaryexpr ::= '.'
    742 ///  primaryexpr ::= ~,+,- primaryexpr
    743 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
    744   SMLoc FirstTokenLoc = getLexer().getLoc();
    745   AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
    746   switch (FirstTokenKind) {
    747   default:
    748     return TokError("unknown token in expression");
    749   // If we have an error assume that we've already handled it.
    750   case AsmToken::Error:
    751     return true;
    752   case AsmToken::Exclaim:
    753     Lex(); // Eat the operator.
    754     if (ParsePrimaryExpr(Res, EndLoc))
    755       return true;
    756     Res = MCUnaryExpr::CreateLNot(Res, getContext());
    757     return false;
    758   case AsmToken::Dollar:
    759   case AsmToken::String:
    760   case AsmToken::Identifier: {
    761     StringRef Identifier;
    762     if (parseIdentifier(Identifier)) {
    763       if (FirstTokenKind == AsmToken::Dollar)
    764         return Error(FirstTokenLoc, "invalid token in expression");
    765       return true;
    766     }
    767 
    768     EndLoc = SMLoc::getFromPointer(Identifier.end());
    769 
    770     // This is a symbol reference.
    771     std::pair<StringRef, StringRef> Split = Identifier.split('@');
    772     MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
    773 
    774     // Lookup the symbol variant if used.
    775     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
    776     if (Split.first.size() != Identifier.size()) {
    777       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
    778       if (Variant == MCSymbolRefExpr::VK_Invalid) {
    779         Variant = MCSymbolRefExpr::VK_None;
    780         return TokError("invalid variant '" + Split.second + "'");
    781       }
    782     }
    783 
    784     // If this is an absolute variable reference, substitute it now to preserve
    785     // semantics in the face of reassignment.
    786     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
    787       if (Variant)
    788         return Error(EndLoc, "unexpected modifier on variable reference");
    789 
    790       Res = Sym->getVariableValue();
    791       return false;
    792     }
    793 
    794     // Otherwise create a symbol ref.
    795     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
    796     return false;
    797   }
    798   case AsmToken::Integer: {
    799     SMLoc Loc = getTok().getLoc();
    800     int64_t IntVal = getTok().getIntVal();
    801     Res = MCConstantExpr::Create(IntVal, getContext());
    802     EndLoc = Lexer.getTok().getEndLoc();
    803     Lex(); // Eat token.
    804     // Look for 'b' or 'f' following an Integer as a directional label
    805     if (Lexer.getKind() == AsmToken::Identifier) {
    806       StringRef IDVal = getTok().getString();
    807       if (IDVal == "f" || IDVal == "b"){
    808         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
    809                                                       IDVal == "f" ? 1 : 0);
    810         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
    811                                       getContext());
    812         if (IDVal == "b" && Sym->isUndefined())
    813           return Error(Loc, "invalid reference to undefined symbol");
    814         EndLoc = Lexer.getTok().getEndLoc();
    815         Lex(); // Eat identifier.
    816       }
    817     }
    818     return false;
    819   }
    820   case AsmToken::Real: {
    821     APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
    822     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
    823     Res = MCConstantExpr::Create(IntVal, getContext());
    824     EndLoc = Lexer.getTok().getEndLoc();
    825     Lex(); // Eat token.
    826     return false;
    827   }
    828   case AsmToken::Dot: {
    829     // This is a '.' reference, which references the current PC.  Emit a
    830     // temporary label to the streamer and refer to it.
    831     MCSymbol *Sym = Ctx.CreateTempSymbol();
    832     Out.EmitLabel(Sym);
    833     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
    834     EndLoc = Lexer.getTok().getEndLoc();
    835     Lex(); // Eat identifier.
    836     return false;
    837   }
    838   case AsmToken::LParen:
    839     Lex(); // Eat the '('.
    840     return ParseParenExpr(Res, EndLoc);
    841   case AsmToken::LBrac:
    842     if (!PlatformParser->HasBracketExpressions())
    843       return TokError("brackets expression not supported on this target");
    844     Lex(); // Eat the '['.
    845     return ParseBracketExpr(Res, EndLoc);
    846   case AsmToken::Minus:
    847     Lex(); // Eat the operator.
    848     if (ParsePrimaryExpr(Res, EndLoc))
    849       return true;
    850     Res = MCUnaryExpr::CreateMinus(Res, getContext());
    851     return false;
    852   case AsmToken::Plus:
    853     Lex(); // Eat the operator.
    854     if (ParsePrimaryExpr(Res, EndLoc))
    855       return true;
    856     Res = MCUnaryExpr::CreatePlus(Res, getContext());
    857     return false;
    858   case AsmToken::Tilde:
    859     Lex(); // Eat the operator.
    860     if (ParsePrimaryExpr(Res, EndLoc))
    861       return true;
    862     Res = MCUnaryExpr::CreateNot(Res, getContext());
    863     return false;
    864   }
    865 }
    866 
    867 bool AsmParser::parseExpression(const MCExpr *&Res) {
    868   SMLoc EndLoc;
    869   return parseExpression(Res, EndLoc);
    870 }
    871 
    872 const MCExpr *
    873 AsmParser::ApplyModifierToExpr(const MCExpr *E,
    874                                MCSymbolRefExpr::VariantKind Variant) {
    875   // Recurse over the given expression, rebuilding it to apply the given variant
    876   // if there is exactly one symbol.
    877   switch (E->getKind()) {
    878   case MCExpr::Target:
    879   case MCExpr::Constant:
    880     return 0;
    881 
    882   case MCExpr::SymbolRef: {
    883     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
    884 
    885     if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
    886       TokError("invalid variant on expression '" +
    887                getTok().getIdentifier() + "' (already modified)");
    888       return E;
    889     }
    890 
    891     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
    892   }
    893 
    894   case MCExpr::Unary: {
    895     const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
    896     const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
    897     if (!Sub)
    898       return 0;
    899     return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
    900   }
    901 
    902   case MCExpr::Binary: {
    903     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
    904     const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
    905     const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
    906 
    907     if (!LHS && !RHS)
    908       return 0;
    909 
    910     if (!LHS) LHS = BE->getLHS();
    911     if (!RHS) RHS = BE->getRHS();
    912 
    913     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
    914   }
    915   }
    916 
    917   llvm_unreachable("Invalid expression kind!");
    918 }
    919 
    920 /// parseExpression - Parse an expression and return it.
    921 ///
    922 ///  expr ::= expr &&,|| expr               -> lowest.
    923 ///  expr ::= expr |,^,&,! expr
    924 ///  expr ::= expr ==,!=,<>,<,<=,>,>= expr
    925 ///  expr ::= expr <<,>> expr
    926 ///  expr ::= expr +,- expr
    927 ///  expr ::= expr *,/,% expr               -> highest.
    928 ///  expr ::= primaryexpr
    929 ///
    930 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
    931   // Parse the expression.
    932   Res = 0;
    933   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
    934     return true;
    935 
    936   // As a special case, we support 'a op b @ modifier' by rewriting the
    937   // expression to include the modifier. This is inefficient, but in general we
    938   // expect users to use 'a@modifier op b'.
    939   if (Lexer.getKind() == AsmToken::At) {
    940     Lex();
    941 
    942     if (Lexer.isNot(AsmToken::Identifier))
    943       return TokError("unexpected symbol modifier following '@'");
    944 
    945     MCSymbolRefExpr::VariantKind Variant =
    946       MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
    947     if (Variant == MCSymbolRefExpr::VK_Invalid)
    948       return TokError("invalid variant '" + getTok().getIdentifier() + "'");
    949 
    950     const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
    951     if (!ModifiedRes) {
    952       return TokError("invalid modifier '" + getTok().getIdentifier() +
    953                       "' (no symbols present)");
    954     }
    955 
    956     Res = ModifiedRes;
    957     Lex();
    958   }
    959 
    960   // Try to constant fold it up front, if possible.
    961   int64_t Value;
    962   if (Res->EvaluateAsAbsolute(Value))
    963     Res = MCConstantExpr::Create(Value, getContext());
    964 
    965   return false;
    966 }
    967 
    968 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
    969   Res = 0;
    970   return ParseParenExpr(Res, EndLoc) ||
    971          ParseBinOpRHS(1, Res, EndLoc);
    972 }
    973 
    974 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
    975   const MCExpr *Expr;
    976 
    977   SMLoc StartLoc = Lexer.getLoc();
    978   if (parseExpression(Expr))
    979     return true;
    980 
    981   if (!Expr->EvaluateAsAbsolute(Res))
    982     return Error(StartLoc, "expected absolute expression");
    983 
    984   return false;
    985 }
    986 
    987 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
    988                                    MCBinaryExpr::Opcode &Kind) {
    989   switch (K) {
    990   default:
    991     return 0;    // not a binop.
    992 
    993     // Lowest Precedence: &&, ||
    994   case AsmToken::AmpAmp:
    995     Kind = MCBinaryExpr::LAnd;
    996     return 1;
    997   case AsmToken::PipePipe:
    998     Kind = MCBinaryExpr::LOr;
    999     return 1;
   1000 
   1001 
   1002     // Low Precedence: |, &, ^
   1003     //
   1004     // FIXME: gas seems to support '!' as an infix operator?
   1005   case AsmToken::Pipe:
   1006     Kind = MCBinaryExpr::Or;
   1007     return 2;
   1008   case AsmToken::Caret:
   1009     Kind = MCBinaryExpr::Xor;
   1010     return 2;
   1011   case AsmToken::Amp:
   1012     Kind = MCBinaryExpr::And;
   1013     return 2;
   1014 
   1015     // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
   1016   case AsmToken::EqualEqual:
   1017     Kind = MCBinaryExpr::EQ;
   1018     return 3;
   1019   case AsmToken::ExclaimEqual:
   1020   case AsmToken::LessGreater:
   1021     Kind = MCBinaryExpr::NE;
   1022     return 3;
   1023   case AsmToken::Less:
   1024     Kind = MCBinaryExpr::LT;
   1025     return 3;
   1026   case AsmToken::LessEqual:
   1027     Kind = MCBinaryExpr::LTE;
   1028     return 3;
   1029   case AsmToken::Greater:
   1030     Kind = MCBinaryExpr::GT;
   1031     return 3;
   1032   case AsmToken::GreaterEqual:
   1033     Kind = MCBinaryExpr::GTE;
   1034     return 3;
   1035 
   1036     // Intermediate Precedence: <<, >>
   1037   case AsmToken::LessLess:
   1038     Kind = MCBinaryExpr::Shl;
   1039     return 4;
   1040   case AsmToken::GreaterGreater:
   1041     Kind = MCBinaryExpr::Shr;
   1042     return 4;
   1043 
   1044     // High Intermediate Precedence: +, -
   1045   case AsmToken::Plus:
   1046     Kind = MCBinaryExpr::Add;
   1047     return 5;
   1048   case AsmToken::Minus:
   1049     Kind = MCBinaryExpr::Sub;
   1050     return 5;
   1051 
   1052     // Highest Precedence: *, /, %
   1053   case AsmToken::Star:
   1054     Kind = MCBinaryExpr::Mul;
   1055     return 6;
   1056   case AsmToken::Slash:
   1057     Kind = MCBinaryExpr::Div;
   1058     return 6;
   1059   case AsmToken::Percent:
   1060     Kind = MCBinaryExpr::Mod;
   1061     return 6;
   1062   }
   1063 }
   1064 
   1065 
   1066 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
   1067 /// Res contains the LHS of the expression on input.
   1068 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
   1069                               SMLoc &EndLoc) {
   1070   while (1) {
   1071     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
   1072     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
   1073 
   1074     // If the next token is lower precedence than we are allowed to eat, return
   1075     // successfully with what we ate already.
   1076     if (TokPrec < Precedence)
   1077       return false;
   1078 
   1079     Lex();
   1080 
   1081     // Eat the next primary expression.
   1082     const MCExpr *RHS;
   1083     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
   1084 
   1085     // If BinOp binds less tightly with RHS than the operator after RHS, let
   1086     // the pending operator take RHS as its LHS.
   1087     MCBinaryExpr::Opcode Dummy;
   1088     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
   1089     if (TokPrec < NextTokPrec) {
   1090       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
   1091     }
   1092 
   1093     // Merge LHS and RHS according to operator.
   1094     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
   1095   }
   1096 }
   1097 
   1098 /// ParseStatement:
   1099 ///   ::= EndOfStatement
   1100 ///   ::= Label* Directive ...Operands... EndOfStatement
   1101 ///   ::= Label* Identifier OperandList* EndOfStatement
   1102 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
   1103   if (Lexer.is(AsmToken::EndOfStatement)) {
   1104     Out.AddBlankLine();
   1105     Lex();
   1106     return false;
   1107   }
   1108 
   1109   // Statements always start with an identifier or are a full line comment.
   1110   AsmToken ID = getTok();
   1111   SMLoc IDLoc = ID.getLoc();
   1112   StringRef IDVal;
   1113   int64_t LocalLabelVal = -1;
   1114   // A full line comment is a '#' as the first token.
   1115   if (Lexer.is(AsmToken::Hash))
   1116     return ParseCppHashLineFilenameComment(IDLoc);
   1117 
   1118   // Allow an integer followed by a ':' as a directional local label.
   1119   if (Lexer.is(AsmToken::Integer)) {
   1120     LocalLabelVal = getTok().getIntVal();
   1121     if (LocalLabelVal < 0) {
   1122       if (!TheCondState.Ignore)
   1123         return TokError("unexpected token at start of statement");
   1124       IDVal = "";
   1125     } else {
   1126       IDVal = getTok().getString();
   1127       Lex(); // Consume the integer token to be used as an identifier token.
   1128       if (Lexer.getKind() != AsmToken::Colon) {
   1129         if (!TheCondState.Ignore)
   1130           return TokError("unexpected token at start of statement");
   1131       }
   1132     }
   1133   } else if (Lexer.is(AsmToken::Dot)) {
   1134     // Treat '.' as a valid identifier in this context.
   1135     Lex();
   1136     IDVal = ".";
   1137   } else if (parseIdentifier(IDVal)) {
   1138     if (!TheCondState.Ignore)
   1139       return TokError("unexpected token at start of statement");
   1140     IDVal = "";
   1141   }
   1142 
   1143   // Handle conditional assembly here before checking for skipping.  We
   1144   // have to do this so that .endif isn't skipped in a ".if 0" block for
   1145   // example.
   1146   StringMap<DirectiveKind>::const_iterator DirKindIt =
   1147     DirectiveKindMap.find(IDVal);
   1148   DirectiveKind DirKind =
   1149     (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
   1150                                             DirKindIt->getValue();
   1151   switch (DirKind) {
   1152     default:
   1153       break;
   1154     case DK_IF:
   1155       return ParseDirectiveIf(IDLoc);
   1156     case DK_IFB:
   1157       return ParseDirectiveIfb(IDLoc, true);
   1158     case DK_IFNB:
   1159       return ParseDirectiveIfb(IDLoc, false);
   1160     case DK_IFC:
   1161       return ParseDirectiveIfc(IDLoc, true);
   1162     case DK_IFNC:
   1163       return ParseDirectiveIfc(IDLoc, false);
   1164     case DK_IFDEF:
   1165       return ParseDirectiveIfdef(IDLoc, true);
   1166     case DK_IFNDEF:
   1167     case DK_IFNOTDEF:
   1168       return ParseDirectiveIfdef(IDLoc, false);
   1169     case DK_ELSEIF:
   1170       return ParseDirectiveElseIf(IDLoc);
   1171     case DK_ELSE:
   1172       return ParseDirectiveElse(IDLoc);
   1173     case DK_ENDIF:
   1174       return ParseDirectiveEndIf(IDLoc);
   1175   }
   1176 
   1177   // Ignore the statement if in the middle of inactive conditional
   1178   // (e.g. ".if 0").
   1179   if (TheCondState.Ignore) {
   1180     eatToEndOfStatement();
   1181     return false;
   1182   }
   1183 
   1184   // FIXME: Recurse on local labels?
   1185 
   1186   // See what kind of statement we have.
   1187   switch (Lexer.getKind()) {
   1188   case AsmToken::Colon: {
   1189     checkForValidSection();
   1190 
   1191     // identifier ':'   -> Label.
   1192     Lex();
   1193 
   1194     // Diagnose attempt to use '.' as a label.
   1195     if (IDVal == ".")
   1196       return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
   1197 
   1198     // Diagnose attempt to use a variable as a label.
   1199     //
   1200     // FIXME: Diagnostics. Note the location of the definition as a label.
   1201     // FIXME: This doesn't diagnose assignment to a symbol which has been
   1202     // implicitly marked as external.
   1203     MCSymbol *Sym;
   1204     if (LocalLabelVal == -1)
   1205       Sym = getContext().GetOrCreateSymbol(IDVal);
   1206     else
   1207       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
   1208     if (!Sym->isUndefined() || Sym->isVariable())
   1209       return Error(IDLoc, "invalid symbol redefinition");
   1210 
   1211     // Emit the label.
   1212     if (!ParsingInlineAsm)
   1213       Out.EmitLabel(Sym);
   1214 
   1215     // If we are generating dwarf for assembly source files then gather the
   1216     // info to make a dwarf label entry for this label if needed.
   1217     if (getContext().getGenDwarfForAssembly())
   1218       MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
   1219                                  IDLoc);
   1220 
   1221     // Consume any end of statement token, if present, to avoid spurious
   1222     // AddBlankLine calls().
   1223     if (Lexer.is(AsmToken::EndOfStatement)) {
   1224       Lex();
   1225       if (Lexer.is(AsmToken::Eof))
   1226         return false;
   1227     }
   1228 
   1229     return false;
   1230   }
   1231 
   1232   case AsmToken::Equal:
   1233     // identifier '=' ... -> assignment statement
   1234     Lex();
   1235 
   1236     return ParseAssignment(IDVal, true);
   1237 
   1238   default: // Normal instruction or directive.
   1239     break;
   1240   }
   1241 
   1242   // If macros are enabled, check to see if this is a macro instantiation.
   1243   if (MacrosEnabled())
   1244     if (const MCAsmMacro *M = LookupMacro(IDVal)) {
   1245       return HandleMacroEntry(M, IDLoc);
   1246     }
   1247 
   1248   // Otherwise, we have a normal instruction or directive.
   1249 
   1250   // Directives start with "."
   1251   if (IDVal[0] == '.' && IDVal != ".") {
   1252     // There are several entities interested in parsing directives:
   1253     //
   1254     // 1. The target-specific assembly parser. Some directives are target
   1255     //    specific or may potentially behave differently on certain targets.
   1256     // 2. Asm parser extensions. For example, platform-specific parsers
   1257     //    (like the ELF parser) register themselves as extensions.
   1258     // 3. The generic directive parser implemented by this class. These are
   1259     //    all the directives that behave in a target and platform independent
   1260     //    manner, or at least have a default behavior that's shared between
   1261     //    all targets and platforms.
   1262 
   1263     // First query the target-specific parser. It will return 'true' if it
   1264     // isn't interested in this directive.
   1265     if (!getTargetParser().ParseDirective(ID))
   1266       return false;
   1267 
   1268     // Next, check the extention directive map to see if any extension has
   1269     // registered itself to parse this directive.
   1270     std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
   1271       ExtensionDirectiveMap.lookup(IDVal);
   1272     if (Handler.first)
   1273       return (*Handler.second)(Handler.first, IDVal, IDLoc);
   1274 
   1275     // Finally, if no one else is interested in this directive, it must be
   1276     // generic and familiar to this class.
   1277     switch (DirKind) {
   1278       default:
   1279         break;
   1280       case DK_SET:
   1281       case DK_EQU:
   1282         return ParseDirectiveSet(IDVal, true);
   1283       case DK_EQUIV:
   1284         return ParseDirectiveSet(IDVal, false);
   1285       case DK_ASCII:
   1286         return ParseDirectiveAscii(IDVal, false);
   1287       case DK_ASCIZ:
   1288       case DK_STRING:
   1289         return ParseDirectiveAscii(IDVal, true);
   1290       case DK_BYTE:
   1291         return ParseDirectiveValue(1);
   1292       case DK_SHORT:
   1293       case DK_VALUE:
   1294       case DK_2BYTE:
   1295         return ParseDirectiveValue(2);
   1296       case DK_LONG:
   1297       case DK_INT:
   1298       case DK_4BYTE:
   1299         return ParseDirectiveValue(4);
   1300       case DK_QUAD:
   1301       case DK_8BYTE:
   1302         return ParseDirectiveValue(8);
   1303       case DK_SINGLE:
   1304       case DK_FLOAT:
   1305         return ParseDirectiveRealValue(APFloat::IEEEsingle);
   1306       case DK_DOUBLE:
   1307         return ParseDirectiveRealValue(APFloat::IEEEdouble);
   1308       case DK_ALIGN: {
   1309         bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
   1310         return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
   1311       }
   1312       case DK_ALIGN32: {
   1313         bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
   1314         return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
   1315       }
   1316       case DK_BALIGN:
   1317         return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
   1318       case DK_BALIGNW:
   1319         return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
   1320       case DK_BALIGNL:
   1321         return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
   1322       case DK_P2ALIGN:
   1323         return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
   1324       case DK_P2ALIGNW:
   1325         return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
   1326       case DK_P2ALIGNL:
   1327         return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
   1328       case DK_ORG:
   1329         return ParseDirectiveOrg();
   1330       case DK_FILL:
   1331         return ParseDirectiveFill();
   1332       case DK_ZERO:
   1333         return ParseDirectiveZero();
   1334       case DK_EXTERN:
   1335         eatToEndOfStatement(); // .extern is the default, ignore it.
   1336         return false;
   1337       case DK_GLOBL:
   1338       case DK_GLOBAL:
   1339         return ParseDirectiveSymbolAttribute(MCSA_Global);
   1340       case DK_INDIRECT_SYMBOL:
   1341         return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
   1342       case DK_LAZY_REFERENCE:
   1343         return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
   1344       case DK_NO_DEAD_STRIP:
   1345         return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
   1346       case DK_SYMBOL_RESOLVER:
   1347         return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
   1348       case DK_PRIVATE_EXTERN:
   1349         return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
   1350       case DK_REFERENCE:
   1351         return ParseDirectiveSymbolAttribute(MCSA_Reference);
   1352       case DK_WEAK_DEFINITION:
   1353         return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
   1354       case DK_WEAK_REFERENCE:
   1355         return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
   1356       case DK_WEAK_DEF_CAN_BE_HIDDEN:
   1357         return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
   1358       case DK_COMM:
   1359       case DK_COMMON:
   1360         return ParseDirectiveComm(/*IsLocal=*/false);
   1361       case DK_LCOMM:
   1362         return ParseDirectiveComm(/*IsLocal=*/true);
   1363       case DK_ABORT:
   1364         return ParseDirectiveAbort();
   1365       case DK_INCLUDE:
   1366         return ParseDirectiveInclude();
   1367       case DK_INCBIN:
   1368         return ParseDirectiveIncbin();
   1369       case DK_CODE16:
   1370       case DK_CODE16GCC:
   1371         return TokError(Twine(IDVal) + " not supported yet");
   1372       case DK_REPT:
   1373         return ParseDirectiveRept(IDLoc);
   1374       case DK_IRP:
   1375         return ParseDirectiveIrp(IDLoc);
   1376       case DK_IRPC:
   1377         return ParseDirectiveIrpc(IDLoc);
   1378       case DK_ENDR:
   1379         return ParseDirectiveEndr(IDLoc);
   1380       case DK_BUNDLE_ALIGN_MODE:
   1381         return ParseDirectiveBundleAlignMode();
   1382       case DK_BUNDLE_LOCK:
   1383         return ParseDirectiveBundleLock();
   1384       case DK_BUNDLE_UNLOCK:
   1385         return ParseDirectiveBundleUnlock();
   1386       case DK_SLEB128:
   1387         return ParseDirectiveLEB128(true);
   1388       case DK_ULEB128:
   1389         return ParseDirectiveLEB128(false);
   1390       case DK_SPACE:
   1391       case DK_SKIP:
   1392         return ParseDirectiveSpace(IDVal);
   1393       case DK_FILE:
   1394         return ParseDirectiveFile(IDLoc);
   1395       case DK_LINE:
   1396         return ParseDirectiveLine();
   1397       case DK_LOC:
   1398         return ParseDirectiveLoc();
   1399       case DK_STABS:
   1400         return ParseDirectiveStabs();
   1401       case DK_CFI_SECTIONS:
   1402         return ParseDirectiveCFISections();
   1403       case DK_CFI_STARTPROC:
   1404         return ParseDirectiveCFIStartProc();
   1405       case DK_CFI_ENDPROC:
   1406         return ParseDirectiveCFIEndProc();
   1407       case DK_CFI_DEF_CFA:
   1408         return ParseDirectiveCFIDefCfa(IDLoc);
   1409       case DK_CFI_DEF_CFA_OFFSET:
   1410         return ParseDirectiveCFIDefCfaOffset();
   1411       case DK_CFI_ADJUST_CFA_OFFSET:
   1412         return ParseDirectiveCFIAdjustCfaOffset();
   1413       case DK_CFI_DEF_CFA_REGISTER:
   1414         return ParseDirectiveCFIDefCfaRegister(IDLoc);
   1415       case DK_CFI_OFFSET:
   1416         return ParseDirectiveCFIOffset(IDLoc);
   1417       case DK_CFI_REL_OFFSET:
   1418         return ParseDirectiveCFIRelOffset(IDLoc);
   1419       case DK_CFI_PERSONALITY:
   1420         return ParseDirectiveCFIPersonalityOrLsda(true);
   1421       case DK_CFI_LSDA:
   1422         return ParseDirectiveCFIPersonalityOrLsda(false);
   1423       case DK_CFI_REMEMBER_STATE:
   1424         return ParseDirectiveCFIRememberState();
   1425       case DK_CFI_RESTORE_STATE:
   1426         return ParseDirectiveCFIRestoreState();
   1427       case DK_CFI_SAME_VALUE:
   1428         return ParseDirectiveCFISameValue(IDLoc);
   1429       case DK_CFI_RESTORE:
   1430         return ParseDirectiveCFIRestore(IDLoc);
   1431       case DK_CFI_ESCAPE:
   1432         return ParseDirectiveCFIEscape();
   1433       case DK_CFI_SIGNAL_FRAME:
   1434         return ParseDirectiveCFISignalFrame();
   1435       case DK_CFI_UNDEFINED:
   1436         return ParseDirectiveCFIUndefined(IDLoc);
   1437       case DK_CFI_REGISTER:
   1438         return ParseDirectiveCFIRegister(IDLoc);
   1439       case DK_MACROS_ON:
   1440       case DK_MACROS_OFF:
   1441         return ParseDirectiveMacrosOnOff(IDVal);
   1442       case DK_MACRO:
   1443         return ParseDirectiveMacro(IDLoc);
   1444       case DK_ENDM:
   1445       case DK_ENDMACRO:
   1446         return ParseDirectiveEndMacro(IDVal);
   1447       case DK_PURGEM:
   1448         return ParseDirectivePurgeMacro(IDLoc);
   1449     }
   1450 
   1451     return Error(IDLoc, "unknown directive");
   1452   }
   1453 
   1454   // __asm _emit or __asm __emit
   1455   if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
   1456                            IDVal == "_EMIT" || IDVal == "__EMIT"))
   1457     return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
   1458 
   1459   // __asm align
   1460   if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
   1461     return ParseDirectiveMSAlign(IDLoc, Info);
   1462 
   1463   checkForValidSection();
   1464 
   1465   // Canonicalize the opcode to lower case.
   1466   std::string OpcodeStr = IDVal.lower();
   1467   ParseInstructionInfo IInfo(Info.AsmRewrites);
   1468   bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
   1469                                                      IDLoc, Info.ParsedOperands);
   1470   Info.ParseError = HadError;
   1471 
   1472   // Dump the parsed representation, if requested.
   1473   if (getShowParsedOperands()) {
   1474     SmallString<256> Str;
   1475     raw_svector_ostream OS(Str);
   1476     OS << "parsed instruction: [";
   1477     for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
   1478       if (i != 0)
   1479         OS << ", ";
   1480       Info.ParsedOperands[i]->print(OS);
   1481     }
   1482     OS << "]";
   1483 
   1484     PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
   1485   }
   1486 
   1487   // If we are generating dwarf for assembly source files and the current
   1488   // section is the initial text section then generate a .loc directive for
   1489   // the instruction.
   1490   if (!HadError && getContext().getGenDwarfForAssembly() &&
   1491       getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
   1492 
   1493     unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
   1494 
   1495     // If we previously parsed a cpp hash file line comment then make sure the
   1496     // current Dwarf File is for the CppHashFilename if not then emit the
   1497     // Dwarf File table for it and adjust the line number for the .loc.
   1498     const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
   1499       getContext().getMCDwarfFiles();
   1500     if (CppHashFilename.size() != 0) {
   1501       if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
   1502           CppHashFilename)
   1503         getStreamer().EmitDwarfFileDirective(
   1504           getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
   1505 
   1506        unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
   1507        Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
   1508     }
   1509 
   1510     getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
   1511                                         Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
   1512                                         DWARF2_FLAG_IS_STMT : 0, 0, 0,
   1513                                         StringRef());
   1514   }
   1515 
   1516   // If parsing succeeded, match the instruction.
   1517   if (!HadError) {
   1518     unsigned ErrorInfo;
   1519     HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
   1520                                                          Info.ParsedOperands,
   1521                                                          Out, ErrorInfo,
   1522                                                          ParsingInlineAsm);
   1523   }
   1524 
   1525   // Don't skip the rest of the line, the instruction parser is responsible for
   1526   // that.
   1527   return false;
   1528 }
   1529 
   1530 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
   1531 /// since they may not be able to be tokenized to get to the end of line token.
   1532 void AsmParser::EatToEndOfLine() {
   1533   if (!Lexer.is(AsmToken::EndOfStatement))
   1534     Lexer.LexUntilEndOfLine();
   1535  // Eat EOL.
   1536  Lex();
   1537 }
   1538 
   1539 /// ParseCppHashLineFilenameComment as this:
   1540 ///   ::= # number "filename"
   1541 /// or just as a full line comment if it doesn't have a number and a string.
   1542 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
   1543   Lex(); // Eat the hash token.
   1544 
   1545   if (getLexer().isNot(AsmToken::Integer)) {
   1546     // Consume the line since in cases it is not a well-formed line directive,
   1547     // as if were simply a full line comment.
   1548     EatToEndOfLine();
   1549     return false;
   1550   }
   1551 
   1552   int64_t LineNumber = getTok().getIntVal();
   1553   Lex();
   1554 
   1555   if (getLexer().isNot(AsmToken::String)) {
   1556     EatToEndOfLine();
   1557     return false;
   1558   }
   1559 
   1560   StringRef Filename = getTok().getString();
   1561   // Get rid of the enclosing quotes.
   1562   Filename = Filename.substr(1, Filename.size()-2);
   1563 
   1564   // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
   1565   CppHashLoc = L;
   1566   CppHashFilename = Filename;
   1567   CppHashLineNumber = LineNumber;
   1568   CppHashBuf = CurBuffer;
   1569 
   1570   // Ignore any trailing characters, they're just comment.
   1571   EatToEndOfLine();
   1572   return false;
   1573 }
   1574 
   1575 /// DiagHandler - will use the last parsed cpp hash line filename comment
   1576 /// for the Filename and LineNo if any in the diagnostic.
   1577 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
   1578   const AsmParser *Parser = static_cast<const AsmParser*>(Context);
   1579   raw_ostream &OS = errs();
   1580 
   1581   const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
   1582   const SMLoc &DiagLoc = Diag.getLoc();
   1583   int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
   1584   int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
   1585 
   1586   // Like SourceMgr::PrintMessage() we need to print the include stack if any
   1587   // before printing the message.
   1588   int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
   1589   if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
   1590      SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
   1591      DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
   1592   }
   1593 
   1594   // If we have not parsed a cpp hash line filename comment or the source
   1595   // manager changed or buffer changed (like in a nested include) then just
   1596   // print the normal diagnostic using its Filename and LineNo.
   1597   if (!Parser->CppHashLineNumber ||
   1598       &DiagSrcMgr != &Parser->SrcMgr ||
   1599       DiagBuf != CppHashBuf) {
   1600     if (Parser->SavedDiagHandler)
   1601       Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
   1602     else
   1603       Diag.print(0, OS);
   1604     return;
   1605   }
   1606 
   1607   // Use the CppHashFilename and calculate a line number based on the
   1608   // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
   1609   // the diagnostic.
   1610   const std::string Filename = Parser->CppHashFilename;
   1611 
   1612   int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
   1613   int CppHashLocLineNo =
   1614       Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
   1615   int LineNo = Parser->CppHashLineNumber - 1 +
   1616                (DiagLocLineNo - CppHashLocLineNo);
   1617 
   1618   SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
   1619                        Filename, LineNo, Diag.getColumnNo(),
   1620                        Diag.getKind(), Diag.getMessage(),
   1621                        Diag.getLineContents(), Diag.getRanges());
   1622 
   1623   if (Parser->SavedDiagHandler)
   1624     Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
   1625   else
   1626     NewDiag.print(0, OS);
   1627 }
   1628 
   1629 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
   1630 // difference being that that function accepts '@' as part of identifiers and
   1631 // we can't do that. AsmLexer.cpp should probably be changed to handle
   1632 // '@' as a special case when needed.
   1633 static bool isIdentifierChar(char c) {
   1634   return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
   1635          c == '.';
   1636 }
   1637 
   1638 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
   1639                             const MCAsmMacroParameters &Parameters,
   1640                             const MCAsmMacroArguments &A,
   1641                             const SMLoc &L) {
   1642   unsigned NParameters = Parameters.size();
   1643   if (NParameters != 0 && NParameters != A.size())
   1644     return Error(L, "Wrong number of arguments");
   1645 
   1646   // A macro without parameters is handled differently on Darwin:
   1647   // gas accepts no arguments and does no substitutions
   1648   while (!Body.empty()) {
   1649     // Scan for the next substitution.
   1650     std::size_t End = Body.size(), Pos = 0;
   1651     for (; Pos != End; ++Pos) {
   1652       // Check for a substitution or escape.
   1653       if (!NParameters) {
   1654         // This macro has no parameters, look for $0, $1, etc.
   1655         if (Body[Pos] != '$' || Pos + 1 == End)
   1656           continue;
   1657 
   1658         char Next = Body[Pos + 1];
   1659         if (Next == '$' || Next == 'n' ||
   1660             isdigit(static_cast<unsigned char>(Next)))
   1661           break;
   1662       } else {
   1663         // This macro has parameters, look for \foo, \bar, etc.
   1664         if (Body[Pos] == '\\' && Pos + 1 != End)
   1665           break;
   1666       }
   1667     }
   1668 
   1669     // Add the prefix.
   1670     OS << Body.slice(0, Pos);
   1671 
   1672     // Check if we reached the end.
   1673     if (Pos == End)
   1674       break;
   1675 
   1676     if (!NParameters) {
   1677       switch (Body[Pos+1]) {
   1678         // $$ => $
   1679       case '$':
   1680         OS << '$';
   1681         break;
   1682 
   1683         // $n => number of arguments
   1684       case 'n':
   1685         OS << A.size();
   1686         break;
   1687 
   1688         // $[0-9] => argument
   1689       default: {
   1690         // Missing arguments are ignored.
   1691         unsigned Index = Body[Pos+1] - '0';
   1692         if (Index >= A.size())
   1693           break;
   1694 
   1695         // Otherwise substitute with the token values, with spaces eliminated.
   1696         for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
   1697                ie = A[Index].end(); it != ie; ++it)
   1698           OS << it->getString();
   1699         break;
   1700       }
   1701       }
   1702       Pos += 2;
   1703     } else {
   1704       unsigned I = Pos + 1;
   1705       while (isIdentifierChar(Body[I]) && I + 1 != End)
   1706         ++I;
   1707 
   1708       const char *Begin = Body.data() + Pos +1;
   1709       StringRef Argument(Begin, I - (Pos +1));
   1710       unsigned Index = 0;
   1711       for (; Index < NParameters; ++Index)
   1712         if (Parameters[Index].first == Argument)
   1713           break;
   1714 
   1715       if (Index == NParameters) {
   1716           if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
   1717             Pos += 3;
   1718           else {
   1719             OS << '\\' << Argument;
   1720             Pos = I;
   1721           }
   1722       } else {
   1723         for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
   1724                ie = A[Index].end(); it != ie; ++it)
   1725           if (it->getKind() == AsmToken::String)
   1726             OS << it->getStringContents();
   1727           else
   1728             OS << it->getString();
   1729 
   1730         Pos += 1 + Argument.size();
   1731       }
   1732     }
   1733     // Update the scan point.
   1734     Body = Body.substr(Pos);
   1735   }
   1736 
   1737   return false;
   1738 }
   1739 
   1740 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
   1741                                        int EB, SMLoc EL,
   1742                                        MemoryBuffer *I)
   1743   : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
   1744     ExitLoc(EL)
   1745 {
   1746 }
   1747 
   1748 static bool IsOperator(AsmToken::TokenKind kind)
   1749 {
   1750   switch (kind)
   1751   {
   1752     default:
   1753       return false;
   1754     case AsmToken::Plus:
   1755     case AsmToken::Minus:
   1756     case AsmToken::Tilde:
   1757     case AsmToken::Slash:
   1758     case AsmToken::Star:
   1759     case AsmToken::Dot:
   1760     case AsmToken::Equal:
   1761     case AsmToken::EqualEqual:
   1762     case AsmToken::Pipe:
   1763     case AsmToken::PipePipe:
   1764     case AsmToken::Caret:
   1765     case AsmToken::Amp:
   1766     case AsmToken::AmpAmp:
   1767     case AsmToken::Exclaim:
   1768     case AsmToken::ExclaimEqual:
   1769     case AsmToken::Percent:
   1770     case AsmToken::Less:
   1771     case AsmToken::LessEqual:
   1772     case AsmToken::LessLess:
   1773     case AsmToken::LessGreater:
   1774     case AsmToken::Greater:
   1775     case AsmToken::GreaterEqual:
   1776     case AsmToken::GreaterGreater:
   1777       return true;
   1778   }
   1779 }
   1780 
   1781 bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
   1782                                    AsmToken::TokenKind &ArgumentDelimiter) {
   1783   unsigned ParenLevel = 0;
   1784   unsigned AddTokens = 0;
   1785 
   1786   // gas accepts arguments separated by whitespace, except on Darwin
   1787   if (!IsDarwin)
   1788     Lexer.setSkipSpace(false);
   1789 
   1790   for (;;) {
   1791     if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
   1792       Lexer.setSkipSpace(true);
   1793       return TokError("unexpected token in macro instantiation");
   1794     }
   1795 
   1796     if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
   1797       // Spaces and commas cannot be mixed to delimit parameters
   1798       if (ArgumentDelimiter == AsmToken::Eof)
   1799         ArgumentDelimiter = AsmToken::Comma;
   1800       else if (ArgumentDelimiter != AsmToken::Comma) {
   1801         Lexer.setSkipSpace(true);
   1802         return TokError("expected ' ' for macro argument separator");
   1803       }
   1804       break;
   1805     }
   1806 
   1807     if (Lexer.is(AsmToken::Space)) {
   1808       Lex(); // Eat spaces
   1809 
   1810       // Spaces can delimit parameters, but could also be part an expression.
   1811       // If the token after a space is an operator, add the token and the next
   1812       // one into this argument
   1813       if (ArgumentDelimiter == AsmToken::Space ||
   1814           ArgumentDelimiter == AsmToken::Eof) {
   1815         if (IsOperator(Lexer.getKind())) {
   1816           // Check to see whether the token is used as an operator,
   1817           // or part of an identifier
   1818           const char *NextChar = getTok().getEndLoc().getPointer();
   1819           if (*NextChar == ' ')
   1820             AddTokens = 2;
   1821         }
   1822 
   1823         if (!AddTokens && ParenLevel == 0) {
   1824           if (ArgumentDelimiter == AsmToken::Eof &&
   1825               !IsOperator(Lexer.getKind()))
   1826             ArgumentDelimiter = AsmToken::Space;
   1827           break;
   1828         }
   1829       }
   1830     }
   1831 
   1832     // HandleMacroEntry relies on not advancing the lexer here
   1833     // to be able to fill in the remaining default parameter values
   1834     if (Lexer.is(AsmToken::EndOfStatement))
   1835       break;
   1836 
   1837     // Adjust the current parentheses level.
   1838     if (Lexer.is(AsmToken::LParen))
   1839       ++ParenLevel;
   1840     else if (Lexer.is(AsmToken::RParen) && ParenLevel)
   1841       --ParenLevel;
   1842 
   1843     // Append the token to the current argument list.
   1844     MA.push_back(getTok());
   1845     if (AddTokens)
   1846       AddTokens--;
   1847     Lex();
   1848   }
   1849 
   1850   Lexer.setSkipSpace(true);
   1851   if (ParenLevel != 0)
   1852     return TokError("unbalanced parentheses in macro argument");
   1853   return false;
   1854 }
   1855 
   1856 // Parse the macro instantiation arguments.
   1857 bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
   1858   const unsigned NParameters = M ? M->Parameters.size() : 0;
   1859   // Argument delimiter is initially unknown. It will be set by
   1860   // ParseMacroArgument()
   1861   AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
   1862 
   1863   // Parse two kinds of macro invocations:
   1864   // - macros defined without any parameters accept an arbitrary number of them
   1865   // - macros defined with parameters accept at most that many of them
   1866   for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
   1867        ++Parameter) {
   1868     MCAsmMacroArgument MA;
   1869 
   1870     if (ParseMacroArgument(MA, ArgumentDelimiter))
   1871       return true;
   1872 
   1873     if (!MA.empty() || !NParameters)
   1874       A.push_back(MA);
   1875     else if (NParameters) {
   1876       if (!M->Parameters[Parameter].second.empty())
   1877         A.push_back(M->Parameters[Parameter].second);
   1878     }
   1879 
   1880     // At the end of the statement, fill in remaining arguments that have
   1881     // default values. If there aren't any, then the next argument is
   1882     // required but missing
   1883     if (Lexer.is(AsmToken::EndOfStatement)) {
   1884       if (NParameters && Parameter < NParameters - 1) {
   1885         if (M->Parameters[Parameter + 1].second.empty())
   1886           return TokError("macro argument '" +
   1887                           Twine(M->Parameters[Parameter + 1].first) +
   1888                           "' is missing");
   1889         else
   1890           continue;
   1891       }
   1892       return false;
   1893     }
   1894 
   1895     if (Lexer.is(AsmToken::Comma))
   1896       Lex();
   1897   }
   1898   return TokError("Too many arguments");
   1899 }
   1900 
   1901 const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
   1902   StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
   1903   return (I == MacroMap.end()) ? NULL : I->getValue();
   1904 }
   1905 
   1906 void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
   1907   MacroMap[Name] = new MCAsmMacro(Macro);
   1908 }
   1909 
   1910 void AsmParser::UndefineMacro(StringRef Name) {
   1911   StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
   1912   if (I != MacroMap.end()) {
   1913     delete I->getValue();
   1914     MacroMap.erase(I);
   1915   }
   1916 }
   1917 
   1918 bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
   1919   // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
   1920   // this, although we should protect against infinite loops.
   1921   if (ActiveMacros.size() == 20)
   1922     return TokError("macros cannot be nested more than 20 levels deep");
   1923 
   1924   MCAsmMacroArguments A;
   1925   if (ParseMacroArguments(M, A))
   1926     return true;
   1927 
   1928   // Remove any trailing empty arguments. Do this after-the-fact as we have
   1929   // to keep empty arguments in the middle of the list or positionality
   1930   // gets off. e.g.,  "foo 1, , 2" vs. "foo 1, 2,"
   1931   while (!A.empty() && A.back().empty())
   1932     A.pop_back();
   1933 
   1934   // Macro instantiation is lexical, unfortunately. We construct a new buffer
   1935   // to hold the macro body with substitutions.
   1936   SmallString<256> Buf;
   1937   StringRef Body = M->Body;
   1938   raw_svector_ostream OS(Buf);
   1939 
   1940   if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
   1941     return true;
   1942 
   1943   // We include the .endmacro in the buffer as our cue to exit the macro
   1944   // instantiation.
   1945   OS << ".endmacro\n";
   1946 
   1947   MemoryBuffer *Instantiation =
   1948     MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
   1949 
   1950   // Create the macro instantiation object and add to the current macro
   1951   // instantiation stack.
   1952   MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
   1953                                                   CurBuffer,
   1954                                                   getTok().getLoc(),
   1955                                                   Instantiation);
   1956   ActiveMacros.push_back(MI);
   1957 
   1958   // Jump to the macro instantiation and prime the lexer.
   1959   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
   1960   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
   1961   Lex();
   1962 
   1963   return false;
   1964 }
   1965 
   1966 void AsmParser::HandleMacroExit() {
   1967   // Jump to the EndOfStatement we should return to, and consume it.
   1968   JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
   1969   Lex();
   1970 
   1971   // Pop the instantiation entry.
   1972   delete ActiveMacros.back();
   1973   ActiveMacros.pop_back();
   1974 }
   1975 
   1976 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
   1977   switch (Value->getKind()) {
   1978   case MCExpr::Binary: {
   1979     const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
   1980     return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
   1981     break;
   1982   }
   1983   case MCExpr::Target:
   1984   case MCExpr::Constant:
   1985     return false;
   1986   case MCExpr::SymbolRef: {
   1987     const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
   1988     if (S.isVariable())
   1989       return IsUsedIn(Sym, S.getVariableValue());
   1990     return &S == Sym;
   1991   }
   1992   case MCExpr::Unary:
   1993     return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
   1994   }
   1995 
   1996   llvm_unreachable("Unknown expr kind!");
   1997 }
   1998 
   1999 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
   2000                                 bool NoDeadStrip) {
   2001   // FIXME: Use better location, we should use proper tokens.
   2002   SMLoc EqualLoc = Lexer.getLoc();
   2003 
   2004   const MCExpr *Value;
   2005   if (parseExpression(Value))
   2006     return true;
   2007 
   2008   // Note: we don't count b as used in "a = b". This is to allow
   2009   // a = b
   2010   // b = c
   2011 
   2012   if (Lexer.isNot(AsmToken::EndOfStatement))
   2013     return TokError("unexpected token in assignment");
   2014 
   2015   // Error on assignment to '.'.
   2016   if (Name == ".") {
   2017     return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
   2018                             "(use '.space' or '.org').)"));
   2019   }
   2020 
   2021   // Eat the end of statement marker.
   2022   Lex();
   2023 
   2024   // Validate that the LHS is allowed to be a variable (either it has not been
   2025   // used as a symbol, or it is an absolute symbol).
   2026   MCSymbol *Sym = getContext().LookupSymbol(Name);
   2027   if (Sym) {
   2028     // Diagnose assignment to a label.
   2029     //
   2030     // FIXME: Diagnostics. Note the location of the definition as a label.
   2031     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
   2032     if (IsUsedIn(Sym, Value))
   2033       return Error(EqualLoc, "Recursive use of '" + Name + "'");
   2034     else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
   2035       ; // Allow redefinitions of undefined symbols only used in directives.
   2036     else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
   2037       ; // Allow redefinitions of variables that haven't yet been used.
   2038     else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
   2039       return Error(EqualLoc, "redefinition of '" + Name + "'");
   2040     else if (!Sym->isVariable())
   2041       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
   2042     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
   2043       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
   2044                    Name + "'");
   2045 
   2046     // Don't count these checks as uses.
   2047     Sym->setUsed(false);
   2048   } else
   2049     Sym = getContext().GetOrCreateSymbol(Name);
   2050 
   2051   // FIXME: Handle '.'.
   2052 
   2053   // Do the assignment.
   2054   Out.EmitAssignment(Sym, Value);
   2055   if (NoDeadStrip)
   2056     Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
   2057 
   2058 
   2059   return false;
   2060 }
   2061 
   2062 /// parseIdentifier:
   2063 ///   ::= identifier
   2064 ///   ::= string
   2065 bool AsmParser::parseIdentifier(StringRef &Res) {
   2066   // The assembler has relaxed rules for accepting identifiers, in particular we
   2067   // allow things like '.globl $foo', which would normally be separate
   2068   // tokens. At this level, we have already lexed so we cannot (currently)
   2069   // handle this as a context dependent token, instead we detect adjacent tokens
   2070   // and return the combined identifier.
   2071   if (Lexer.is(AsmToken::Dollar)) {
   2072     SMLoc DollarLoc = getLexer().getLoc();
   2073 
   2074     // Consume the dollar sign, and check for a following identifier.
   2075     Lex();
   2076     if (Lexer.isNot(AsmToken::Identifier))
   2077       return true;
   2078 
   2079     // We have a '$' followed by an identifier, make sure they are adjacent.
   2080     if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
   2081       return true;
   2082 
   2083     // Construct the joined identifier and consume the token.
   2084     Res = StringRef(DollarLoc.getPointer(),
   2085                     getTok().getIdentifier().size() + 1);
   2086     Lex();
   2087     return false;
   2088   }
   2089 
   2090   if (Lexer.isNot(AsmToken::Identifier) &&
   2091       Lexer.isNot(AsmToken::String))
   2092     return true;
   2093 
   2094   Res = getTok().getIdentifier();
   2095 
   2096   Lex(); // Consume the identifier token.
   2097 
   2098   return false;
   2099 }
   2100 
   2101 /// ParseDirectiveSet:
   2102 ///   ::= .equ identifier ',' expression
   2103 ///   ::= .equiv identifier ',' expression
   2104 ///   ::= .set identifier ',' expression
   2105 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
   2106   StringRef Name;
   2107 
   2108   if (parseIdentifier(Name))
   2109     return TokError("expected identifier after '" + Twine(IDVal) + "'");
   2110 
   2111   if (getLexer().isNot(AsmToken::Comma))
   2112     return TokError("unexpected token in '" + Twine(IDVal) + "'");
   2113   Lex();
   2114 
   2115   return ParseAssignment(Name, allow_redef, true);
   2116 }
   2117 
   2118 bool AsmParser::parseEscapedString(std::string &Data) {
   2119   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
   2120 
   2121   Data = "";
   2122   StringRef Str = getTok().getStringContents();
   2123   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
   2124     if (Str[i] != '\\') {
   2125       Data += Str[i];
   2126       continue;
   2127     }
   2128 
   2129     // Recognize escaped characters. Note that this escape semantics currently
   2130     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
   2131     ++i;
   2132     if (i == e)
   2133       return TokError("unexpected backslash at end of string");
   2134 
   2135     // Recognize octal sequences.
   2136     if ((unsigned) (Str[i] - '0') <= 7) {
   2137       // Consume up to three octal characters.
   2138       unsigned Value = Str[i] - '0';
   2139 
   2140       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
   2141         ++i;
   2142         Value = Value * 8 + (Str[i] - '0');
   2143 
   2144         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
   2145           ++i;
   2146           Value = Value * 8 + (Str[i] - '0');
   2147         }
   2148       }
   2149 
   2150       if (Value > 255)
   2151         return TokError("invalid octal escape sequence (out of range)");
   2152 
   2153       Data += (unsigned char) Value;
   2154       continue;
   2155     }
   2156 
   2157     // Otherwise recognize individual escapes.
   2158     switch (Str[i]) {
   2159     default:
   2160       // Just reject invalid escape sequences for now.
   2161       return TokError("invalid escape sequence (unrecognized character)");
   2162 
   2163     case 'b': Data += '\b'; break;
   2164     case 'f': Data += '\f'; break;
   2165     case 'n': Data += '\n'; break;
   2166     case 'r': Data += '\r'; break;
   2167     case 't': Data += '\t'; break;
   2168     case '"': Data += '"'; break;
   2169     case '\\': Data += '\\'; break;
   2170     }
   2171   }
   2172 
   2173   return false;
   2174 }
   2175 
   2176 /// ParseDirectiveAscii:
   2177 ///   ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
   2178 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
   2179   if (getLexer().isNot(AsmToken::EndOfStatement)) {
   2180     checkForValidSection();
   2181 
   2182     for (;;) {
   2183       if (getLexer().isNot(AsmToken::String))
   2184         return TokError("expected string in '" + Twine(IDVal) + "' directive");
   2185 
   2186       std::string Data;
   2187       if (parseEscapedString(Data))
   2188         return true;
   2189 
   2190       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
   2191       if (ZeroTerminated)
   2192         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
   2193 
   2194       Lex();
   2195 
   2196       if (getLexer().is(AsmToken::EndOfStatement))
   2197         break;
   2198 
   2199       if (getLexer().isNot(AsmToken::Comma))
   2200         return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
   2201       Lex();
   2202     }
   2203   }
   2204 
   2205   Lex();
   2206   return false;
   2207 }
   2208 
   2209 /// ParseDirectiveValue
   2210 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
   2211 bool AsmParser::ParseDirectiveValue(unsigned Size) {
   2212   if (getLexer().isNot(AsmToken::EndOfStatement)) {
   2213     checkForValidSection();
   2214 
   2215     for (;;) {
   2216       const MCExpr *Value;
   2217       SMLoc ExprLoc = getLexer().getLoc();
   2218       if (parseExpression(Value))
   2219         return true;
   2220 
   2221       // Special case constant expressions to match code generator.
   2222       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
   2223         assert(Size <= 8 && "Invalid size");
   2224         uint64_t IntValue = MCE->getValue();
   2225         if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
   2226           return Error(ExprLoc, "literal value out of range for directive");
   2227         getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
   2228       } else
   2229         getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
   2230 
   2231       if (getLexer().is(AsmToken::EndOfStatement))
   2232         break;
   2233 
   2234       // FIXME: Improve diagnostic.
   2235       if (getLexer().isNot(AsmToken::Comma))
   2236         return TokError("unexpected token in directive");
   2237       Lex();
   2238     }
   2239   }
   2240 
   2241   Lex();
   2242   return false;
   2243 }
   2244 
   2245 /// ParseDirectiveRealValue
   2246 ///  ::= (.single | .double) [ expression (, expression)* ]
   2247 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
   2248   if (getLexer().isNot(AsmToken::EndOfStatement)) {
   2249     checkForValidSection();
   2250 
   2251     for (;;) {
   2252       // We don't truly support arithmetic on floating point expressions, so we
   2253       // have to manually parse unary prefixes.
   2254       bool IsNeg = false;
   2255       if (getLexer().is(AsmToken::Minus)) {
   2256         Lex();
   2257         IsNeg = true;
   2258       } else if (getLexer().is(AsmToken::Plus))
   2259         Lex();
   2260 
   2261       if (getLexer().isNot(AsmToken::Integer) &&
   2262           getLexer().isNot(AsmToken::Real) &&
   2263           getLexer().isNot(AsmToken::Identifier))
   2264         return TokError("unexpected token in directive");
   2265 
   2266       // Convert to an APFloat.
   2267       APFloat Value(Semantics);
   2268       StringRef IDVal = getTok().getString();
   2269       if (getLexer().is(AsmToken::Identifier)) {
   2270         if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
   2271           Value = APFloat::getInf(Semantics);
   2272         else if (!IDVal.compare_lower("nan"))
   2273           Value = APFloat::getNaN(Semantics, false, ~0);
   2274         else
   2275           return TokError("invalid floating point literal");
   2276       } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
   2277           APFloat::opInvalidOp)
   2278         return TokError("invalid floating point literal");
   2279       if (IsNeg)
   2280         Value.changeSign();
   2281 
   2282       // Consume the numeric token.
   2283       Lex();
   2284 
   2285       // Emit the value as an integer.
   2286       APInt AsInt = Value.bitcastToAPInt();
   2287       getStreamer().EmitIntValue(AsInt.getLimitedValue(),
   2288                                  AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
   2289 
   2290       if (getLexer().is(AsmToken::EndOfStatement))
   2291         break;
   2292 
   2293       if (getLexer().isNot(AsmToken::Comma))
   2294         return TokError("unexpected token in directive");
   2295       Lex();
   2296     }
   2297   }
   2298 
   2299   Lex();
   2300   return false;
   2301 }
   2302 
   2303 /// ParseDirectiveZero
   2304 ///  ::= .zero expression
   2305 bool AsmParser::ParseDirectiveZero() {
   2306   checkForValidSection();
   2307 
   2308   int64_t NumBytes;
   2309   if (parseAbsoluteExpression(NumBytes))
   2310     return true;
   2311 
   2312   int64_t Val = 0;
   2313   if (getLexer().is(AsmToken::Comma)) {
   2314     Lex();
   2315     if (parseAbsoluteExpression(Val))
   2316       return true;
   2317   }
   2318 
   2319   if (getLexer().isNot(AsmToken::EndOfStatement))
   2320     return TokError("unexpected token in '.zero' directive");
   2321 
   2322   Lex();
   2323 
   2324   getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
   2325 
   2326   return false;
   2327 }
   2328 
   2329 /// ParseDirectiveFill
   2330 ///  ::= .fill expression , expression , expression
   2331 bool AsmParser::ParseDirectiveFill() {
   2332   checkForValidSection();
   2333 
   2334   int64_t NumValues;
   2335   if (parseAbsoluteExpression(NumValues))
   2336     return true;
   2337 
   2338   if (getLexer().isNot(AsmToken::Comma))
   2339     return TokError("unexpected token in '.fill' directive");
   2340   Lex();
   2341 
   2342   int64_t FillSize;
   2343   if (parseAbsoluteExpression(FillSize))
   2344     return true;
   2345 
   2346   if (getLexer().isNot(AsmToken::Comma))
   2347     return TokError("unexpected token in '.fill' directive");
   2348   Lex();
   2349 
   2350   int64_t FillExpr;
   2351   if (parseAbsoluteExpression(FillExpr))
   2352     return true;
   2353 
   2354   if (getLexer().isNot(AsmToken::EndOfStatement))
   2355     return TokError("unexpected token in '.fill' directive");
   2356 
   2357   Lex();
   2358 
   2359   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
   2360     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
   2361 
   2362   for (uint64_t i = 0, e = NumValues; i != e; ++i)
   2363     getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
   2364 
   2365   return false;
   2366 }
   2367 
   2368 /// ParseDirectiveOrg
   2369 ///  ::= .org expression [ , expression ]
   2370 bool AsmParser::ParseDirectiveOrg() {
   2371   checkForValidSection();
   2372 
   2373   const MCExpr *Offset;
   2374   SMLoc Loc = getTok().getLoc();
   2375   if (parseExpression(Offset))
   2376     return true;
   2377 
   2378   // Parse optional fill expression.
   2379   int64_t FillExpr = 0;
   2380   if (getLexer().isNot(AsmToken::EndOfStatement)) {
   2381     if (getLexer().isNot(AsmToken::Comma))
   2382       return TokError("unexpected token in '.org' directive");
   2383     Lex();
   2384 
   2385     if (parseAbsoluteExpression(FillExpr))
   2386       return true;
   2387 
   2388     if (getLexer().isNot(AsmToken::EndOfStatement))
   2389       return TokError("unexpected token in '.org' directive");
   2390   }
   2391 
   2392   Lex();
   2393 
   2394   // Only limited forms of relocatable expressions are accepted here, it
   2395   // has to be relative to the current section. The streamer will return
   2396   // 'true' if the expression wasn't evaluatable.
   2397   if (getStreamer().EmitValueToOffset(Offset, FillExpr))
   2398     return Error(Loc, "expected assembly-time absolute expression");
   2399 
   2400   return false;
   2401 }
   2402 
   2403 /// ParseDirectiveAlign
   2404 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
   2405 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
   2406   checkForValidSection();
   2407 
   2408   SMLoc AlignmentLoc = getLexer().getLoc();
   2409   int64_t Alignment;
   2410   if (parseAbsoluteExpression(Alignment))
   2411     return true;
   2412 
   2413   SMLoc MaxBytesLoc;
   2414   bool HasFillExpr = false;
   2415   int64_t FillExpr = 0;
   2416   int64_t MaxBytesToFill = 0;
   2417   if (getLexer().isNot(AsmToken::EndOfStatement)) {
   2418     if (getLexer().isNot(AsmToken::Comma))
   2419       return TokError("unexpected token in directive");
   2420     Lex();
   2421 
   2422     // The fill expression can be omitted while specifying a maximum number of
   2423     // alignment bytes, e.g:
   2424     //  .align 3,,4
   2425     if (getLexer().isNot(AsmToken::Comma)) {
   2426       HasFillExpr = true;
   2427       if (parseAbsoluteExpression(FillExpr))
   2428         return true;
   2429     }
   2430 
   2431     if (getLexer().isNot(AsmToken::EndOfStatement)) {
   2432       if (getLexer().isNot(AsmToken::Comma))
   2433         return TokError("unexpected token in directive");
   2434       Lex();
   2435 
   2436       MaxBytesLoc = getLexer().getLoc();
   2437       if (parseAbsoluteExpression(MaxBytesToFill))
   2438         return true;
   2439 
   2440       if (getLexer().isNot(AsmToken::EndOfStatement))
   2441         return TokError("unexpected token in directive");
   2442     }
   2443   }
   2444 
   2445   Lex();
   2446 
   2447   if (!HasFillExpr)
   2448     FillExpr = 0;
   2449 
   2450   // Compute alignment in bytes.
   2451   if (IsPow2) {
   2452     // FIXME: Diagnose overflow.
   2453     if (Alignment >= 32) {
   2454       Error(AlignmentLoc, "invalid alignment value");
   2455       Alignment = 31;
   2456     }
   2457 
   2458     Alignment = 1ULL << Alignment;
   2459   } else {
   2460     // Reject alignments that aren't a power of two, for gas compatibility.
   2461     if (!isPowerOf2_64(Alignment))
   2462       Error(AlignmentLoc, "alignment must be a power of 2");
   2463   }
   2464 
   2465   // Diagnose non-sensical max bytes to align.
   2466   if (MaxBytesLoc.isValid()) {
   2467     if (MaxBytesToFill < 1) {
   2468       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
   2469             "many bytes, ignoring maximum bytes expression");
   2470       MaxBytesToFill = 0;
   2471     }
   2472 
   2473     if (MaxBytesToFill >= Alignment) {
   2474       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
   2475               "has no effect");
   2476       MaxBytesToFill = 0;
   2477     }
   2478   }
   2479 
   2480   // Check whether we should use optimal code alignment for this .align
   2481   // directive.
   2482   bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
   2483   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
   2484       ValueSize == 1 && UseCodeAlign) {
   2485     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
   2486   } else {
   2487     // FIXME: Target specific behavior about how the "extra" bytes are filled.
   2488     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
   2489                                        MaxBytesToFill);
   2490   }
   2491 
   2492   return false;
   2493 }
   2494 
   2495 /// ParseDirectiveFile
   2496 /// ::= .file [number] filename
   2497 /// ::= .file number directory filename
   2498 bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
   2499   // FIXME: I'm not sure what this is.
   2500   int64_t FileNumber = -1;
   2501   SMLoc FileNumberLoc = getLexer().getLoc();
   2502   if (getLexer().is(AsmToken::Integer)) {
   2503     FileNumber = getTok().getIntVal();
   2504     Lex();
   2505 
   2506     if (FileNumber < 1)
   2507       return TokError("file number less than one");
   2508   }
   2509 
   2510   if (getLexer().isNot(AsmToken::String))
   2511     return TokError("unexpected token in '.file' directive");
   2512 
   2513   // Usually the directory and filename together, otherwise just the directory.
   2514   StringRef Path = getTok().getString();
   2515   Path = Path.substr(1, Path.size()-2);
   2516   Lex();
   2517 
   2518   StringRef Directory;
   2519   StringRef Filename;
   2520   if (getLexer().is(AsmToken::String)) {
   2521     if (FileNumber == -1)
   2522       return TokError("explicit path specified, but no file number");
   2523     Filename = getTok().getString();
   2524     Filename = Filename.substr(1, Filename.size()-2);
   2525     Directory = Path;
   2526     Lex();
   2527   } else {
   2528     Filename = Path;
   2529   }
   2530 
   2531   if (getLexer().isNot(AsmToken::EndOfStatement))
   2532     return TokError("unexpected token in '.file' directive");
   2533 
   2534   if (FileNumber == -1)
   2535     getStreamer().EmitFileDirective(Filename);
   2536   else {
   2537     if (getContext().getGenDwarfForAssembly() == true)
   2538       Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
   2539                         "used to generate dwarf debug info for assembly code");
   2540 
   2541     if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
   2542       Error(FileNumberLoc, "file number already allocated");
   2543   }
   2544 
   2545   return false;
   2546 }
   2547 
   2548 /// ParseDirectiveLine
   2549 /// ::= .line [number]
   2550 bool AsmParser::ParseDirectiveLine() {
   2551   if (getLexer().isNot(AsmToken::EndOfStatement)) {
   2552     if (getLexer().isNot(AsmToken::Integer))
   2553       return TokError("unexpected token in '.line' directive");
   2554 
   2555     int64_t LineNumber = getTok().getIntVal();
   2556     (void) LineNumber;
   2557     Lex();
   2558 
   2559     // FIXME: Do something with the .line.
   2560   }
   2561 
   2562   if (getLexer().isNot(AsmToken::EndOfStatement))
   2563     return TokError("unexpected token in '.line' directive");
   2564 
   2565   return false;
   2566 }
   2567 
   2568 /// ParseDirectiveLoc
   2569 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
   2570 ///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
   2571 /// The first number is a file number, must have been previously assigned with
   2572 /// a .file directive, the second number is the line number and optionally the
   2573 /// third number is a column position (zero if not specified).  The remaining
   2574 /// optional items are .loc sub-directives.
   2575 bool AsmParser::ParseDirectiveLoc() {
   2576   if (getLexer().isNot(AsmToken::Integer))
   2577     return TokError("unexpected token in '.loc' directive");
   2578   int64_t FileNumber = getTok().getIntVal();
   2579   if (FileNumber < 1)
   2580     return TokError("file number less than one in '.loc' directive");
   2581   if (!getContext().isValidDwarfFileNumber(FileNumber))
   2582     return TokError("unassigned file number in '.loc' directive");
   2583   Lex();
   2584 
   2585   int64_t LineNumber = 0;
   2586   if (getLexer().is(AsmToken::Integer)) {
   2587     LineNumber = getTok().getIntVal();
   2588     if (LineNumber < 1)
   2589       return TokError("line number less than one in '.loc' directive");
   2590     Lex();
   2591   }
   2592 
   2593   int64_t ColumnPos = 0;
   2594   if (getLexer().is(AsmToken::Integer)) {
   2595     ColumnPos = getTok().getIntVal();
   2596     if (ColumnPos < 0)
   2597       return TokError("column position less than zero in '.loc' directive");
   2598     Lex();
   2599   }
   2600 
   2601   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
   2602   unsigned Isa = 0;
   2603   int64_t Discriminator = 0;
   2604   if (getLexer().isNot(AsmToken::EndOfStatement)) {
   2605     for (;;) {
   2606       if (getLexer().is(AsmToken::EndOfStatement))
   2607         break;
   2608 
   2609       StringRef Name;
   2610       SMLoc Loc = getTok().getLoc();
   2611       if (parseIdentifier(Name))
   2612         return TokError("unexpected token in '.loc' directive");
   2613 
   2614       if (Name == "basic_block")
   2615         Flags |= DWARF2_FLAG_BASIC_BLOCK;
   2616       else if (Name == "prologue_end")
   2617         Flags |= DWARF2_FLAG_PROLOGUE_END;
   2618       else if (Name == "epilogue_begin")
   2619         Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
   2620       else if (Name == "is_stmt") {
   2621         Loc = getTok().getLoc();
   2622         const MCExpr *Value;
   2623         if (parseExpression(Value))
   2624           return true;
   2625         // The expression must be the constant 0 or 1.
   2626         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
   2627           int Value = MCE->getValue();
   2628           if (Value == 0)
   2629             Flags &= ~DWARF2_FLAG_IS_STMT;
   2630           else if (Value == 1)
   2631             Flags |= DWARF2_FLAG_IS_STMT;
   2632           else
   2633             return Error(Loc, "is_stmt value not 0 or 1");
   2634         }
   2635         else {
   2636           return Error(Loc, "is_stmt value not the constant value of 0 or 1");
   2637         }
   2638       }
   2639       else if (Name == "isa") {
   2640         Loc = getTok().getLoc();
   2641         const MCExpr *Value;
   2642         if (parseExpression(Value))
   2643           return true;
   2644         // The expression must be a constant greater or equal to 0.
   2645         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
   2646           int Value = MCE->getValue();
   2647           if (Value < 0)
   2648             return Error(Loc, "isa number less than zero");
   2649           Isa = Value;
   2650         }
   2651         else {
   2652           return Error(Loc, "isa number not a constant value");
   2653         }
   2654       }
   2655       else if (Name == "discriminator") {
   2656         if (parseAbsoluteExpression(Discriminator))
   2657           return true;
   2658       }
   2659       else {
   2660         return Error(Loc, "unknown sub-directive in '.loc' directive");
   2661       }
   2662 
   2663       if (getLexer().is(AsmToken::EndOfStatement))
   2664         break;
   2665     }
   2666   }
   2667 
   2668   getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
   2669                                       Isa, Discriminator, StringRef());
   2670 
   2671   return false;
   2672 }
   2673 
   2674 /// ParseDirectiveStabs
   2675 /// ::= .stabs string, number, number, number
   2676 bool AsmParser::ParseDirectiveStabs() {
   2677   return TokError("unsupported directive '.stabs'");
   2678 }
   2679 
   2680 /// ParseDirectiveCFISections
   2681 /// ::= .cfi_sections section [, section]
   2682 bool AsmParser::ParseDirectiveCFISections() {
   2683   StringRef Name;
   2684   bool EH = false;
   2685   bool Debug = false;
   2686 
   2687   if (parseIdentifier(Name))
   2688     return TokError("Expected an identifier");
   2689 
   2690   if (Name == ".eh_frame")
   2691     EH = true;
   2692   else if (Name == ".debug_frame")
   2693     Debug = true;
   2694 
   2695   if (getLexer().is(AsmToken::Comma)) {
   2696     Lex();
   2697 
   2698     if (parseIdentifier(Name))
   2699       return TokError("Expected an identifier");
   2700 
   2701     if (Name == ".eh_frame")
   2702       EH = true;
   2703     else if (Name == ".debug_frame")
   2704       Debug = true;
   2705   }
   2706 
   2707   getStreamer().EmitCFISections(EH, Debug);
   2708   return false;
   2709 }
   2710 
   2711 /// ParseDirectiveCFIStartProc
   2712 /// ::= .cfi_startproc
   2713 bool AsmParser::ParseDirectiveCFIStartProc() {
   2714   getStreamer().EmitCFIStartProc();
   2715   return false;
   2716 }
   2717 
   2718 /// ParseDirectiveCFIEndProc
   2719 /// ::= .cfi_endproc
   2720 bool AsmParser::ParseDirectiveCFIEndProc() {
   2721   getStreamer().EmitCFIEndProc();
   2722   return false;
   2723 }
   2724 
   2725 /// ParseRegisterOrRegisterNumber - parse register name or number.
   2726 bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
   2727                                               SMLoc DirectiveLoc) {
   2728   unsigned RegNo;
   2729 
   2730   if (getLexer().isNot(AsmToken::Integer)) {
   2731     if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
   2732       return true;
   2733     Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
   2734   } else
   2735     return parseAbsoluteExpression(Register);
   2736 
   2737   return false;
   2738 }
   2739 
   2740 /// ParseDirectiveCFIDefCfa
   2741 /// ::= .cfi_def_cfa register,  offset
   2742 bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
   2743   int64_t Register = 0;
   2744   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
   2745     return true;
   2746 
   2747   if (getLexer().isNot(AsmToken::Comma))
   2748     return TokError("unexpected token in directive");
   2749   Lex();
   2750 
   2751   int64_t Offset = 0;
   2752   if (parseAbsoluteExpression(Offset))
   2753     return true;
   2754 
   2755   getStreamer().EmitCFIDefCfa(Register, Offset);
   2756   return false;
   2757 }
   2758 
   2759 /// ParseDirectiveCFIDefCfaOffset
   2760 /// ::= .cfi_def_cfa_offset offset
   2761 bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
   2762   int64_t Offset = 0;
   2763   if (parseAbsoluteExpression(Offset))
   2764     return true;
   2765 
   2766   getStreamer().EmitCFIDefCfaOffset(Offset);
   2767   return false;
   2768 }
   2769 
   2770 /// ParseDirectiveCFIRegister
   2771 /// ::= .cfi_register register, register
   2772 bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
   2773   int64_t Register1 = 0;
   2774   if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
   2775     return true;
   2776 
   2777   if (getLexer().isNot(AsmToken::Comma))
   2778     return TokError("unexpected token in directive");
   2779   Lex();
   2780 
   2781   int64_t Register2 = 0;
   2782   if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
   2783     return true;
   2784 
   2785   getStreamer().EmitCFIRegister(Register1, Register2);
   2786   return false;
   2787 }
   2788 
   2789 /// ParseDirectiveCFIAdjustCfaOffset
   2790 /// ::= .cfi_adjust_cfa_offset adjustment
   2791 bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
   2792   int64_t Adjustment = 0;
   2793   if (parseAbsoluteExpression(Adjustment))
   2794     return true;
   2795 
   2796   getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
   2797   return false;
   2798 }
   2799 
   2800 /// ParseDirectiveCFIDefCfaRegister
   2801 /// ::= .cfi_def_cfa_register register
   2802 bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
   2803   int64_t Register = 0;
   2804   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
   2805     return true;
   2806 
   2807   getStreamer().EmitCFIDefCfaRegister(Register);
   2808   return false;
   2809 }
   2810 
   2811 /// ParseDirectiveCFIOffset
   2812 /// ::= .cfi_offset register, offset
   2813 bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
   2814   int64_t Register = 0;
   2815   int64_t Offset = 0;
   2816 
   2817   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
   2818     return true;
   2819 
   2820   if (getLexer().isNot(AsmToken::Comma))
   2821     return TokError("unexpected token in directive");
   2822   Lex();
   2823 
   2824   if (parseAbsoluteExpression(Offset))
   2825     return true;
   2826 
   2827   getStreamer().EmitCFIOffset(Register, Offset);
   2828   return false;
   2829 }
   2830 
   2831 /// ParseDirectiveCFIRelOffset
   2832 /// ::= .cfi_rel_offset register, offset
   2833 bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
   2834   int64_t Register = 0;
   2835 
   2836   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
   2837     return true;
   2838 
   2839   if (getLexer().isNot(AsmToken::Comma))
   2840     return TokError("unexpected token in directive");
   2841   Lex();
   2842 
   2843   int64_t Offset = 0;
   2844   if (parseAbsoluteExpression(Offset))
   2845     return true;
   2846 
   2847   getStreamer().EmitCFIRelOffset(Register, Offset);
   2848   return false;
   2849 }
   2850 
   2851 static bool isValidEncoding(int64_t Encoding) {
   2852   if (Encoding & ~0xff)
   2853     return false;
   2854 
   2855   if (Encoding == dwarf::DW_EH_PE_omit)
   2856     return true;
   2857 
   2858   const unsigned Format = Encoding & 0xf;
   2859   if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
   2860       Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
   2861       Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
   2862       Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
   2863     return false;
   2864 
   2865   const unsigned Application = Encoding & 0x70;
   2866   if (Application != dwarf::DW_EH_PE_absptr &&
   2867       Application != dwarf::DW_EH_PE_pcrel)
   2868     return false;
   2869 
   2870   return true;
   2871 }
   2872 
   2873 /// ParseDirectiveCFIPersonalityOrLsda
   2874 /// IsPersonality true for cfi_personality, false for cfi_lsda
   2875 /// ::= .cfi_personality encoding, [symbol_name]
   2876 /// ::= .cfi_lsda encoding, [symbol_name]
   2877 bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
   2878   int64_t Encoding = 0;
   2879   if (parseAbsoluteExpression(Encoding))
   2880     return true;
   2881   if (Encoding == dwarf::DW_EH_PE_omit)
   2882     return false;
   2883 
   2884   if (!isValidEncoding(Encoding))
   2885     return TokError("unsupported encoding.");
   2886 
   2887   if (getLexer().isNot(AsmToken::Comma))
   2888     return TokError("unexpected token in directive");
   2889   Lex();
   2890 
   2891   StringRef Name;
   2892   if (parseIdentifier(Name))
   2893     return TokError("expected identifier in directive");
   2894 
   2895   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
   2896 
   2897   if (IsPersonality)
   2898     getStreamer().EmitCFIPersonality(Sym, Encoding);
   2899   else
   2900     getStreamer().EmitCFILsda(Sym, Encoding);
   2901   return false;
   2902 }
   2903 
   2904 /// ParseDirectiveCFIRememberState
   2905 /// ::= .cfi_remember_state
   2906 bool AsmParser::ParseDirectiveCFIRememberState() {
   2907   getStreamer().EmitCFIRememberState();
   2908   return false;
   2909 }
   2910 
   2911 /// ParseDirectiveCFIRestoreState
   2912 /// ::= .cfi_remember_state
   2913 bool AsmParser::ParseDirectiveCFIRestoreState() {
   2914   getStreamer().EmitCFIRestoreState();
   2915   return false;
   2916 }
   2917 
   2918 /// ParseDirectiveCFISameValue
   2919 /// ::= .cfi_same_value register
   2920 bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
   2921   int64_t Register = 0;
   2922 
   2923   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
   2924     return true;
   2925 
   2926   getStreamer().EmitCFISameValue(Register);
   2927   return false;
   2928 }
   2929 
   2930 /// ParseDirectiveCFIRestore
   2931 /// ::= .cfi_restore register
   2932 bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
   2933   int64_t Register = 0;
   2934   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
   2935     return true;
   2936 
   2937   getStreamer().EmitCFIRestore(Register);
   2938   return false;
   2939 }
   2940 
   2941 /// ParseDirectiveCFIEscape
   2942 /// ::= .cfi_escape expression[,...]
   2943 bool AsmParser::ParseDirectiveCFIEscape() {
   2944   std::string Values;
   2945   int64_t CurrValue;
   2946   if (parseAbsoluteExpression(CurrValue))
   2947     return true;
   2948 
   2949   Values.push_back((uint8_t)CurrValue);
   2950 
   2951   while (getLexer().is(AsmToken::Comma)) {
   2952     Lex();
   2953 
   2954     if (parseAbsoluteExpression(CurrValue))
   2955       return true;
   2956 
   2957     Values.push_back((uint8_t)CurrValue);
   2958   }
   2959 
   2960   getStreamer().EmitCFIEscape(Values);
   2961   return false;
   2962 }
   2963 
   2964 /// ParseDirectiveCFISignalFrame
   2965 /// ::= .cfi_signal_frame
   2966 bool AsmParser::ParseDirectiveCFISignalFrame() {
   2967   if (getLexer().isNot(AsmToken::EndOfStatement))
   2968     return Error(getLexer().getLoc(),
   2969                  "unexpected token in '.cfi_signal_frame'");
   2970 
   2971   getStreamer().EmitCFISignalFrame();
   2972   return false;
   2973 }
   2974 
   2975 /// ParseDirectiveCFIUndefined
   2976 /// ::= .cfi_undefined register
   2977 bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
   2978   int64_t Register = 0;
   2979 
   2980   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
   2981     return true;
   2982 
   2983   getStreamer().EmitCFIUndefined(Register);
   2984   return false;
   2985 }
   2986 
   2987 /// ParseDirectiveMacrosOnOff
   2988 /// ::= .macros_on
   2989 /// ::= .macros_off
   2990 bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
   2991   if (getLexer().isNot(AsmToken::EndOfStatement))
   2992     return Error(getLexer().getLoc(),
   2993                  "unexpected token in '" + Directive + "' directive");
   2994 
   2995   SetMacrosEnabled(Directive == ".macros_on");
   2996   return false;
   2997 }
   2998 
   2999 /// ParseDirectiveMacro
   3000 /// ::= .macro name [parameters]
   3001 bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
   3002   StringRef Name;
   3003   if (parseIdentifier(Name))
   3004     return TokError("expected identifier in '.macro' directive");
   3005 
   3006   MCAsmMacroParameters Parameters;
   3007   // Argument delimiter is initially unknown. It will be set by
   3008   // ParseMacroArgument()
   3009   AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
   3010   if (getLexer().isNot(AsmToken::EndOfStatement)) {
   3011     for (;;) {
   3012       MCAsmMacroParameter Parameter;
   3013       if (parseIdentifier(Parameter.first))
   3014         return TokError("expected identifier in '.macro' directive");
   3015 
   3016       if (getLexer().is(AsmToken::Equal)) {
   3017         Lex();
   3018         if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
   3019           return true;
   3020       }
   3021 
   3022       Parameters.push_back(Parameter);
   3023 
   3024       if (getLexer().is(AsmToken::Comma))
   3025         Lex();
   3026       else if (getLexer().is(AsmToken::EndOfStatement))
   3027         break;
   3028     }
   3029   }
   3030 
   3031   // Eat the end of statement.
   3032   Lex();
   3033 
   3034   AsmToken EndToken, StartToken = getTok();
   3035 
   3036   // Lex the macro definition.
   3037   for (;;) {
   3038     // Check whether we have reached the end of the file.
   3039     if (getLexer().is(AsmToken::Eof))
   3040       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
   3041 
   3042     // Otherwise, check whether we have reach the .endmacro.
   3043     if (getLexer().is(AsmToken::Identifier) &&
   3044         (getTok().getIdentifier() == ".endm" ||
   3045          getTok().getIdentifier() == ".endmacro")) {
   3046       EndToken = getTok();
   3047       Lex();
   3048       if (getLexer().isNot(AsmToken::EndOfStatement))
   3049         return TokError("unexpected token in '" + EndToken.getIdentifier() +
   3050                         "' directive");
   3051       break;
   3052     }
   3053 
   3054     // Otherwise, scan til the end of the statement.
   3055     eatToEndOfStatement();
   3056   }
   3057 
   3058   if (LookupMacro(Name)) {
   3059     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
   3060   }
   3061 
   3062   const char *BodyStart = StartToken.getLoc().getPointer();
   3063   const char *BodyEnd = EndToken.getLoc().getPointer();
   3064   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
   3065   CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
   3066   DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
   3067   return false;
   3068 }
   3069 
   3070 /// CheckForBadMacro
   3071 ///
   3072 /// With the support added for named parameters there may be code out there that
   3073 /// is transitioning from positional parameters.  In versions of gas that did
   3074 /// not support named parameters they would be ignored on the macro defintion.
   3075 /// But to support both styles of parameters this is not possible so if a macro
   3076 /// defintion has named parameters but does not use them and has what appears
   3077 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
   3078 /// warning that the positional parameter found in body which have no effect.
   3079 /// Hoping the developer will either remove the named parameters from the macro
   3080 /// definiton so the positional parameters get used if that was what was
   3081 /// intended or change the macro to use the named parameters.  It is possible
   3082 /// this warning will trigger when the none of the named parameters are used
   3083 /// and the strings like $1 are infact to simply to be passed trough unchanged.
   3084 void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
   3085                                  StringRef Body,
   3086                                  MCAsmMacroParameters Parameters) {
   3087   // If this macro is not defined with named parameters the warning we are
   3088   // checking for here doesn't apply.
   3089   unsigned NParameters = Parameters.size();
   3090   if (NParameters == 0)
   3091     return;
   3092 
   3093   bool NamedParametersFound = false;
   3094   bool PositionalParametersFound = false;
   3095 
   3096   // Look at the body of the macro for use of both the named parameters and what
   3097   // are likely to be positional parameters.  This is what expandMacro() is
   3098   // doing when it finds the parameters in the body.
   3099   while (!Body.empty()) {
   3100     // Scan for the next possible parameter.
   3101     std::size_t End = Body.size(), Pos = 0;
   3102     for (; Pos != End; ++Pos) {
   3103       // Check for a substitution or escape.
   3104       // This macro is defined with parameters, look for \foo, \bar, etc.
   3105       if (Body[Pos] == '\\' && Pos + 1 != End)
   3106         break;
   3107 
   3108       // This macro should have parameters, but look for $0, $1, ..., $n too.
   3109       if (Body[Pos] != '$' || Pos + 1 == End)
   3110         continue;
   3111       char Next = Body[Pos + 1];
   3112       if (Next == '$' || Next == 'n' ||
   3113           isdigit(static_cast<unsigned char>(Next)))
   3114         break;
   3115     }
   3116 
   3117     // Check if we reached the end.
   3118     if (Pos == End)
   3119       break;
   3120 
   3121     if (Body[Pos] == '$') {
   3122       switch (Body[Pos+1]) {
   3123         // $$ => $
   3124       case '$':
   3125         break;
   3126 
   3127         // $n => number of arguments
   3128       case 'n':
   3129         PositionalParametersFound = true;
   3130         break;
   3131 
   3132         // $[0-9] => argument
   3133       default: {
   3134         PositionalParametersFound = true;
   3135         break;
   3136         }
   3137       }
   3138       Pos += 2;
   3139     } else {
   3140       unsigned I = Pos + 1;
   3141       while (isIdentifierChar(Body[I]) && I + 1 != End)
   3142         ++I;
   3143 
   3144       const char *Begin = Body.data() + Pos +1;
   3145       StringRef Argument(Begin, I - (Pos +1));
   3146       unsigned Index = 0;
   3147       for (; Index < NParameters; ++Index)
   3148         if (Parameters[Index].first == Argument)
   3149           break;
   3150 
   3151       if (Index == NParameters) {
   3152           if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
   3153             Pos += 3;
   3154           else {
   3155             Pos = I;
   3156           }
   3157       } else {
   3158         NamedParametersFound = true;
   3159         Pos += 1 + Argument.size();
   3160       }
   3161     }
   3162     // Update the scan point.
   3163     Body = Body.substr(Pos);
   3164   }
   3165 
   3166   if (!NamedParametersFound && PositionalParametersFound)
   3167     Warning(DirectiveLoc, "macro defined with named parameters which are not "
   3168                           "used in macro body, possible positional parameter "
   3169                           "found in body which will have no effect");
   3170 }
   3171 
   3172 /// ParseDirectiveEndMacro
   3173 /// ::= .endm
   3174 /// ::= .endmacro
   3175 bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
   3176   if (getLexer().isNot(AsmToken::EndOfStatement))
   3177     return TokError("unexpected token in '" + Directive + "' directive");
   3178 
   3179   // If we are inside a macro instantiation, terminate the current
   3180   // instantiation.
   3181   if (InsideMacroInstantiation()) {
   3182     HandleMacroExit();
   3183     return false;
   3184   }
   3185 
   3186   // Otherwise, this .endmacro is a stray entry in the file; well formed
   3187   // .endmacro directives are handled during the macro definition parsing.
   3188   return TokError("unexpected '" + Directive + "' in file, "
   3189                   "no current macro definition");
   3190 }
   3191 
   3192 /// ParseDirectivePurgeMacro
   3193 /// ::= .purgem
   3194 bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
   3195   StringRef Name;
   3196   if (parseIdentifier(Name))
   3197     return TokError("expected identifier in '.purgem' directive");
   3198 
   3199   if (getLexer().isNot(AsmToken::EndOfStatement))
   3200     return TokError("unexpected token in '.purgem' directive");
   3201 
   3202   if (!LookupMacro(Name))
   3203     return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
   3204 
   3205   UndefineMacro(Name);
   3206   return false;
   3207 }
   3208 
   3209 /// ParseDirectiveBundleAlignMode
   3210 /// ::= {.bundle_align_mode} expression
   3211 bool AsmParser::ParseDirectiveBundleAlignMode() {
   3212   checkForValidSection();
   3213 
   3214   // Expect a single argument: an expression that evaluates to a constant
   3215   // in the inclusive range 0-30.
   3216   SMLoc ExprLoc = getLexer().getLoc();
   3217   int64_t AlignSizePow2;
   3218   if (parseAbsoluteExpression(AlignSizePow2))
   3219     return true;
   3220   else if (getLexer().isNot(AsmToken::EndOfStatement))
   3221     return TokError("unexpected token after expression in"
   3222                     " '.bundle_align_mode' directive");
   3223   else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
   3224     return Error(ExprLoc,
   3225                  "invalid bundle alignment size (expected between 0 and 30)");
   3226 
   3227   Lex();
   3228 
   3229   // Because of AlignSizePow2's verified range we can safely truncate it to
   3230   // unsigned.
   3231   getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
   3232   return false;
   3233 }
   3234 
   3235 /// ParseDirectiveBundleLock
   3236 /// ::= {.bundle_lock} [align_to_end]
   3237 bool AsmParser::ParseDirectiveBundleLock() {
   3238   checkForValidSection();
   3239   bool AlignToEnd = false;
   3240 
   3241   if (getLexer().isNot(AsmToken::EndOfStatement)) {
   3242     StringRef Option;
   3243     SMLoc Loc = getTok().getLoc();
   3244     const char *kInvalidOptionError =
   3245       "invalid option for '.bundle_lock' directive";
   3246 
   3247     if (parseIdentifier(Option))
   3248       return Error(Loc, kInvalidOptionError);
   3249 
   3250     if (Option != "align_to_end")
   3251       return Error(Loc, kInvalidOptionError);
   3252     else if (getLexer().isNot(AsmToken::EndOfStatement))
   3253       return Error(Loc,
   3254                    "unexpected token after '.bundle_lock' directive option");
   3255     AlignToEnd = true;
   3256   }
   3257 
   3258   Lex();
   3259 
   3260   getStreamer().EmitBundleLock(AlignToEnd);
   3261   return false;
   3262 }
   3263 
   3264 /// ParseDirectiveBundleLock
   3265 /// ::= {.bundle_lock}
   3266 bool AsmParser::ParseDirectiveBundleUnlock() {
   3267   checkForValidSection();
   3268 
   3269   if (getLexer().isNot(AsmToken::EndOfStatement))
   3270     return TokError("unexpected token in '.bundle_unlock' directive");
   3271   Lex();
   3272 
   3273   getStreamer().EmitBundleUnlock();
   3274   return false;
   3275 }
   3276 
   3277 /// ParseDirectiveSpace
   3278 /// ::= (.skip | .space) expression [ , expression ]
   3279 bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
   3280   checkForValidSection();
   3281 
   3282   int64_t NumBytes;
   3283   if (parseAbsoluteExpression(NumBytes))
   3284     return true;
   3285 
   3286   int64_t FillExpr = 0;
   3287   if (getLexer().isNot(AsmToken::EndOfStatement)) {
   3288     if (getLexer().isNot(AsmToken::Comma))
   3289       return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
   3290     Lex();
   3291 
   3292     if (parseAbsoluteExpression(FillExpr))
   3293       return true;
   3294 
   3295     if (getLexer().isNot(AsmToken::EndOfStatement))
   3296       return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
   3297   }
   3298 
   3299   Lex();
   3300 
   3301   if (NumBytes <= 0)
   3302     return TokError("invalid number of bytes in '" +
   3303                     Twine(IDVal) + "' directive");
   3304 
   3305   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
   3306   getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
   3307 
   3308   return false;
   3309 }
   3310 
   3311 /// ParseDirectiveLEB128
   3312 /// ::= (.sleb128 | .uleb128) expression
   3313 bool AsmParser::ParseDirectiveLEB128(bool Signed) {
   3314   checkForValidSection();
   3315   const MCExpr *Value;
   3316 
   3317   if (parseExpression(Value))
   3318     return true;
   3319 
   3320   if (getLexer().isNot(AsmToken::EndOfStatement))
   3321     return TokError("unexpected token in directive");
   3322 
   3323   if (Signed)
   3324     getStreamer().EmitSLEB128Value(Value);
   3325   else
   3326     getStreamer().EmitULEB128Value(Value);
   3327 
   3328   return false;
   3329 }
   3330 
   3331 /// ParseDirectiveSymbolAttribute
   3332 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
   3333 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
   3334   if (getLexer().isNot(AsmToken::EndOfStatement)) {
   3335     for (;;) {
   3336       StringRef Name;
   3337       SMLoc Loc = getTok().getLoc();
   3338 
   3339       if (parseIdentifier(Name))
   3340         return Error(Loc, "expected identifier in directive");
   3341 
   3342       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
   3343 
   3344       // Assembler local symbols don't make any sense here. Complain loudly.
   3345       if (Sym->isTemporary())
   3346         return Error(Loc, "non-local symbol required in directive");
   3347 
   3348       getStreamer().EmitSymbolAttribute(Sym, Attr);
   3349 
   3350       if (getLexer().is(AsmToken::EndOfStatement))
   3351         break;
   3352 
   3353       if (getLexer().isNot(AsmToken::Comma))
   3354         return TokError("unexpected token in directive");
   3355       Lex();
   3356     }
   3357   }
   3358 
   3359   Lex();
   3360   return false;
   3361 }
   3362 
   3363 /// ParseDirectiveComm
   3364 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
   3365 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
   3366   checkForValidSection();
   3367 
   3368   SMLoc IDLoc = getLexer().getLoc();
   3369   StringRef Name;
   3370   if (parseIdentifier(Name))
   3371     return TokError("expected identifier in directive");
   3372 
   3373   // Handle the identifier as the key symbol.
   3374   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
   3375 
   3376   if (getLexer().isNot(AsmToken::Comma))
   3377     return TokError("unexpected token in directive");
   3378   Lex();
   3379 
   3380   int64_t Size;
   3381   SMLoc SizeLoc = getLexer().getLoc();
   3382   if (parseAbsoluteExpression(Size))
   3383     return true;
   3384 
   3385   int64_t Pow2Alignment = 0;
   3386   SMLoc Pow2AlignmentLoc;
   3387   if (getLexer().is(AsmToken::Comma)) {
   3388     Lex();
   3389     Pow2AlignmentLoc = getLexer().getLoc();
   3390     if (parseAbsoluteExpression(Pow2Alignment))
   3391       return true;
   3392 
   3393     LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
   3394     if (IsLocal && LCOMM == LCOMM::NoAlignment)
   3395       return Error(Pow2AlignmentLoc, "alignment not supported on this target");
   3396 
   3397     // If this target takes alignments in bytes (not log) validate and convert.
   3398     if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
   3399         (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
   3400       if (!isPowerOf2_64(Pow2Alignment))
   3401         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
   3402       Pow2Alignment = Log2_64(Pow2Alignment);
   3403     }
   3404   }
   3405 
   3406   if (getLexer().isNot(AsmToken::EndOfStatement))
   3407     return TokError("unexpected token in '.comm' or '.lcomm' directive");
   3408 
   3409   Lex();
   3410 
   3411   // NOTE: a size of zero for a .comm should create a undefined symbol
   3412   // but a size of .lcomm creates a bss symbol of size zero.
   3413   if (Size < 0)
   3414     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
   3415                  "be less than zero");
   3416 
   3417   // NOTE: The alignment in the directive is a power of 2 value, the assembler
   3418   // may internally end up wanting an alignment in bytes.
   3419   // FIXME: Diagnose overflow.
   3420   if (Pow2Alignment < 0)
   3421     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
   3422                  "alignment, can't be less than zero");
   3423 
   3424   if (!Sym->isUndefined())
   3425     return Error(IDLoc, "invalid symbol redefinition");
   3426 
   3427   // Create the Symbol as a common or local common with Size and Pow2Alignment
   3428   if (IsLocal) {
   3429     getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
   3430     return false;
   3431   }
   3432 
   3433   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
   3434   return false;
   3435 }
   3436 
   3437 /// ParseDirectiveAbort
   3438 ///  ::= .abort [... message ...]
   3439 bool AsmParser::ParseDirectiveAbort() {
   3440   // FIXME: Use loc from directive.
   3441   SMLoc Loc = getLexer().getLoc();
   3442 
   3443   StringRef Str = parseStringToEndOfStatement();
   3444   if (getLexer().isNot(AsmToken::EndOfStatement))
   3445     return TokError("unexpected token in '.abort' directive");
   3446 
   3447   Lex();
   3448 
   3449   if (Str.empty())
   3450     Error(Loc, ".abort detected. Assembly stopping.");
   3451   else
   3452     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
   3453   // FIXME: Actually abort assembly here.
   3454 
   3455   return false;
   3456 }
   3457 
   3458 /// ParseDirectiveInclude
   3459 ///  ::= .include "filename"
   3460 bool AsmParser::ParseDirectiveInclude() {
   3461   if (getLexer().isNot(AsmToken::String))
   3462     return TokError("expected string in '.include' directive");
   3463 
   3464   std::string Filename = getTok().getString();
   3465   SMLoc IncludeLoc = getLexer().getLoc();
   3466   Lex();
   3467 
   3468   if (getLexer().isNot(AsmToken::EndOfStatement))
   3469     return TokError("unexpected token in '.include' directive");
   3470 
   3471   // Strip the quotes.
   3472   Filename = Filename.substr(1, Filename.size()-2);
   3473 
   3474   // Attempt to switch the lexer to the included file before consuming the end
   3475   // of statement to avoid losing it when we switch.
   3476   if (EnterIncludeFile(Filename)) {
   3477     Error(IncludeLoc, "Could not find include file '" + Filename + "'");
   3478     return true;
   3479   }
   3480 
   3481   return false;
   3482 }
   3483 
   3484 /// ParseDirectiveIncbin
   3485 ///  ::= .incbin "filename"
   3486 bool AsmParser::ParseDirectiveIncbin() {
   3487   if (getLexer().isNot(AsmToken::String))
   3488     return TokError("expected string in '.incbin' directive");
   3489 
   3490   std::string Filename = getTok().getString();
   3491   SMLoc IncbinLoc = getLexer().getLoc();
   3492   Lex();
   3493 
   3494   if (getLexer().isNot(AsmToken::EndOfStatement))
   3495     return TokError("unexpected token in '.incbin' directive");
   3496 
   3497   // Strip the quotes.
   3498   Filename = Filename.substr(1, Filename.size()-2);
   3499 
   3500   // Attempt to process the included file.
   3501   if (ProcessIncbinFile(Filename)) {
   3502     Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
   3503     return true;
   3504   }
   3505 
   3506   return false;
   3507 }
   3508 
   3509 /// ParseDirectiveIf
   3510 /// ::= .if expression
   3511 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
   3512   TheCondStack.push_back(TheCondState);
   3513   TheCondState.TheCond = AsmCond::IfCond;
   3514   if (TheCondState.Ignore) {
   3515     eatToEndOfStatement();
   3516   } else {
   3517     int64_t ExprValue;
   3518     if (parseAbsoluteExpression(ExprValue))
   3519       return true;
   3520 
   3521     if (getLexer().isNot(AsmToken::EndOfStatement))
   3522       return TokError("unexpected token in '.if' directive");
   3523 
   3524     Lex();
   3525 
   3526     TheCondState.CondMet = ExprValue;
   3527     TheCondState.Ignore = !TheCondState.CondMet;
   3528   }
   3529 
   3530   return false;
   3531 }
   3532 
   3533 /// ParseDirectiveIfb
   3534 /// ::= .ifb string
   3535 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
   3536   TheCondStack.push_back(TheCondState);
   3537   TheCondState.TheCond = AsmCond::IfCond;
   3538 
   3539   if (TheCondState.Ignore) {
   3540     eatToEndOfStatement();
   3541   } else {
   3542     StringRef Str = parseStringToEndOfStatement();
   3543 
   3544     if (getLexer().isNot(AsmToken::EndOfStatement))
   3545       return TokError("unexpected token in '.ifb' directive");
   3546 
   3547     Lex();
   3548 
   3549     TheCondState.CondMet = ExpectBlank == Str.empty();
   3550     TheCondState.Ignore = !TheCondState.CondMet;
   3551   }
   3552 
   3553   return false;
   3554 }
   3555 
   3556 /// ParseDirectiveIfc
   3557 /// ::= .ifc string1, string2
   3558 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
   3559   TheCondStack.push_back(TheCondState);
   3560   TheCondState.TheCond = AsmCond::IfCond;
   3561 
   3562   if (TheCondState.Ignore) {
   3563     eatToEndOfStatement();
   3564   } else {
   3565     StringRef Str1 = ParseStringToComma();
   3566 
   3567     if (getLexer().isNot(AsmToken::Comma))
   3568       return TokError("unexpected token in '.ifc' directive");
   3569 
   3570     Lex();
   3571 
   3572     StringRef Str2 = parseStringToEndOfStatement();
   3573 
   3574     if (getLexer().isNot(AsmToken::EndOfStatement))
   3575       return TokError("unexpected token in '.ifc' directive");
   3576 
   3577     Lex();
   3578 
   3579     TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
   3580     TheCondState.Ignore = !TheCondState.CondMet;
   3581   }
   3582 
   3583   return false;
   3584 }
   3585 
   3586 /// ParseDirectiveIfdef
   3587 /// ::= .ifdef symbol
   3588 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
   3589   StringRef Name;
   3590   TheCondStack.push_back(TheCondState);
   3591   TheCondState.TheCond = AsmCond::IfCond;
   3592 
   3593   if (TheCondState.Ignore) {
   3594     eatToEndOfStatement();
   3595   } else {
   3596     if (parseIdentifier(Name))
   3597       return TokError("expected identifier after '.ifdef'");
   3598 
   3599     Lex();
   3600 
   3601     MCSymbol *Sym = getContext().LookupSymbol(Name);
   3602 
   3603     if (expect_defined)
   3604       TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
   3605     else
   3606       TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
   3607     TheCondState.Ignore = !TheCondState.CondMet;
   3608   }
   3609 
   3610   return false;
   3611 }
   3612 
   3613 /// ParseDirectiveElseIf
   3614 /// ::= .elseif expression
   3615 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
   3616   if (TheCondState.TheCond != AsmCond::IfCond &&
   3617       TheCondState.TheCond != AsmCond::ElseIfCond)
   3618       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
   3619                           " an .elseif");
   3620   TheCondState.TheCond = AsmCond::ElseIfCond;
   3621 
   3622   bool LastIgnoreState = false;
   3623   if (!TheCondStack.empty())
   3624       LastIgnoreState = TheCondStack.back().Ignore;
   3625   if (LastIgnoreState || TheCondState.CondMet) {
   3626     TheCondState.Ignore = true;
   3627     eatToEndOfStatement();
   3628   }
   3629   else {
   3630     int64_t ExprValue;
   3631     if (parseAbsoluteExpression(ExprValue))
   3632       return true;
   3633 
   3634     if (getLexer().isNot(AsmToken::EndOfStatement))
   3635       return TokError("unexpected token in '.elseif' directive");
   3636 
   3637     Lex();
   3638     TheCondState.CondMet = ExprValue;
   3639     TheCondState.Ignore = !TheCondState.CondMet;
   3640   }
   3641 
   3642   return false;
   3643 }
   3644 
   3645 /// ParseDirectiveElse
   3646 /// ::= .else
   3647 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
   3648   if (getLexer().isNot(AsmToken::EndOfStatement))
   3649     return TokError("unexpected token in '.else' directive");
   3650 
   3651   Lex();
   3652 
   3653   if (TheCondState.TheCond != AsmCond::IfCond &&
   3654       TheCondState.TheCond != AsmCond::ElseIfCond)
   3655       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
   3656                           ".elseif");
   3657   TheCondState.TheCond = AsmCond::ElseCond;
   3658   bool LastIgnoreState = false;
   3659   if (!TheCondStack.empty())
   3660     LastIgnoreState = TheCondStack.back().Ignore;
   3661   if (LastIgnoreState || TheCondState.CondMet)
   3662     TheCondState.Ignore = true;
   3663   else
   3664     TheCondState.Ignore = false;
   3665 
   3666   return false;
   3667 }
   3668 
   3669 /// ParseDirectiveEndIf
   3670 /// ::= .endif
   3671 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
   3672   if (getLexer().isNot(AsmToken::EndOfStatement))
   3673     return TokError("unexpected token in '.endif' directive");
   3674 
   3675   Lex();
   3676 
   3677   if ((TheCondState.TheCond == AsmCond::NoCond) ||
   3678       TheCondStack.empty())
   3679     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
   3680                         ".else");
   3681   if (!TheCondStack.empty()) {
   3682     TheCondState = TheCondStack.back();
   3683     TheCondStack.pop_back();
   3684   }
   3685 
   3686   return false;
   3687 }
   3688 
   3689 void AsmParser::initializeDirectiveKindMap() {
   3690   DirectiveKindMap[".set"] = DK_SET;
   3691   DirectiveKindMap[".equ"] = DK_EQU;
   3692   DirectiveKindMap[".equiv"] = DK_EQUIV;
   3693   DirectiveKindMap[".ascii"] = DK_ASCII;
   3694   DirectiveKindMap[".asciz"] = DK_ASCIZ;
   3695   DirectiveKindMap[".string"] = DK_STRING;
   3696   DirectiveKindMap[".byte"] = DK_BYTE;
   3697   DirectiveKindMap[".short"] = DK_SHORT;
   3698   DirectiveKindMap[".value"] = DK_VALUE;
   3699   DirectiveKindMap[".2byte"] = DK_2BYTE;
   3700   DirectiveKindMap[".long"] = DK_LONG;
   3701   DirectiveKindMap[".int"] = DK_INT;
   3702   DirectiveKindMap[".4byte"] = DK_4BYTE;
   3703   DirectiveKindMap[".quad"] = DK_QUAD;
   3704   DirectiveKindMap[".8byte"] = DK_8BYTE;
   3705   DirectiveKindMap[".single"] = DK_SINGLE;
   3706   DirectiveKindMap[".float"] = DK_FLOAT;
   3707   DirectiveKindMap[".double"] = DK_DOUBLE;
   3708   DirectiveKindMap[".align"] = DK_ALIGN;
   3709   DirectiveKindMap[".align32"] = DK_ALIGN32;
   3710   DirectiveKindMap[".balign"] = DK_BALIGN;
   3711   DirectiveKindMap[".balignw"] = DK_BALIGNW;
   3712   DirectiveKindMap[".balignl"] = DK_BALIGNL;
   3713   DirectiveKindMap[".p2align"] = DK_P2ALIGN;
   3714   DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
   3715   DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
   3716   DirectiveKindMap[".org"] = DK_ORG;
   3717   DirectiveKindMap[".fill"] = DK_FILL;
   3718   DirectiveKindMap[".zero"] = DK_ZERO;
   3719   DirectiveKindMap[".extern"] = DK_EXTERN;
   3720   DirectiveKindMap[".globl"] = DK_GLOBL;
   3721   DirectiveKindMap[".global"] = DK_GLOBAL;
   3722   DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
   3723   DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
   3724   DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
   3725   DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
   3726   DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
   3727   DirectiveKindMap[".reference"] = DK_REFERENCE;
   3728   DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
   3729   DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
   3730   DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
   3731   DirectiveKindMap[".comm"] = DK_COMM;
   3732   DirectiveKindMap[".common"] = DK_COMMON;
   3733   DirectiveKindMap[".lcomm"] = DK_LCOMM;
   3734   DirectiveKindMap[".abort"] = DK_ABORT;
   3735   DirectiveKindMap[".include"] = DK_INCLUDE;
   3736   DirectiveKindMap[".incbin"] = DK_INCBIN;
   3737   DirectiveKindMap[".code16"] = DK_CODE16;
   3738   DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
   3739   DirectiveKindMap[".rept"] = DK_REPT;
   3740   DirectiveKindMap[".irp"] = DK_IRP;
   3741   DirectiveKindMap[".irpc"] = DK_IRPC;
   3742   DirectiveKindMap[".endr"] = DK_ENDR;
   3743   DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
   3744   DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
   3745   DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
   3746   DirectiveKindMap[".if"] = DK_IF;
   3747   DirectiveKindMap[".ifb"] = DK_IFB;
   3748   DirectiveKindMap[".ifnb"] = DK_IFNB;
   3749   DirectiveKindMap[".ifc"] = DK_IFC;
   3750   DirectiveKindMap[".ifnc"] = DK_IFNC;
   3751   DirectiveKindMap[".ifdef"] = DK_IFDEF;
   3752   DirectiveKindMap[".ifndef"] = DK_IFNDEF;
   3753   DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
   3754   DirectiveKindMap[".elseif"] = DK_ELSEIF;
   3755   DirectiveKindMap[".else"] = DK_ELSE;
   3756   DirectiveKindMap[".endif"] = DK_ENDIF;
   3757   DirectiveKindMap[".skip"] = DK_SKIP;
   3758   DirectiveKindMap[".space"] = DK_SPACE;
   3759   DirectiveKindMap[".file"] = DK_FILE;
   3760   DirectiveKindMap[".line"] = DK_LINE;
   3761   DirectiveKindMap[".loc"] = DK_LOC;
   3762   DirectiveKindMap[".stabs"] = DK_STABS;
   3763   DirectiveKindMap[".sleb128"] = DK_SLEB128;
   3764   DirectiveKindMap[".uleb128"] = DK_ULEB128;
   3765   DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
   3766   DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
   3767   DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
   3768   DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
   3769   DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
   3770   DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
   3771   DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
   3772   DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
   3773   DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
   3774   DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
   3775   DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
   3776   DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
   3777   DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
   3778   DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
   3779   DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
   3780   DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
   3781   DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
   3782   DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
   3783   DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
   3784   DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
   3785   DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
   3786   DirectiveKindMap[".macro"] = DK_MACRO;
   3787   DirectiveKindMap[".endm"] = DK_ENDM;
   3788   DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
   3789   DirectiveKindMap[".purgem"] = DK_PURGEM;
   3790 }
   3791 
   3792 
   3793 MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
   3794   AsmToken EndToken, StartToken = getTok();
   3795 
   3796   unsigned NestLevel = 0;
   3797   for (;;) {
   3798     // Check whether we have reached the end of the file.
   3799     if (getLexer().is(AsmToken::Eof)) {
   3800       Error(DirectiveLoc, "no matching '.endr' in definition");
   3801       return 0;
   3802     }
   3803 
   3804     if (Lexer.is(AsmToken::Identifier) &&
   3805         (getTok().getIdentifier() == ".rept")) {
   3806       ++NestLevel;
   3807     }
   3808 
   3809     // Otherwise, check whether we have reached the .endr.
   3810     if (Lexer.is(AsmToken::Identifier) &&
   3811         getTok().getIdentifier() == ".endr") {
   3812       if (NestLevel == 0) {
   3813         EndToken = getTok();
   3814         Lex();
   3815         if (Lexer.isNot(AsmToken::EndOfStatement)) {
   3816           TokError("unexpected token in '.endr' directive");
   3817           return 0;
   3818         }
   3819         break;
   3820       }
   3821       --NestLevel;
   3822     }
   3823 
   3824     // Otherwise, scan till the end of the statement.
   3825     eatToEndOfStatement();
   3826   }
   3827 
   3828   const char *BodyStart = StartToken.getLoc().getPointer();
   3829   const char *BodyEnd = EndToken.getLoc().getPointer();
   3830   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
   3831 
   3832   // We Are Anonymous.
   3833   StringRef Name;
   3834   MCAsmMacroParameters Parameters;
   3835   return new MCAsmMacro(Name, Body, Parameters);
   3836 }
   3837 
   3838 void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
   3839                                          raw_svector_ostream &OS) {
   3840   OS << ".endr\n";
   3841 
   3842   MemoryBuffer *Instantiation =
   3843     MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
   3844 
   3845   // Create the macro instantiation object and add to the current macro
   3846   // instantiation stack.
   3847   MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
   3848                                                   CurBuffer,
   3849                                                   getTok().getLoc(),
   3850                                                   Instantiation);
   3851   ActiveMacros.push_back(MI);
   3852 
   3853   // Jump to the macro instantiation and prime the lexer.
   3854   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
   3855   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
   3856   Lex();
   3857 }
   3858 
   3859 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
   3860   int64_t Count;
   3861   if (parseAbsoluteExpression(Count))
   3862     return TokError("unexpected token in '.rept' directive");
   3863 
   3864   if (Count < 0)
   3865     return TokError("Count is negative");
   3866 
   3867   if (Lexer.isNot(AsmToken::EndOfStatement))
   3868     return TokError("unexpected token in '.rept' directive");
   3869 
   3870   // Eat the end of statement.
   3871   Lex();
   3872 
   3873   // Lex the rept definition.
   3874   MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
   3875   if (!M)
   3876     return true;
   3877 
   3878   // Macro instantiation is lexical, unfortunately. We construct a new buffer
   3879   // to hold the macro body with substitutions.
   3880   SmallString<256> Buf;
   3881   MCAsmMacroParameters Parameters;
   3882   MCAsmMacroArguments A;
   3883   raw_svector_ostream OS(Buf);
   3884   while (Count--) {
   3885     if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
   3886       return true;
   3887   }
   3888   InstantiateMacroLikeBody(M, DirectiveLoc, OS);
   3889 
   3890   return false;
   3891 }
   3892 
   3893 /// ParseDirectiveIrp
   3894 /// ::= .irp symbol,values
   3895 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
   3896   MCAsmMacroParameters Parameters;
   3897   MCAsmMacroParameter Parameter;
   3898 
   3899   if (parseIdentifier(Parameter.first))
   3900     return TokError("expected identifier in '.irp' directive");
   3901 
   3902   Parameters.push_back(Parameter);
   3903 
   3904   if (Lexer.isNot(AsmToken::Comma))
   3905     return TokError("expected comma in '.irp' directive");
   3906 
   3907   Lex();
   3908 
   3909   MCAsmMacroArguments A;
   3910   if (ParseMacroArguments(0, A))
   3911     return true;
   3912 
   3913   // Eat the end of statement.
   3914   Lex();
   3915 
   3916   // Lex the irp definition.
   3917   MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
   3918   if (!M)
   3919     return true;
   3920 
   3921   // Macro instantiation is lexical, unfortunately. We construct a new buffer
   3922   // to hold the macro body with substitutions.
   3923   SmallString<256> Buf;
   3924   raw_svector_ostream OS(Buf);
   3925 
   3926   for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
   3927     MCAsmMacroArguments Args;
   3928     Args.push_back(*i);
   3929 
   3930     if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
   3931       return true;
   3932   }
   3933 
   3934   InstantiateMacroLikeBody(M, DirectiveLoc, OS);
   3935 
   3936   return false;
   3937 }
   3938 
   3939 /// ParseDirectiveIrpc
   3940 /// ::= .irpc symbol,values
   3941 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
   3942   MCAsmMacroParameters Parameters;
   3943   MCAsmMacroParameter Parameter;
   3944 
   3945   if (parseIdentifier(Parameter.first))
   3946     return TokError("expected identifier in '.irpc' directive");
   3947 
   3948   Parameters.push_back(Parameter);
   3949 
   3950   if (Lexer.isNot(AsmToken::Comma))
   3951     return TokError("expected comma in '.irpc' directive");
   3952 
   3953   Lex();
   3954 
   3955   MCAsmMacroArguments A;
   3956   if (ParseMacroArguments(0, A))
   3957     return true;
   3958 
   3959   if (A.size() != 1 || A.front().size() != 1)
   3960     return TokError("unexpected token in '.irpc' directive");
   3961 
   3962   // Eat the end of statement.
   3963   Lex();
   3964 
   3965   // Lex the irpc definition.
   3966   MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
   3967   if (!M)
   3968     return true;
   3969 
   3970   // Macro instantiation is lexical, unfortunately. We construct a new buffer
   3971   // to hold the macro body with substitutions.
   3972   SmallString<256> Buf;
   3973   raw_svector_ostream OS(Buf);
   3974 
   3975   StringRef Values = A.front().front().getString();
   3976   std::size_t I, End = Values.size();
   3977   for (I = 0; I < End; ++I) {
   3978     MCAsmMacroArgument Arg;
   3979     Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
   3980 
   3981     MCAsmMacroArguments Args;
   3982     Args.push_back(Arg);
   3983 
   3984     if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
   3985       return true;
   3986   }
   3987 
   3988   InstantiateMacroLikeBody(M, DirectiveLoc, OS);
   3989 
   3990   return false;
   3991 }
   3992 
   3993 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
   3994   if (ActiveMacros.empty())
   3995     return TokError("unmatched '.endr' directive");
   3996 
   3997   // The only .repl that should get here are the ones created by
   3998   // InstantiateMacroLikeBody.
   3999   assert(getLexer().is(AsmToken::EndOfStatement));
   4000 
   4001   HandleMacroExit();
   4002   return false;
   4003 }
   4004 
   4005 bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
   4006                                      size_t Len) {
   4007   const MCExpr *Value;
   4008   SMLoc ExprLoc = getLexer().getLoc();
   4009   if (parseExpression(Value))
   4010     return true;
   4011   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
   4012   if (!MCE)
   4013     return Error(ExprLoc, "unexpected expression in _emit");
   4014   uint64_t IntValue = MCE->getValue();
   4015   if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
   4016     return Error(ExprLoc, "literal value out of range for directive");
   4017 
   4018   Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
   4019   return false;
   4020 }
   4021 
   4022 bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
   4023   const MCExpr *Value;
   4024   SMLoc ExprLoc = getLexer().getLoc();
   4025   if (parseExpression(Value))
   4026     return true;
   4027   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
   4028   if (!MCE)
   4029     return Error(ExprLoc, "unexpected expression in align");
   4030   uint64_t IntValue = MCE->getValue();
   4031   if (!isPowerOf2_64(IntValue))
   4032     return Error(ExprLoc, "literal value not a power of two greater then zero");
   4033 
   4034   Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
   4035                                          Log2_64(IntValue)));
   4036   return false;
   4037 }
   4038 
   4039 // We are comparing pointers, but the pointers are relative to a single string.
   4040 // Thus, this should always be deterministic.
   4041 static int RewritesSort(const void *A, const void *B) {
   4042   const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
   4043   const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
   4044   if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
   4045     return -1;
   4046   if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
   4047     return 1;
   4048 
   4049   // It's possible to have a SizeDirective rewrite and an Input/Output rewrite
   4050   // to the same location.  Make sure the SizeDirective rewrite is performed
   4051   // first.  This also ensure the sort algorithm is stable.
   4052   if (AsmRewriteA->Kind == AOK_SizeDirective) {
   4053     assert ((AsmRewriteB->Kind == AOK_Input || AsmRewriteB->Kind == AOK_Output) &&
   4054             "Expected an Input/Output rewrite!");
   4055     return -1;
   4056   }
   4057   if (AsmRewriteB->Kind == AOK_SizeDirective) {
   4058     assert ((AsmRewriteA->Kind == AOK_Input || AsmRewriteA->Kind == AOK_Output) &&
   4059             "Expected an Input/Output rewrite!");
   4060     return 1;
   4061   }
   4062   llvm_unreachable ("Unstable rewrite sort.");
   4063 }
   4064 
   4065 bool
   4066 AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
   4067                             unsigned &NumOutputs, unsigned &NumInputs,
   4068                             SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
   4069                             SmallVectorImpl<std::string> &Constraints,
   4070                             SmallVectorImpl<std::string> &Clobbers,
   4071                             const MCInstrInfo *MII,
   4072                             const MCInstPrinter *IP,
   4073                             MCAsmParserSemaCallback &SI) {
   4074   SmallVector<void *, 4> InputDecls;
   4075   SmallVector<void *, 4> OutputDecls;
   4076   SmallVector<bool, 4> InputDeclsAddressOf;
   4077   SmallVector<bool, 4> OutputDeclsAddressOf;
   4078   SmallVector<std::string, 4> InputConstraints;
   4079   SmallVector<std::string, 4> OutputConstraints;
   4080   SmallVector<unsigned, 4> ClobberRegs;
   4081 
   4082   SmallVector<AsmRewrite, 4> AsmStrRewrites;
   4083 
   4084   // Prime the lexer.
   4085   Lex();
   4086 
   4087   // While we have input, parse each statement.
   4088   unsigned InputIdx = 0;
   4089   unsigned OutputIdx = 0;
   4090   while (getLexer().isNot(AsmToken::Eof)) {
   4091     ParseStatementInfo Info(&AsmStrRewrites);
   4092     if (ParseStatement(Info))
   4093       return true;
   4094 
   4095     if (Info.ParseError)
   4096       return true;
   4097 
   4098     if (Info.Opcode == ~0U)
   4099       continue;
   4100 
   4101     const MCInstrDesc &Desc = MII->get(Info.Opcode);
   4102 
   4103     // Build the list of clobbers, outputs and inputs.
   4104     for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
   4105       MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
   4106 
   4107       // Immediate.
   4108       if (Operand->isImm()) {
   4109         if (Operand->needAsmRewrite())
   4110           AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
   4111                                               Operand->getStartLoc()));
   4112         continue;
   4113       }
   4114 
   4115       // Register operand.
   4116       if (Operand->isReg() && !Operand->needAddressOf()) {
   4117         unsigned NumDefs = Desc.getNumDefs();
   4118         // Clobber.
   4119         if (NumDefs && Operand->getMCOperandNum() < NumDefs)
   4120           ClobberRegs.push_back(Operand->getReg());
   4121         continue;
   4122       }
   4123 
   4124       // Expr/Input or Output.
   4125       bool IsVarDecl;
   4126       unsigned Length, Size, Type;
   4127       void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
   4128                                                   Length, Size, Type,
   4129                                                   IsVarDecl);
   4130       if (!OpDecl)
   4131         continue;
   4132 
   4133       bool isOutput = (i == 1) && Desc.mayStore();
   4134       if (Operand->isMem() && Operand->needSizeDirective())
   4135         AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
   4136                                             Operand->getStartLoc(), /*Len*/0,
   4137                                             Operand->getMemSize()));
   4138 
   4139       if (isOutput) {
   4140         ++InputIdx;
   4141         OutputDecls.push_back(OpDecl);
   4142         OutputDeclsAddressOf.push_back(Operand->needAddressOf());
   4143         OutputConstraints.push_back('=' + Operand->getConstraint().str());
   4144         AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Operand->getStartLoc(),
   4145                                             Operand->getNameLen()));
   4146       } else {
   4147         InputDecls.push_back(OpDecl);
   4148         InputDeclsAddressOf.push_back(Operand->needAddressOf());
   4149         InputConstraints.push_back(Operand->getConstraint().str());
   4150         AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Operand->getStartLoc(),
   4151                                             Operand->getNameLen()));
   4152       }
   4153     }
   4154   }
   4155 
   4156   // Set the number of Outputs and Inputs.
   4157   NumOutputs = OutputDecls.size();
   4158   NumInputs = InputDecls.size();
   4159 
   4160   // Set the unique clobbers.
   4161   array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
   4162   ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
   4163                     ClobberRegs.end());
   4164   Clobbers.assign(ClobberRegs.size(), std::string());
   4165   for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
   4166     raw_string_ostream OS(Clobbers[I]);
   4167     IP->printRegName(OS, ClobberRegs[I]);
   4168   }
   4169 
   4170   // Merge the various outputs and inputs.  Output are expected first.
   4171   if (NumOutputs || NumInputs) {
   4172     unsigned NumExprs = NumOutputs + NumInputs;
   4173     OpDecls.resize(NumExprs);
   4174     Constraints.resize(NumExprs);
   4175     for (unsigned i = 0; i < NumOutputs; ++i) {
   4176       OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
   4177       Constraints[i] = OutputConstraints[i];
   4178     }
   4179     for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
   4180       OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
   4181       Constraints[j] = InputConstraints[i];
   4182     }
   4183   }
   4184 
   4185   // Build the IR assembly string.
   4186   std::string AsmStringIR;
   4187   AsmRewriteKind PrevKind = AOK_Imm;
   4188   raw_string_ostream OS(AsmStringIR);
   4189   const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
   4190   array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
   4191   for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
   4192                                              E = AsmStrRewrites.end();
   4193        I != E; ++I) {
   4194     const char *Loc = (*I).Loc.getPointer();
   4195     assert(Loc >= Start && "Expected Loc to be after Start!");
   4196 
   4197     unsigned AdditionalSkip = 0;
   4198     AsmRewriteKind Kind = (*I).Kind;
   4199 
   4200     // Emit everything up to the immediate/expression.  If the previous rewrite
   4201     // was a size directive, then this has already been done.
   4202     if (PrevKind != AOK_SizeDirective)
   4203       OS << StringRef(Start, Loc - Start);
   4204     PrevKind = Kind;
   4205 
   4206     // Skip the original expression.
   4207     if (Kind == AOK_Skip) {
   4208       Start = Loc + (*I).Len;
   4209       continue;
   4210     }
   4211 
   4212     // Rewrite expressions in $N notation.
   4213     switch (Kind) {
   4214     default: break;
   4215     case AOK_Imm:
   4216       OS << "$$" << (*I).Val;
   4217       break;
   4218     case AOK_ImmPrefix:
   4219       OS << "$$";
   4220       break;
   4221     case AOK_Input:
   4222       OS << '$' << InputIdx++;
   4223       break;
   4224     case AOK_Output:
   4225       OS << '$' << OutputIdx++;
   4226       break;
   4227     case AOK_SizeDirective:
   4228       switch ((*I).Val) {
   4229       default: break;
   4230       case 8:  OS << "byte ptr "; break;
   4231       case 16: OS << "word ptr "; break;
   4232       case 32: OS << "dword ptr "; break;
   4233       case 64: OS << "qword ptr "; break;
   4234       case 80: OS << "xword ptr "; break;
   4235       case 128: OS << "xmmword ptr "; break;
   4236       case 256: OS << "ymmword ptr "; break;
   4237       }
   4238       break;
   4239     case AOK_Emit:
   4240       OS << ".byte";
   4241       break;
   4242     case AOK_Align: {
   4243       unsigned Val = (*I).Val;
   4244       OS << ".align " << Val;
   4245 
   4246       // Skip the original immediate.
   4247       assert(Val < 10 && "Expected alignment less then 2^10.");
   4248       AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
   4249       break;
   4250     }
   4251     case AOK_DotOperator:
   4252       OS << (*I).Val;
   4253       break;
   4254     }
   4255 
   4256     // Skip the original expression.
   4257     if (Kind != AOK_SizeDirective)
   4258       Start = Loc + (*I).Len + AdditionalSkip;
   4259   }
   4260 
   4261   // Emit the remainder of the asm string.
   4262   const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
   4263   if (Start != AsmEnd)
   4264     OS << StringRef(Start, AsmEnd - Start);
   4265 
   4266   AsmString = OS.str();
   4267   return false;
   4268 }
   4269 
   4270 /// \brief Create an MCAsmParser instance.
   4271 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
   4272                                      MCContext &C, MCStreamer &Out,
   4273                                      const MCAsmInfo &MAI) {
   4274   return new AsmParser(SM, C, Out, MAI);
   4275 }
   4276