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