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