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