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