blob: 0db343049f374ba5b6e3cf373de82758d97df197 [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- 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
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000016#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000017#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000018#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000019#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000020#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000021#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000022#include "llvm/MC/MCInstPrinter.h"
23#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000024#include "llvm/MC/MCParser/AsmCond.h"
25#include "llvm/MC/MCParser/AsmLexer.h"
26#include "llvm/MC/MCParser/MCAsmParser.h"
27#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000028#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000029#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000030#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000031#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000032#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000033#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000034#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000035#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000037#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000038#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000039#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000040#include <set>
41#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000042#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000043using namespace llvm;
44
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000045static cl::opt<bool>
46FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
48
Eric Christopher2318ba12012-12-18 00:30:54 +000049MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000050
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000051namespace {
52
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000053/// \brief Helper class for storing information about an active macro
54/// instantiation.
55struct MacroInstantiation {
56 /// The macro being instantiated.
Eli Benderskyc0c67b02013-01-14 23:22:36 +000057 const MCAsmMacro *TheMacro;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000058
59 /// The macro instantiation with substitutions.
60 MemoryBuffer *Instantiation;
61
62 /// The location of the instantiation.
63 SMLoc InstantiationLoc;
64
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000065 /// The buffer where parsing should resume upon instantiation completion.
66 int ExitBuffer;
67
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000068 /// The location where parsing should resume upon instantiation completion.
69 SMLoc ExitLoc;
70
71public:
Eli Benderskyc0c67b02013-01-14 23:22:36 +000072 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000073 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000074};
75
Chad Rosier6a020a72012-10-25 20:41:34 +000076//struct AsmRewrite;
Eli Friedman2128aae2012-10-22 23:58:19 +000077struct ParseStatementInfo {
78 /// ParsedOperands - The parsed operands from the last parsed statement.
79 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
80
81 /// Opcode - The opcode from the last parsed instruction.
82 unsigned Opcode;
83
Chad Rosier57498012012-12-12 22:45:52 +000084 /// Error - Was there an error parsing the inline assembly?
85 bool ParseError;
86
Eli Friedman2128aae2012-10-22 23:58:19 +000087 SmallVectorImpl<AsmRewrite> *AsmRewrites;
88
Chad Rosier57498012012-12-12 22:45:52 +000089 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +000090 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +000091 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +000092
93 ~ParseStatementInfo() {
94 // Free any parsed operands.
95 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
96 delete ParsedOperands[i];
97 ParsedOperands.clear();
98 }
99};
100
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000101/// \brief The concrete assembly parser instance.
102class AsmParser : public MCAsmParser {
Craig Topper85aadc02012-09-15 16:23:52 +0000103 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
104 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000105private:
106 AsmLexer Lexer;
107 MCContext &Ctx;
108 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000109 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000110 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000111 SourceMgr::DiagHandlerTy SavedDiagHandler;
112 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000113 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000114
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000115 /// This is the current buffer index we're lexing from as managed by the
116 /// SourceMgr object.
117 int CurBuffer;
118
119 AsmCond TheCondState;
120 std::vector<AsmCond> TheCondStack;
121
Eli Bendersky6ee13082013-01-15 22:59:42 +0000122 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
123 /// extensions. Extensions register themselves in this map by calling
124 /// AddDirectiveHandler.
Eli Bendersky6ee13082013-01-15 22:59:42 +0000125 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000126
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000127 /// MacroMap - Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000128 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000129
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000130 /// ActiveMacros - Stack of active macro instantiations.
131 std::vector<MacroInstantiation*> ActiveMacros;
132
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000133 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000134 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000135
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000136 /// Flag tracking whether any errors have been encountered.
137 unsigned HadError : 1;
138
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000139 /// The values from the last parsed cpp hash file line comment if any.
140 StringRef CppHashFilename;
141 int64_t CppHashLineNumber;
142 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000143 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000144
Devang Patel0db58bf2012-01-31 18:14:05 +0000145 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
146 unsigned AssemblerDialect;
147
Preston Gurd7b6f2032012-09-19 20:36:12 +0000148 /// IsDarwin - is Darwin compatibility enabled?
149 bool IsDarwin;
150
Chad Rosier8f138d12012-10-15 17:19:13 +0000151 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000152 bool ParsingInlineAsm;
153
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000154public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000155 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000156 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000157 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000158
159 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
160
Eli Bendersky171192f2013-01-16 00:50:52 +0000161 virtual void AddDirectiveHandler(StringRef Directive,
162 ExtensionDirectiveHandler Handler) {
163 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000164 }
165
166public:
167 /// @name MCAsmParser Interface
168 /// {
169
170 virtual SourceMgr &getSourceManager() { return SrcMgr; }
171 virtual MCAsmLexer &getLexer() { return Lexer; }
172 virtual MCContext &getContext() { return Ctx; }
173 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000174 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000175 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000176 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000177 else
178 return AssemblerDialect;
179 }
180 virtual void setAssemblerDialect(unsigned i) {
181 AssemblerDialect = i;
182 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000183
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000184 virtual bool Warning(SMLoc L, const Twine &Msg,
185 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
186 virtual bool Error(SMLoc L, const Twine &Msg,
187 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000188
Craig Topper345d16d2012-08-29 05:48:09 +0000189 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000190
Chad Rosier84125ca2012-10-13 00:26:04 +0000191 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000192 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000193
194 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
195 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000196 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000197 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000198 SmallVectorImpl<std::string> &Clobbers,
199 const MCInstrInfo *MII,
200 const MCInstPrinter *IP,
201 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000202
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000203 bool ParseExpression(const MCExpr *&Res);
204 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
205 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
206 virtual bool ParseAbsoluteExpression(int64_t &Res);
207
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000208 bool ParseMacroArgument(MCAsmMacroArgument &MA,
209 AsmToken::TokenKind &ArgumentDelimiter);
210
Eli Benderskybf706b32013-01-12 00:05:00 +0000211 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
212 /// and set \p Res to the identifier contents.
213 virtual bool ParseIdentifier(StringRef &Res);
Eli Benderskyb2f0b592013-01-12 00:23:24 +0000214 virtual void EatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000215
Eli Bendersky733c3362013-01-14 18:08:41 +0000216 virtual bool MacrosEnabled() {return MacrosEnabledFlag;}
217 virtual void SetMacrosEnabled(bool flag) {MacrosEnabledFlag = flag;}
218
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000219 virtual const MCAsmMacro* LookupMacro(StringRef Name);
220 virtual void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
221 virtual void UndefineMacro(StringRef Name);
222
223 virtual bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
224 virtual bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
225 void HandleMacroExit();
226
Eli Bendersky318cad32013-01-14 19:15:01 +0000227 virtual void CheckForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000228 /// }
229
230private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000231
Eli Friedman2128aae2012-10-22 23:58:19 +0000232 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000233 void EatToEndOfLine();
234 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000235
Rafael Espindola761cb062012-06-03 23:57:14 +0000236 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000237 const MCAsmMacroParameters &Parameters,
238 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000239 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000240
241 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000242 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000243 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
244 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000245 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000246 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000247
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000248 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
249 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000250 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
251 /// This returns true on failure.
252 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000253
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000254 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000255 /// current token is not set; clients should ensure Lex() is called
256 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000257 ///
258 /// \param InBuffer If not -1, should be the known buffer id that contains the
259 /// location.
260 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000261
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000262 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000263
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000264 /// \brief Parse up to the end of statement and a return the contents from the
265 /// current token until the end of the statement; the current token on exit
266 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000267 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000268
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000269 /// \brief Parse until the end of a statement or a comma is encountered,
270 /// return the contents from the current token up to the end or comma.
271 StringRef ParseStringToComma();
272
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000273 bool ParseAssignment(StringRef Name, bool allow_redef,
274 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000275
276 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
277 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
278 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000279 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000280
Eli Bendersky6ee13082013-01-15 22:59:42 +0000281 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000282
Eli Bendersky6ee13082013-01-15 22:59:42 +0000283 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000284 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000285 DK_NO_DIRECTIVE, // Placeholder
286 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
287 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
288 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000289 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000290 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
291 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
292 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
293 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
294 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
295 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
296 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000297 DK_ELSEIF, DK_ELSE, DK_ENDIF,
298 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
299 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
300 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
301 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
302 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
303 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
304 DK_CFI_REGISTER,
305 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
306 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000307 };
308
Eli Bendersky6ee13082013-01-15 22:59:42 +0000309 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
310 /// directives parsed by this class.
311 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000312
313 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000314 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000315 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000316 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000317 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000318 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000319 // ".set", ".equ", ".equiv"
320 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000321 bool ParseDirectiveOrg(); // ".org"
322 // ".align{,32}", ".p2align{,w,l}"
323 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
324
Eli Bendersky6ee13082013-01-15 22:59:42 +0000325 // ".file", ".line", ".loc", ".stabs"
326 bool ParseDirectiveFile(SMLoc DirectiveLoc);
327 bool ParseDirectiveLine();
328 bool ParseDirectiveLoc();
329 bool ParseDirectiveStabs();
330
331 // .cfi directives
332 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
333 bool ParseDirectiveCFISections();
334 bool ParseDirectiveCFIStartProc();
335 bool ParseDirectiveCFIEndProc();
336 bool ParseDirectiveCFIDefCfaOffset();
337 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
338 bool ParseDirectiveCFIAdjustCfaOffset();
339 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
340 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
341 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
342 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
343 bool ParseDirectiveCFIRememberState();
344 bool ParseDirectiveCFIRestoreState();
345 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
346 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
347 bool ParseDirectiveCFIEscape();
348 bool ParseDirectiveCFISignalFrame();
349 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
350
351 // macro directives
352 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
353 bool ParseDirectiveEndMacro(StringRef Directive);
354 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
355 bool ParseDirectiveMacrosOnOff(StringRef Directive);
356
Eli Bendersky4766ef42012-12-20 19:05:53 +0000357 // ".bundle_align_mode"
358 bool ParseDirectiveBundleAlignMode();
359 // ".bundle_lock"
360 bool ParseDirectiveBundleLock();
361 // ".bundle_unlock"
362 bool ParseDirectiveBundleUnlock();
363
Eli Bendersky6ee13082013-01-15 22:59:42 +0000364 // ".space", ".skip"
365 bool ParseDirectiveSpace(StringRef IDVal);
366
367 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
368 bool ParseDirectiveLEB128(bool Signed);
369
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000370 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
371 /// accepts a single symbol (which should be a label or an external).
372 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000373
374 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
375
376 bool ParseDirectiveAbort(); // ".abort"
377 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000378 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000379
380 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000381 // ".ifb" or ".ifnb", depending on ExpectBlank.
382 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000383 // ".ifc" or ".ifnc", depending on ExpectEqual.
384 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000385 // ".ifdef" or ".ifndef", depending on expect_defined
386 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000387 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
388 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
389 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
390
391 /// ParseEscapedString - Parse the current token as a string which may include
392 /// escaped characters and return the string contents.
393 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000394
395 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
396 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000397
Rafael Espindola761cb062012-06-03 23:57:14 +0000398 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000399 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
400 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000401 raw_svector_ostream &OS);
402 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000403 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000404 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000405 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000406
Eli Friedman2128aae2012-10-22 23:58:19 +0000407 // "_emit"
408 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000409
Eli Bendersky6ee13082013-01-15 22:59:42 +0000410 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000411};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000412}
413
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000414namespace llvm {
415
416extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000417extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000418extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000419
420}
421
Chris Lattneraaec2052010-01-19 19:46:13 +0000422enum { DEFAULT_ADDRSPACE = 0 };
423
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000424AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000425 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000426 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000427 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000428 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000429 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000430 // Save the old handler.
431 SavedDiagHandler = SrcMgr.getDiagHandler();
432 SavedDiagContext = SrcMgr.getDiagContext();
433 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000434 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000435 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000436
Daniel Dunbare4749702010-07-12 18:12:02 +0000437 // Initialize the platform / file format parser.
438 //
439 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
440 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000441 if (_MAI.hasMicrosoftFastStdCallMangling()) {
442 PlatformParser = createCOFFAsmParser();
443 PlatformParser->Initialize(*this);
444 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000445 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000446 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000447 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000448 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000449 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000450 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000451 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000452
Eli Bendersky6ee13082013-01-15 22:59:42 +0000453 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000454}
455
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000456AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000457 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
458
459 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000460 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000461 ie = MacroMap.end(); it != ie; ++it)
462 delete it->getValue();
463
Daniel Dunbare4749702010-07-12 18:12:02 +0000464 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000465}
466
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000467void AsmParser::PrintMacroInstantiations() {
468 // Print the active macro instantiation stack.
469 for (std::vector<MacroInstantiation*>::const_reverse_iterator
470 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000471 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
472 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000473}
474
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000475bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000476 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000477 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000478 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000479 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000480 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000481}
482
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000483bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000484 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000485 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000486 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000487 return true;
488}
489
Sean Callananfd0b0282010-01-21 00:19:58 +0000490bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000491 std::string IncludedFile;
492 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000493 if (NewBuf == -1)
494 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000495
Sean Callananfd0b0282010-01-21 00:19:58 +0000496 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000497
Sean Callananfd0b0282010-01-21 00:19:58 +0000498 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000499
Sean Callananfd0b0282010-01-21 00:19:58 +0000500 return false;
501}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000502
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000503/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000504/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000505/// returns true on failure.
506bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
507 std::string IncludedFile;
508 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
509 if (NewBuf == -1)
510 return true;
511
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000512 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000513 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
514 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000515 return false;
516}
517
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000518void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
519 if (InBuffer != -1) {
520 CurBuffer = InBuffer;
521 } else {
522 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
523 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000524 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
525}
526
Sean Callananfd0b0282010-01-21 00:19:58 +0000527const AsmToken &AsmParser::Lex() {
528 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000529
Sean Callananfd0b0282010-01-21 00:19:58 +0000530 if (tok->is(AsmToken::Eof)) {
531 // If this is the end of an included file, pop the parent file off the
532 // include stack.
533 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
534 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000535 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000536 tok = &Lexer.Lex();
537 }
538 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000539
Sean Callananfd0b0282010-01-21 00:19:58 +0000540 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000541 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000542
Sean Callananfd0b0282010-01-21 00:19:58 +0000543 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000544}
545
Chris Lattner79180e22010-04-05 23:15:42 +0000546bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000547 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000548 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000549 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000550
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000551 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000552 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000553
554 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000555 AsmCond StartingCondState = TheCondState;
556
Kevin Enderby613b7572011-11-01 22:27:22 +0000557 // If we are generating dwarf for assembly source files save the initial text
558 // section and generate a .file directive.
559 if (getContext().getGenDwarfForAssembly()) {
560 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000561 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
562 getStreamer().EmitLabel(SectionStartSym);
563 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000564 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000565 StringRef(),
566 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000567 }
568
Chris Lattnerb717fb02009-07-02 21:53:43 +0000569 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000570 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000571 ParseStatementInfo Info;
572 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000573
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000574 // We had an error, validate that one was emitted and recover by skipping to
575 // the next line.
576 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000577 EatToEndOfStatement();
578 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000579
580 if (TheCondState.TheCond != StartingCondState.TheCond ||
581 TheCondState.Ignore != StartingCondState.Ignore)
582 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000583
584 // Check to see there are no empty DwarfFile slots.
585 const std::vector<MCDwarfFile *> &MCDwarfFiles =
586 getContext().getMCDwarfFiles();
587 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000588 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000589 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000590 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000591
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000592 // Check to see that all assembler local symbols were actually defined.
593 // Targets that don't do subsections via symbols may not want this, though,
594 // so conservatively exclude them. Only do this if we're finalizing, though,
595 // as otherwise we won't necessarilly have seen everything yet.
596 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
597 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
598 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
599 e = Symbols.end();
600 i != e; ++i) {
601 MCSymbol *Sym = i->getValue();
602 // Variable symbols may not be marked as defined, so check those
603 // explicitly. If we know it's a variable, we have a definition for
604 // the purposes of this check.
605 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
606 // FIXME: We would really like to refer back to where the symbol was
607 // first referenced for a source location. We need to add something
608 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000609 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
610 "assembler local symbol '" + Sym->getName() +
611 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000612 }
613 }
614
615
Chris Lattner79180e22010-04-05 23:15:42 +0000616 // Finalize the output stream if there are no errors and if the client wants
617 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000618 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000619 Out.Finish();
620
Chris Lattnerb717fb02009-07-02 21:53:43 +0000621 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000622}
623
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000624void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000625 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000626 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000627 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000628 }
629}
630
Chris Lattner2cf5f142009-06-22 01:29:09 +0000631/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
632void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000633 while (Lexer.isNot(AsmToken::EndOfStatement) &&
634 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000635 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000636
Chris Lattner2cf5f142009-06-22 01:29:09 +0000637 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000638 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000639 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000640}
641
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000642StringRef AsmParser::ParseStringToEndOfStatement() {
643 const char *Start = getTok().getLoc().getPointer();
644
645 while (Lexer.isNot(AsmToken::EndOfStatement) &&
646 Lexer.isNot(AsmToken::Eof))
647 Lex();
648
649 const char *End = getTok().getLoc().getPointer();
650 return StringRef(Start, End - Start);
651}
Chris Lattnerc4193832009-06-22 05:51:26 +0000652
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000653StringRef AsmParser::ParseStringToComma() {
654 const char *Start = getTok().getLoc().getPointer();
655
656 while (Lexer.isNot(AsmToken::EndOfStatement) &&
657 Lexer.isNot(AsmToken::Comma) &&
658 Lexer.isNot(AsmToken::Eof))
659 Lex();
660
661 const char *End = getTok().getLoc().getPointer();
662 return StringRef(Start, End - Start);
663}
664
Chris Lattner74ec1a32009-06-22 06:32:03 +0000665/// ParseParenExpr - Parse a paren expression and return it.
666/// NOTE: This assumes the leading '(' has already been consumed.
667///
668/// parenexpr ::= expr)
669///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000670bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000671 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000672 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000673 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000674 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000675 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000676 return false;
677}
Chris Lattnerc4193832009-06-22 05:51:26 +0000678
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000679/// ParseBracketExpr - Parse a bracket expression and return it.
680/// NOTE: This assumes the leading '[' has already been consumed.
681///
682/// bracketexpr ::= expr]
683///
684bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
685 if (ParseExpression(Res)) return true;
686 if (Lexer.isNot(AsmToken::RBrac))
687 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000688 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000689 Lex();
690 return false;
691}
692
Chris Lattner74ec1a32009-06-22 06:32:03 +0000693/// ParsePrimaryExpr - Parse a primary expression and return it.
694/// primaryexpr ::= (parenexpr
695/// primaryexpr ::= symbol
696/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000697/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000698/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000699bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000700 switch (Lexer.getKind()) {
701 default:
702 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000703 // If we have an error assume that we've already handled it.
704 case AsmToken::Error:
705 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000706 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000707 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000708 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000709 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000710 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000711 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000712 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000713 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000714 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000715 StringRef Identifier;
716 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000717 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000718
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000719 EndLoc = SMLoc::getFromPointer(Identifier.end());
720
Daniel Dunbarfffff912009-10-16 01:34:54 +0000721 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000722 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000723 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000724
725 // Lookup the symbol variant if used.
726 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000727 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000728 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000729 if (Variant == MCSymbolRefExpr::VK_Invalid) {
730 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000731 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000732 }
733 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000734
Daniel Dunbarfffff912009-10-16 01:34:54 +0000735 // If this is an absolute variable reference, substitute it now to preserve
736 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000737 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000738 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000739 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000740
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000741 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000742 return false;
743 }
744
745 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000746 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000747 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000748 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000749 case AsmToken::Integer: {
750 SMLoc Loc = getTok().getLoc();
751 int64_t IntVal = getTok().getIntVal();
752 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000753 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000754 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000755 // Look for 'b' or 'f' following an Integer as a directional label
756 if (Lexer.getKind() == AsmToken::Identifier) {
757 StringRef IDVal = getTok().getString();
758 if (IDVal == "f" || IDVal == "b"){
759 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
760 IDVal == "f" ? 1 : 0);
761 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
762 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000763 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000764 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000765 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000766 Lex(); // Eat identifier.
767 }
768 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000769 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000770 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000771 case AsmToken::Real: {
772 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000773 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000774 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000775 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000776 Lex(); // Eat token.
777 return false;
778 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000779 case AsmToken::Dot: {
780 // This is a '.' reference, which references the current PC. Emit a
781 // temporary label to the streamer and refer to it.
782 MCSymbol *Sym = Ctx.CreateTempSymbol();
783 Out.EmitLabel(Sym);
784 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000785 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000786 Lex(); // Eat identifier.
787 return false;
788 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000789 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000790 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000791 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000792 case AsmToken::LBrac:
793 if (!PlatformParser->HasBracketExpressions())
794 return TokError("brackets expression not supported on this target");
795 Lex(); // Eat the '['.
796 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000797 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000798 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000799 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000800 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000801 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000802 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000803 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000804 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000805 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000806 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000807 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000808 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000809 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000810 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000811 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000812 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000813 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000814 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000815 }
816}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000817
Chris Lattnerb4307b32010-01-15 19:28:38 +0000818bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000819 SMLoc EndLoc;
820 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000821}
822
Daniel Dunbarcceba832010-09-17 02:47:07 +0000823const MCExpr *
824AsmParser::ApplyModifierToExpr(const MCExpr *E,
825 MCSymbolRefExpr::VariantKind Variant) {
826 // Recurse over the given expression, rebuilding it to apply the given variant
827 // if there is exactly one symbol.
828 switch (E->getKind()) {
829 case MCExpr::Target:
830 case MCExpr::Constant:
831 return 0;
832
833 case MCExpr::SymbolRef: {
834 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
835
836 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
837 TokError("invalid variant on expression '" +
838 getTok().getIdentifier() + "' (already modified)");
839 return E;
840 }
841
842 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
843 }
844
845 case MCExpr::Unary: {
846 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
847 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
848 if (!Sub)
849 return 0;
850 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
851 }
852
853 case MCExpr::Binary: {
854 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
855 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
856 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
857
858 if (!LHS && !RHS)
859 return 0;
860
861 if (!LHS) LHS = BE->getLHS();
862 if (!RHS) RHS = BE->getRHS();
863
864 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
865 }
866 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000867
Craig Topper85814382012-02-07 05:05:23 +0000868 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000869}
870
Chris Lattner74ec1a32009-06-22 06:32:03 +0000871/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000872///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000873/// expr ::= expr &&,|| expr -> lowest.
874/// expr ::= expr |,^,&,! expr
875/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
876/// expr ::= expr <<,>> expr
877/// expr ::= expr +,- expr
878/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000879/// expr ::= primaryexpr
880///
Chris Lattner54482b42010-01-15 19:39:23 +0000881bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000882 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000883 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000884 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
885 return true;
886
Daniel Dunbarcceba832010-09-17 02:47:07 +0000887 // As a special case, we support 'a op b @ modifier' by rewriting the
888 // expression to include the modifier. This is inefficient, but in general we
889 // expect users to use 'a@modifier op b'.
890 if (Lexer.getKind() == AsmToken::At) {
891 Lex();
892
893 if (Lexer.isNot(AsmToken::Identifier))
894 return TokError("unexpected symbol modifier following '@'");
895
896 MCSymbolRefExpr::VariantKind Variant =
897 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
898 if (Variant == MCSymbolRefExpr::VK_Invalid)
899 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
900
901 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
902 if (!ModifiedRes) {
903 return TokError("invalid modifier '" + getTok().getIdentifier() +
904 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000905 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000906
Daniel Dunbarcceba832010-09-17 02:47:07 +0000907 Res = ModifiedRes;
908 Lex();
909 }
910
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000911 // Try to constant fold it up front, if possible.
912 int64_t Value;
913 if (Res->EvaluateAsAbsolute(Value))
914 Res = MCConstantExpr::Create(Value, getContext());
915
916 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000917}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000918
Chris Lattnerb4307b32010-01-15 19:28:38 +0000919bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000920 Res = 0;
921 return ParseParenExpr(Res, EndLoc) ||
922 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000923}
924
Daniel Dunbar475839e2009-06-29 20:37:27 +0000925bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000926 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000927
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000928 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000929 if (ParseExpression(Expr))
930 return true;
931
Daniel Dunbare00b0112009-10-16 01:57:52 +0000932 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000933 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000934
935 return false;
936}
937
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000938static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000939 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000940 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000941 default:
942 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000943
Jim Grosbachfbe16812011-08-20 16:24:13 +0000944 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000945 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000946 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000947 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000948 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000949 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000950 return 1;
951
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000952
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000953 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000954 //
955 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000956 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000957 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000958 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000959 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000960 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000961 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000962 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000963 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000964 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000965
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000966 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000967 case AsmToken::EqualEqual:
968 Kind = MCBinaryExpr::EQ;
969 return 3;
970 case AsmToken::ExclaimEqual:
971 case AsmToken::LessGreater:
972 Kind = MCBinaryExpr::NE;
973 return 3;
974 case AsmToken::Less:
975 Kind = MCBinaryExpr::LT;
976 return 3;
977 case AsmToken::LessEqual:
978 Kind = MCBinaryExpr::LTE;
979 return 3;
980 case AsmToken::Greater:
981 Kind = MCBinaryExpr::GT;
982 return 3;
983 case AsmToken::GreaterEqual:
984 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000985 return 3;
986
Jim Grosbachfbe16812011-08-20 16:24:13 +0000987 // Intermediate Precedence: <<, >>
988 case AsmToken::LessLess:
989 Kind = MCBinaryExpr::Shl;
990 return 4;
991 case AsmToken::GreaterGreater:
992 Kind = MCBinaryExpr::Shr;
993 return 4;
994
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000995 // High Intermediate Precedence: +, -
996 case AsmToken::Plus:
997 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000998 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000999 case AsmToken::Minus:
1000 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001001 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001002
Jim Grosbachfbe16812011-08-20 16:24:13 +00001003 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001004 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001005 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001006 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001007 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001008 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001009 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001010 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001011 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001012 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001013 }
1014}
1015
1016
1017/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1018/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001019bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1020 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001021 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001022 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001023 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001024
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001025 // If the next token is lower precedence than we are allowed to eat, return
1026 // successfully with what we ate already.
1027 if (TokPrec < Precedence)
1028 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001029
Sean Callanan79ed1a82010-01-19 20:22:31 +00001030 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001031
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001032 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001033 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001034 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001035
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001036 // If BinOp binds less tightly with RHS than the operator after RHS, let
1037 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001038 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001039 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001040 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001041 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001042 }
1043
Daniel Dunbar475839e2009-06-29 20:37:27 +00001044 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001045 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001046 }
1047}
1048
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001049/// ParseStatement:
1050/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001051/// ::= Label* Directive ...Operands... EndOfStatement
1052/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001053bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001054 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001055 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001056 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001057 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001058 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001059
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001060 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001061 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001062 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001063 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001064 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001065 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001066 if (Lexer.is(AsmToken::Hash))
1067 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001068
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001069 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001070 if (Lexer.is(AsmToken::Integer)) {
1071 LocalLabelVal = getTok().getIntVal();
1072 if (LocalLabelVal < 0) {
1073 if (!TheCondState.Ignore)
1074 return TokError("unexpected token at start of statement");
1075 IDVal = "";
1076 }
1077 else {
1078 IDVal = getTok().getString();
1079 Lex(); // Consume the integer token to be used as an identifier token.
1080 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001081 if (!TheCondState.Ignore)
1082 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001083 }
1084 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001085
1086 } else if (Lexer.is(AsmToken::Dot)) {
1087 // Treat '.' as a valid identifier in this context.
1088 Lex();
1089 IDVal = ".";
1090
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001091 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001092 if (!TheCondState.Ignore)
1093 return TokError("unexpected token at start of statement");
1094 IDVal = "";
1095 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001096
Chris Lattner7834fac2010-04-17 18:14:27 +00001097 // Handle conditional assembly here before checking for skipping. We
1098 // have to do this so that .endif isn't skipped in a ".if 0" block for
1099 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001100 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001101 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001102 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001103 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1104 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001105 switch (DirKind) {
1106 default:
1107 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001108 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001109 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001110 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001111 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001112 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001113 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001114 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001115 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001116 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001117 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001118 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001119 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001120 case DK_IFNDEF:
1121 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001122 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001123 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001124 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001125 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001126 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001127 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001128 return ParseDirectiveEndIf(IDLoc);
1129 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001130
Chris Lattner7834fac2010-04-17 18:14:27 +00001131 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001132 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001133 EatToEndOfStatement();
1134 return false;
1135 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001136
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001137 // FIXME: Recurse on local labels?
1138
1139 // See what kind of statement we have.
1140 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001141 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001142 CheckForValidSection();
1143
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001144 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001145 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001146
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001147 // Diagnose attempt to use '.' as a label.
1148 if (IDVal == ".")
1149 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1150
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001151 // Diagnose attempt to use a variable as a label.
1152 //
1153 // FIXME: Diagnostics. Note the location of the definition as a label.
1154 // FIXME: This doesn't diagnose assignment to a symbol which has been
1155 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001156 MCSymbol *Sym;
1157 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001158 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001159 else
1160 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001161 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001162 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001163
Daniel Dunbar959fd882009-08-26 22:13:22 +00001164 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001165 if (!ParsingInlineAsm)
1166 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001167
Kevin Enderby94c2e852011-12-09 18:09:40 +00001168 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001169 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001170 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001171 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1172 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001173
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001174 // Consume any end of statement token, if present, to avoid spurious
1175 // AddBlankLine calls().
1176 if (Lexer.is(AsmToken::EndOfStatement)) {
1177 Lex();
1178 if (Lexer.is(AsmToken::Eof))
1179 return false;
1180 }
1181
Eli Friedman2128aae2012-10-22 23:58:19 +00001182 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001183 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001184
Daniel Dunbar3f872332009-07-28 16:08:33 +00001185 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001186 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001187 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001188
Nico Weber4c4c7322011-01-28 03:04:41 +00001189 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001190
1191 default: // Normal instruction or directive.
1192 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001193 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001194
1195 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001196 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001197 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1198 return HandleMacroEntry(M, IDLoc);
1199 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001200
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001201 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001202
1203 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001204 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001205 // There are several entities interested in parsing directives:
1206 //
1207 // 1. The target-specific assembly parser. Some directives are target
1208 // specific or may potentially behave differently on certain targets.
1209 // 2. Asm parser extensions. For example, platform-specific parsers
1210 // (like the ELF parser) register themselves as extensions.
1211 // 3. The generic directive parser implemented by this class. These are
1212 // all the directives that behave in a target and platform independent
1213 // manner, or at least have a default behavior that's shared between
1214 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001215
Eli Bendersky6ee13082013-01-15 22:59:42 +00001216 // First query the target-specific parser. It will return 'true' if it
1217 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001218 if (!getTargetParser().ParseDirective(ID))
1219 return false;
1220
Eli Bendersky6ee13082013-01-15 22:59:42 +00001221 // Next, check the extention directive map to see if any extension has
1222 // registered itself to parse this directive.
1223 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1224 ExtensionDirectiveMap.lookup(IDVal);
1225 if (Handler.first)
1226 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1227
1228 // Finally, if no one else is interested in this directive, it must be
1229 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001230 switch (DirKind) {
1231 default:
1232 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001233 case DK_SET:
1234 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001235 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001236 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001237 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001238 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001239 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001240 case DK_ASCIZ:
1241 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001242 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001243 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001244 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001245 case DK_SHORT:
1246 case DK_VALUE:
1247 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001248 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001249 case DK_LONG:
1250 case DK_INT:
1251 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001252 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001253 case DK_QUAD:
1254 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001255 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001256 case DK_SINGLE:
1257 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001258 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001259 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001260 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001261 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001262 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1263 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1264 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001265 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001266 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1267 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1268 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001269 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001270 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001271 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001272 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001273 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001274 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001275 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001276 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001277 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001278 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001279 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001280 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001281 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001282 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001283 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001284 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001285 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001286 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001287 case DK_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001288 EatToEndOfStatement(); // .extern is the default, ignore it.
1289 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001290 case DK_GLOBL:
1291 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001292 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001293 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001294 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001295 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001296 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001297 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001298 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001299 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001300 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001301 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001302 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001303 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001304 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001305 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001306 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001307 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001308 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001309 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001310 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_COMM:
1312 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001313 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001314 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001315 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001316 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001317 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001318 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001319 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001320 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001321 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001322 case DK_CODE16:
1323 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001324 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001325 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001326 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001327 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001328 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001329 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001330 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001331 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001332 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001333 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001334 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001335 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001336 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001337 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001338 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001339 case DK_SLEB128:
1340 return ParseDirectiveLEB128(true);
1341 case DK_ULEB128:
1342 return ParseDirectiveLEB128(false);
1343 case DK_SPACE:
1344 case DK_SKIP:
1345 return ParseDirectiveSpace(IDVal);
1346 case DK_FILE:
1347 return ParseDirectiveFile(IDLoc);
1348 case DK_LINE:
1349 return ParseDirectiveLine();
1350 case DK_LOC:
1351 return ParseDirectiveLoc();
1352 case DK_STABS:
1353 return ParseDirectiveStabs();
1354 case DK_CFI_SECTIONS:
1355 return ParseDirectiveCFISections();
1356 case DK_CFI_STARTPROC:
1357 return ParseDirectiveCFIStartProc();
1358 case DK_CFI_ENDPROC:
1359 return ParseDirectiveCFIEndProc();
1360 case DK_CFI_DEF_CFA:
1361 return ParseDirectiveCFIDefCfa(IDLoc);
1362 case DK_CFI_DEF_CFA_OFFSET:
1363 return ParseDirectiveCFIDefCfaOffset();
1364 case DK_CFI_ADJUST_CFA_OFFSET:
1365 return ParseDirectiveCFIAdjustCfaOffset();
1366 case DK_CFI_DEF_CFA_REGISTER:
1367 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1368 case DK_CFI_OFFSET:
1369 return ParseDirectiveCFIOffset(IDLoc);
1370 case DK_CFI_REL_OFFSET:
1371 return ParseDirectiveCFIRelOffset(IDLoc);
1372 case DK_CFI_PERSONALITY:
1373 return ParseDirectiveCFIPersonalityOrLsda(true);
1374 case DK_CFI_LSDA:
1375 return ParseDirectiveCFIPersonalityOrLsda(false);
1376 case DK_CFI_REMEMBER_STATE:
1377 return ParseDirectiveCFIRememberState();
1378 case DK_CFI_RESTORE_STATE:
1379 return ParseDirectiveCFIRestoreState();
1380 case DK_CFI_SAME_VALUE:
1381 return ParseDirectiveCFISameValue(IDLoc);
1382 case DK_CFI_RESTORE:
1383 return ParseDirectiveCFIRestore(IDLoc);
1384 case DK_CFI_ESCAPE:
1385 return ParseDirectiveCFIEscape();
1386 case DK_CFI_SIGNAL_FRAME:
1387 return ParseDirectiveCFISignalFrame();
1388 case DK_CFI_UNDEFINED:
1389 return ParseDirectiveCFIUndefined(IDLoc);
1390 case DK_CFI_REGISTER:
1391 return ParseDirectiveCFIRegister(IDLoc);
1392 case DK_MACROS_ON:
1393 case DK_MACROS_OFF:
1394 return ParseDirectiveMacrosOnOff(IDVal);
1395 case DK_MACRO:
1396 return ParseDirectiveMacro(IDLoc);
1397 case DK_ENDM:
1398 case DK_ENDMACRO:
1399 return ParseDirectiveEndMacro(IDVal);
1400 case DK_PURGEM:
1401 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001402 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001403
Jim Grosbach686c0182012-05-01 18:38:27 +00001404 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001405 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001406
Eli Friedman2128aae2012-10-22 23:58:19 +00001407 // _emit
1408 if (ParsingInlineAsm && IDVal == "_emit")
1409 return ParseDirectiveEmit(IDLoc, Info);
1410
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001411 CheckForValidSection();
1412
Chris Lattnera7f13542010-05-19 23:34:33 +00001413 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001414 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001415 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001416 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001417
Chad Rosier6a020a72012-10-25 20:41:34 +00001418 ParseInstructionInfo IInfo(Info.AsmRewrites);
1419 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1420 IDLoc,Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001421 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001422
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001423 // Dump the parsed representation, if requested.
1424 if (getShowParsedOperands()) {
1425 SmallString<256> Str;
1426 raw_svector_ostream OS(Str);
1427 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001428 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001429 if (i != 0)
1430 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001431 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001432 }
1433 OS << "]";
1434
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001435 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001436 }
1437
Kevin Enderby613b7572011-11-01 22:27:22 +00001438 // If we are generating dwarf for assembly source files and the current
1439 // section is the initial text section then generate a .loc directive for
1440 // the instruction.
1441 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001442 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001443
1444 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1445
1446 // If we previously parsed a cpp hash file line comment then make sure the
1447 // current Dwarf File is for the CppHashFilename if not then emit the
1448 // Dwarf File table for it and adjust the line number for the .loc.
1449 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1450 getContext().getMCDwarfFiles();
1451 if (CppHashFilename.size() != 0) {
1452 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1453 CppHashFilename)
Eric Christopher2318ba12012-12-18 00:30:54 +00001454 getStreamer().EmitDwarfFileDirective(
1455 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001456
Kevin Enderby32c1a822012-11-05 21:55:41 +00001457 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001458 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1459 }
1460
Kevin Enderby613b7572011-11-01 22:27:22 +00001461 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001462 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001463 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001464 StringRef());
1465 }
1466
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001467 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001468 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001469 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001470 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1471 Info.ParsedOperands,
1472 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001473 ParsingInlineAsm);
1474 }
Chris Lattner98986712010-01-14 22:21:20 +00001475
Chris Lattnercbf8a982010-09-11 16:18:25 +00001476 // Don't skip the rest of the line, the instruction parser is responsible for
1477 // that.
1478 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001479}
Chris Lattner9a023f72009-06-24 04:43:34 +00001480
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001481/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1482/// since they may not be able to be tokenized to get to the end of line token.
1483void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001484 if (!Lexer.is(AsmToken::EndOfStatement))
1485 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001486 // Eat EOL.
1487 Lex();
1488}
1489
1490/// ParseCppHashLineFilenameComment as this:
1491/// ::= # number "filename"
1492/// or just as a full line comment if it doesn't have a number and a string.
1493bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1494 Lex(); // Eat the hash token.
1495
1496 if (getLexer().isNot(AsmToken::Integer)) {
1497 // Consume the line since in cases it is not a well-formed line directive,
1498 // as if were simply a full line comment.
1499 EatToEndOfLine();
1500 return false;
1501 }
1502
1503 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001504 Lex();
1505
1506 if (getLexer().isNot(AsmToken::String)) {
1507 EatToEndOfLine();
1508 return false;
1509 }
1510
1511 StringRef Filename = getTok().getString();
1512 // Get rid of the enclosing quotes.
1513 Filename = Filename.substr(1, Filename.size()-2);
1514
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001515 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1516 CppHashLoc = L;
1517 CppHashFilename = Filename;
1518 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001519 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001520
1521 // Ignore any trailing characters, they're just comment.
1522 EatToEndOfLine();
1523 return false;
1524}
1525
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001526/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001527/// for the Filename and LineNo if any in the diagnostic.
1528void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1529 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1530 raw_ostream &OS = errs();
1531
1532 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1533 const SMLoc &DiagLoc = Diag.getLoc();
1534 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1535 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1536
1537 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1538 // before printing the message.
1539 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001540 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001541 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1542 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1543 }
1544
Eric Christopher2318ba12012-12-18 00:30:54 +00001545 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001546 // manager changed or buffer changed (like in a nested include) then just
1547 // print the normal diagnostic using its Filename and LineNo.
1548 if (!Parser->CppHashLineNumber ||
1549 &DiagSrcMgr != &Parser->SrcMgr ||
1550 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001551 if (Parser->SavedDiagHandler)
1552 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1553 else
1554 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001555 return;
1556 }
1557
Eric Christopher2318ba12012-12-18 00:30:54 +00001558 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001559 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1560 // the diagnostic.
1561 const std::string Filename = Parser->CppHashFilename;
1562
1563 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1564 int CppHashLocLineNo =
1565 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1566 int LineNo = Parser->CppHashLineNumber - 1 +
1567 (DiagLocLineNo - CppHashLocLineNo);
1568
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001569 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1570 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001571 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001572 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001573
Benjamin Kramer04a04262011-10-16 10:48:29 +00001574 if (Parser->SavedDiagHandler)
1575 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1576 else
1577 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001578}
1579
Rafael Espindola799aacf2012-08-21 18:29:30 +00001580// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1581// difference being that that function accepts '@' as part of identifiers and
1582// we can't do that. AsmLexer.cpp should probably be changed to handle
1583// '@' as a special case when needed.
1584static bool isIdentifierChar(char c) {
1585 return isalnum(c) || c == '_' || c == '$' || c == '.';
1586}
1587
Rafael Espindola761cb062012-06-03 23:57:14 +00001588bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001589 const MCAsmMacroParameters &Parameters,
1590 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001591 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001592 unsigned NParameters = Parameters.size();
1593 if (NParameters != 0 && NParameters != A.size())
1594 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001595
Preston Gurd7b6f2032012-09-19 20:36:12 +00001596 // A macro without parameters is handled differently on Darwin:
1597 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001598 while (!Body.empty()) {
1599 // Scan for the next substitution.
1600 std::size_t End = Body.size(), Pos = 0;
1601 for (; Pos != End; ++Pos) {
1602 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001603 if (!NParameters) {
1604 // This macro has no parameters, look for $0, $1, etc.
1605 if (Body[Pos] != '$' || Pos + 1 == End)
1606 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001607
Rafael Espindola65366442011-06-05 02:43:45 +00001608 char Next = Body[Pos + 1];
1609 if (Next == '$' || Next == 'n' || isdigit(Next))
1610 break;
1611 } else {
1612 // This macro has parameters, look for \foo, \bar, etc.
1613 if (Body[Pos] == '\\' && Pos + 1 != End)
1614 break;
1615 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001616 }
1617
1618 // Add the prefix.
1619 OS << Body.slice(0, Pos);
1620
1621 // Check if we reached the end.
1622 if (Pos == End)
1623 break;
1624
Rafael Espindola65366442011-06-05 02:43:45 +00001625 if (!NParameters) {
1626 switch (Body[Pos+1]) {
1627 // $$ => $
1628 case '$':
1629 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001630 break;
1631
Rafael Espindola65366442011-06-05 02:43:45 +00001632 // $n => number of arguments
1633 case 'n':
1634 OS << A.size();
1635 break;
1636
1637 // $[0-9] => argument
1638 default: {
1639 // Missing arguments are ignored.
1640 unsigned Index = Body[Pos+1] - '0';
1641 if (Index >= A.size())
1642 break;
1643
1644 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001645 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001646 ie = A[Index].end(); it != ie; ++it)
1647 OS << it->getString();
1648 break;
1649 }
1650 }
1651 Pos += 2;
1652 } else {
1653 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001654 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001655 ++I;
1656
1657 const char *Begin = Body.data() + Pos +1;
1658 StringRef Argument(Begin, I - (Pos +1));
1659 unsigned Index = 0;
1660 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001661 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001662 break;
1663
Preston Gurd7b6f2032012-09-19 20:36:12 +00001664 if (Index == NParameters) {
1665 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1666 Pos += 3;
1667 else {
1668 OS << '\\' << Argument;
1669 Pos = I;
1670 }
1671 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001672 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001673 ie = A[Index].end(); it != ie; ++it)
1674 if (it->getKind() == AsmToken::String)
1675 OS << it->getStringContents();
1676 else
1677 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001678
Preston Gurd7b6f2032012-09-19 20:36:12 +00001679 Pos += 1 + Argument.size();
1680 }
Rafael Espindola65366442011-06-05 02:43:45 +00001681 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001682 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001683 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001684 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001685
Rafael Espindola65366442011-06-05 02:43:45 +00001686 return false;
1687}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001688
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001689MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001690 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001691 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001692 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1693 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001694{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001695}
1696
Preston Gurd7b6f2032012-09-19 20:36:12 +00001697static bool IsOperator(AsmToken::TokenKind kind)
1698{
1699 switch (kind)
1700 {
1701 default:
1702 return false;
1703 case AsmToken::Plus:
1704 case AsmToken::Minus:
1705 case AsmToken::Tilde:
1706 case AsmToken::Slash:
1707 case AsmToken::Star:
1708 case AsmToken::Dot:
1709 case AsmToken::Equal:
1710 case AsmToken::EqualEqual:
1711 case AsmToken::Pipe:
1712 case AsmToken::PipePipe:
1713 case AsmToken::Caret:
1714 case AsmToken::Amp:
1715 case AsmToken::AmpAmp:
1716 case AsmToken::Exclaim:
1717 case AsmToken::ExclaimEqual:
1718 case AsmToken::Percent:
1719 case AsmToken::Less:
1720 case AsmToken::LessEqual:
1721 case AsmToken::LessLess:
1722 case AsmToken::LessGreater:
1723 case AsmToken::Greater:
1724 case AsmToken::GreaterEqual:
1725 case AsmToken::GreaterGreater:
1726 return true;
1727 }
1728}
1729
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001730bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001731 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001732 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001733 unsigned AddTokens = 0;
1734
1735 // gas accepts arguments separated by whitespace, except on Darwin
1736 if (!IsDarwin)
1737 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001738
1739 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001740 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1741 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001742 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001743 }
1744
1745 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1746 // Spaces and commas cannot be mixed to delimit parameters
1747 if (ArgumentDelimiter == AsmToken::Eof)
1748 ArgumentDelimiter = AsmToken::Comma;
1749 else if (ArgumentDelimiter != AsmToken::Comma) {
1750 Lexer.setSkipSpace(true);
1751 return TokError("expected ' ' for macro argument separator");
1752 }
1753 break;
1754 }
1755
1756 if (Lexer.is(AsmToken::Space)) {
1757 Lex(); // Eat spaces
1758
1759 // Spaces can delimit parameters, but could also be part an expression.
1760 // If the token after a space is an operator, add the token and the next
1761 // one into this argument
1762 if (ArgumentDelimiter == AsmToken::Space ||
1763 ArgumentDelimiter == AsmToken::Eof) {
1764 if (IsOperator(Lexer.getKind())) {
1765 // Check to see whether the token is used as an operator,
1766 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001767 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001768 if (*NextChar == ' ')
1769 AddTokens = 2;
1770 }
1771
1772 if (!AddTokens && ParenLevel == 0) {
1773 if (ArgumentDelimiter == AsmToken::Eof &&
1774 !IsOperator(Lexer.getKind()))
1775 ArgumentDelimiter = AsmToken::Space;
1776 break;
1777 }
1778 }
1779 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001780
1781 // HandleMacroEntry relies on not advancing the lexer here
1782 // to be able to fill in the remaining default parameter values
1783 if (Lexer.is(AsmToken::EndOfStatement))
1784 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001785
1786 // Adjust the current parentheses level.
1787 if (Lexer.is(AsmToken::LParen))
1788 ++ParenLevel;
1789 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1790 --ParenLevel;
1791
1792 // Append the token to the current argument list.
1793 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001794 if (AddTokens)
1795 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001796 Lex();
1797 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001798
1799 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001800 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001801 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001802 return false;
1803}
1804
1805// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001806bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001807 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001808 // Argument delimiter is initially unknown. It will be set by
1809 // ParseMacroArgument()
1810 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001811
1812 // Parse two kinds of macro invocations:
1813 // - macros defined without any parameters accept an arbitrary number of them
1814 // - macros defined with parameters accept at most that many of them
1815 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1816 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001817 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001818
Preston Gurd7b6f2032012-09-19 20:36:12 +00001819 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001820 return true;
1821
Preston Gurd6c9176a2012-09-19 20:29:04 +00001822 if (!MA.empty() || !NParameters)
1823 A.push_back(MA);
1824 else if (NParameters) {
1825 if (!M->Parameters[Parameter].second.empty())
1826 A.push_back(M->Parameters[Parameter].second);
1827 }
Jim Grosbach97146442012-07-30 22:44:17 +00001828
Preston Gurd6c9176a2012-09-19 20:29:04 +00001829 // At the end of the statement, fill in remaining arguments that have
1830 // default values. If there aren't any, then the next argument is
1831 // required but missing
1832 if (Lexer.is(AsmToken::EndOfStatement)) {
1833 if (NParameters && Parameter < NParameters - 1) {
1834 if (M->Parameters[Parameter + 1].second.empty())
1835 return TokError("macro argument '" +
1836 Twine(M->Parameters[Parameter + 1].first) +
1837 "' is missing");
1838 else
1839 continue;
1840 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001841 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001842 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001843
1844 if (Lexer.is(AsmToken::Comma))
1845 Lex();
1846 }
1847 return TokError("Too many arguments");
1848}
1849
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001850const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1851 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1852 return (I == MacroMap.end()) ? NULL : I->getValue();
1853}
1854
1855void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1856 MacroMap[Name] = new MCAsmMacro(Macro);
1857}
1858
1859void AsmParser::UndefineMacro(StringRef Name) {
1860 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1861 if (I != MacroMap.end()) {
1862 delete I->getValue();
1863 MacroMap.erase(I);
1864 }
1865}
1866
1867bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001868 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1869 // this, although we should protect against infinite loops.
1870 if (ActiveMacros.size() == 20)
1871 return TokError("macros cannot be nested more than 20 levels deep");
1872
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001873 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001874 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001875 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001876
Jim Grosbach97146442012-07-30 22:44:17 +00001877 // Remove any trailing empty arguments. Do this after-the-fact as we have
1878 // to keep empty arguments in the middle of the list or positionality
1879 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001880 while (!A.empty() && A.back().empty())
1881 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001882
Rafael Espindola65366442011-06-05 02:43:45 +00001883 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1884 // to hold the macro body with substitutions.
1885 SmallString<256> Buf;
1886 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001887 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001888
Rafael Espindola8a403d32012-08-08 14:51:03 +00001889 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001890 return true;
1891
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001892 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001893 // instantiation.
1894 OS << ".endmacro\n";
1895
Rafael Espindola65366442011-06-05 02:43:45 +00001896 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001897 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001898
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001899 // Create the macro instantiation object and add to the current macro
1900 // instantiation stack.
1901 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001902 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001903 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001904 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001905 ActiveMacros.push_back(MI);
1906
1907 // Jump to the macro instantiation and prime the lexer.
1908 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1909 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1910 Lex();
1911
1912 return false;
1913}
1914
1915void AsmParser::HandleMacroExit() {
1916 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001917 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001918 Lex();
1919
1920 // Pop the instantiation entry.
1921 delete ActiveMacros.back();
1922 ActiveMacros.pop_back();
1923}
1924
Rafael Espindolae71cc862012-01-28 05:57:00 +00001925static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001926 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001927 case MCExpr::Binary: {
1928 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1929 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001930 break;
1931 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001932 case MCExpr::Target:
1933 case MCExpr::Constant:
1934 return false;
1935 case MCExpr::SymbolRef: {
1936 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001937 if (S.isVariable())
1938 return IsUsedIn(Sym, S.getVariableValue());
1939 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001940 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001941 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001942 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001943 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001944
1945 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001946}
1947
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001948bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1949 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001950 // FIXME: Use better location, we should use proper tokens.
1951 SMLoc EqualLoc = Lexer.getLoc();
1952
Daniel Dunbar821e3332009-08-31 08:09:28 +00001953 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001954 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001955 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001956
Rafael Espindolae71cc862012-01-28 05:57:00 +00001957 // Note: we don't count b as used in "a = b". This is to allow
1958 // a = b
1959 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001960
Daniel Dunbar3f872332009-07-28 16:08:33 +00001961 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001962 return TokError("unexpected token in assignment");
1963
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001964 // Error on assignment to '.'.
1965 if (Name == ".") {
1966 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1967 "(use '.space' or '.org').)"));
1968 }
1969
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001970 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001971 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001972
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001973 // Validate that the LHS is allowed to be a variable (either it has not been
1974 // used as a symbol, or it is an absolute symbol).
1975 MCSymbol *Sym = getContext().LookupSymbol(Name);
1976 if (Sym) {
1977 // Diagnose assignment to a label.
1978 //
1979 // FIXME: Diagnostics. Note the location of the definition as a label.
1980 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001981 if (IsUsedIn(Sym, Value))
1982 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1983 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001984 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001985 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1986 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001987 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001988 return Error(EqualLoc, "redefinition of '" + Name + "'");
1989 else if (!Sym->isVariable())
1990 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001991 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001992 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1993 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001994
1995 // Don't count these checks as uses.
1996 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001997 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001998 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001999
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002000 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002001
2002 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002003 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002004 if (NoDeadStrip)
2005 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2006
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002007
2008 return false;
2009}
2010
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002011/// ParseIdentifier:
2012/// ::= identifier
2013/// ::= string
2014bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002015 // The assembler has relaxed rules for accepting identifiers, in particular we
2016 // allow things like '.globl $foo', which would normally be separate
2017 // tokens. At this level, we have already lexed so we cannot (currently)
2018 // handle this as a context dependent token, instead we detect adjacent tokens
2019 // and return the combined identifier.
2020 if (Lexer.is(AsmToken::Dollar)) {
2021 SMLoc DollarLoc = getLexer().getLoc();
2022
2023 // Consume the dollar sign, and check for a following identifier.
2024 Lex();
2025 if (Lexer.isNot(AsmToken::Identifier))
2026 return true;
2027
2028 // We have a '$' followed by an identifier, make sure they are adjacent.
2029 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2030 return true;
2031
2032 // Construct the joined identifier and consume the token.
2033 Res = StringRef(DollarLoc.getPointer(),
2034 getTok().getIdentifier().size() + 1);
2035 Lex();
2036 return false;
2037 }
2038
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002039 if (Lexer.isNot(AsmToken::Identifier) &&
2040 Lexer.isNot(AsmToken::String))
2041 return true;
2042
Sean Callanan18b83232010-01-19 21:44:56 +00002043 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002044
Sean Callanan79ed1a82010-01-19 20:22:31 +00002045 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002046
2047 return false;
2048}
2049
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002050/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002051/// ::= .equ identifier ',' expression
2052/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002053/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002054bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002055 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002056
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002057 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002058 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002059
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002060 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002061 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002062 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002063
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002064 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002065}
2066
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002067bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002068 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002069
2070 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002071 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002072 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2073 if (Str[i] != '\\') {
2074 Data += Str[i];
2075 continue;
2076 }
2077
2078 // Recognize escaped characters. Note that this escape semantics currently
2079 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2080 ++i;
2081 if (i == e)
2082 return TokError("unexpected backslash at end of string");
2083
2084 // Recognize octal sequences.
2085 if ((unsigned) (Str[i] - '0') <= 7) {
2086 // Consume up to three octal characters.
2087 unsigned Value = Str[i] - '0';
2088
2089 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2090 ++i;
2091 Value = Value * 8 + (Str[i] - '0');
2092
2093 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2094 ++i;
2095 Value = Value * 8 + (Str[i] - '0');
2096 }
2097 }
2098
2099 if (Value > 255)
2100 return TokError("invalid octal escape sequence (out of range)");
2101
2102 Data += (unsigned char) Value;
2103 continue;
2104 }
2105
2106 // Otherwise recognize individual escapes.
2107 switch (Str[i]) {
2108 default:
2109 // Just reject invalid escape sequences for now.
2110 return TokError("invalid escape sequence (unrecognized character)");
2111
2112 case 'b': Data += '\b'; break;
2113 case 'f': Data += '\f'; break;
2114 case 'n': Data += '\n'; break;
2115 case 'r': Data += '\r'; break;
2116 case 't': Data += '\t'; break;
2117 case '"': Data += '"'; break;
2118 case '\\': Data += '\\'; break;
2119 }
2120 }
2121
2122 return false;
2123}
2124
Daniel Dunbara0d14262009-06-24 23:30:00 +00002125/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002126/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2127bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002128 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002129 CheckForValidSection();
2130
Daniel Dunbara0d14262009-06-24 23:30:00 +00002131 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002132 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002133 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002134
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002135 std::string Data;
2136 if (ParseEscapedString(Data))
2137 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002138
2139 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002140 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002141 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2142
Sean Callanan79ed1a82010-01-19 20:22:31 +00002143 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002144
2145 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002146 break;
2147
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002148 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002149 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002150 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002151 }
2152 }
2153
Sean Callanan79ed1a82010-01-19 20:22:31 +00002154 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002155 return false;
2156}
2157
2158/// ParseDirectiveValue
2159/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2160bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002161 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002162 CheckForValidSection();
2163
Daniel Dunbara0d14262009-06-24 23:30:00 +00002164 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002165 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002166 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002167 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002168 return true;
2169
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002170 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002171 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2172 assert(Size <= 8 && "Invalid size");
2173 uint64_t IntValue = MCE->getValue();
2174 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2175 return Error(ExprLoc, "literal value out of range for directive");
2176 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2177 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002178 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002179
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002180 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002181 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002182
Daniel Dunbara0d14262009-06-24 23:30:00 +00002183 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002184 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002185 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002186 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002187 }
2188 }
2189
Sean Callanan79ed1a82010-01-19 20:22:31 +00002190 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002191 return false;
2192}
2193
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002194/// ParseDirectiveRealValue
2195/// ::= (.single | .double) [ expression (, expression)* ]
2196bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2197 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2198 CheckForValidSection();
2199
2200 for (;;) {
2201 // We don't truly support arithmetic on floating point expressions, so we
2202 // have to manually parse unary prefixes.
2203 bool IsNeg = false;
2204 if (getLexer().is(AsmToken::Minus)) {
2205 Lex();
2206 IsNeg = true;
2207 } else if (getLexer().is(AsmToken::Plus))
2208 Lex();
2209
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002210 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002211 getLexer().isNot(AsmToken::Real) &&
2212 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002213 return TokError("unexpected token in directive");
2214
2215 // Convert to an APFloat.
2216 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002217 StringRef IDVal = getTok().getString();
2218 if (getLexer().is(AsmToken::Identifier)) {
2219 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2220 Value = APFloat::getInf(Semantics);
2221 else if (!IDVal.compare_lower("nan"))
2222 Value = APFloat::getNaN(Semantics, false, ~0);
2223 else
2224 return TokError("invalid floating point literal");
2225 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002226 APFloat::opInvalidOp)
2227 return TokError("invalid floating point literal");
2228 if (IsNeg)
2229 Value.changeSign();
2230
2231 // Consume the numeric token.
2232 Lex();
2233
2234 // Emit the value as an integer.
2235 APInt AsInt = Value.bitcastToAPInt();
2236 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2237 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2238
2239 if (getLexer().is(AsmToken::EndOfStatement))
2240 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002241
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002242 if (getLexer().isNot(AsmToken::Comma))
2243 return TokError("unexpected token in directive");
2244 Lex();
2245 }
2246 }
2247
2248 Lex();
2249 return false;
2250}
2251
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002252/// ParseDirectiveZero
2253/// ::= .zero expression
2254bool AsmParser::ParseDirectiveZero() {
2255 CheckForValidSection();
2256
2257 int64_t NumBytes;
2258 if (ParseAbsoluteExpression(NumBytes))
2259 return true;
2260
Rafael Espindolae452b172010-10-05 19:42:57 +00002261 int64_t Val = 0;
2262 if (getLexer().is(AsmToken::Comma)) {
2263 Lex();
2264 if (ParseAbsoluteExpression(Val))
2265 return true;
2266 }
2267
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002268 if (getLexer().isNot(AsmToken::EndOfStatement))
2269 return TokError("unexpected token in '.zero' directive");
2270
2271 Lex();
2272
Rafael Espindolae452b172010-10-05 19:42:57 +00002273 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002274
2275 return false;
2276}
2277
Daniel Dunbara0d14262009-06-24 23:30:00 +00002278/// ParseDirectiveFill
2279/// ::= .fill expression , expression , expression
2280bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002281 CheckForValidSection();
2282
Daniel Dunbara0d14262009-06-24 23:30:00 +00002283 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002284 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002285 return true;
2286
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002287 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002288 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002289 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002290
Daniel Dunbara0d14262009-06-24 23:30:00 +00002291 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002292 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002293 return true;
2294
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002295 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002296 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002297 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002298
Daniel Dunbara0d14262009-06-24 23:30:00 +00002299 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002300 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002301 return true;
2302
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002303 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002304 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002305
Sean Callanan79ed1a82010-01-19 20:22:31 +00002306 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002307
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002308 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2309 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002310
2311 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002312 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002313
2314 return false;
2315}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002316
2317/// ParseDirectiveOrg
2318/// ::= .org expression [ , expression ]
2319bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002320 CheckForValidSection();
2321
Daniel Dunbar821e3332009-08-31 08:09:28 +00002322 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002323 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002324 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002325 return true;
2326
2327 // Parse optional fill expression.
2328 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002329 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2330 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002331 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002332 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002333
Daniel Dunbar475839e2009-06-29 20:37:27 +00002334 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002335 return true;
2336
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002337 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002338 return TokError("unexpected token in '.org' directive");
2339 }
2340
Sean Callanan79ed1a82010-01-19 20:22:31 +00002341 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002342
Jim Grosbachebd4c052012-01-27 00:37:08 +00002343 // Only limited forms of relocatable expressions are accepted here, it
2344 // has to be relative to the current section. The streamer will return
2345 // 'true' if the expression wasn't evaluatable.
2346 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2347 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002348
2349 return false;
2350}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002351
2352/// ParseDirectiveAlign
2353/// ::= {.align, ...} expression [ , expression [ , expression ]]
2354bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002355 CheckForValidSection();
2356
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002357 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002358 int64_t Alignment;
2359 if (ParseAbsoluteExpression(Alignment))
2360 return true;
2361
2362 SMLoc MaxBytesLoc;
2363 bool HasFillExpr = false;
2364 int64_t FillExpr = 0;
2365 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002366 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2367 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002368 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002369 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002370
2371 // The fill expression can be omitted while specifying a maximum number of
2372 // alignment bytes, e.g:
2373 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002374 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002375 HasFillExpr = true;
2376 if (ParseAbsoluteExpression(FillExpr))
2377 return true;
2378 }
2379
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2381 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002382 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002383 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002384
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002385 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002386 if (ParseAbsoluteExpression(MaxBytesToFill))
2387 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002388
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002389 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002390 return TokError("unexpected token in directive");
2391 }
2392 }
2393
Sean Callanan79ed1a82010-01-19 20:22:31 +00002394 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002395
Daniel Dunbar648ac512010-05-17 21:54:30 +00002396 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002397 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002398
2399 // Compute alignment in bytes.
2400 if (IsPow2) {
2401 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002402 if (Alignment >= 32) {
2403 Error(AlignmentLoc, "invalid alignment value");
2404 Alignment = 31;
2405 }
2406
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002407 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002408 }
2409
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002410 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002411 if (MaxBytesLoc.isValid()) {
2412 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002413 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2414 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002415 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002416 }
2417
2418 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002419 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2420 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002421 MaxBytesToFill = 0;
2422 }
2423 }
2424
Daniel Dunbar648ac512010-05-17 21:54:30 +00002425 // Check whether we should use optimal code alignment for this .align
2426 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002427 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002428 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2429 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002430 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002431 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002432 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002433 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2434 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002435 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002436
2437 return false;
2438}
2439
Eli Bendersky6ee13082013-01-15 22:59:42 +00002440/// ParseDirectiveFile
2441/// ::= .file [number] filename
2442/// ::= .file number directory filename
2443bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2444 // FIXME: I'm not sure what this is.
2445 int64_t FileNumber = -1;
2446 SMLoc FileNumberLoc = getLexer().getLoc();
2447 if (getLexer().is(AsmToken::Integer)) {
2448 FileNumber = getTok().getIntVal();
2449 Lex();
2450
2451 if (FileNumber < 1)
2452 return TokError("file number less than one");
2453 }
2454
2455 if (getLexer().isNot(AsmToken::String))
2456 return TokError("unexpected token in '.file' directive");
2457
2458 // Usually the directory and filename together, otherwise just the directory.
2459 StringRef Path = getTok().getString();
2460 Path = Path.substr(1, Path.size()-2);
2461 Lex();
2462
2463 StringRef Directory;
2464 StringRef Filename;
2465 if (getLexer().is(AsmToken::String)) {
2466 if (FileNumber == -1)
2467 return TokError("explicit path specified, but no file number");
2468 Filename = getTok().getString();
2469 Filename = Filename.substr(1, Filename.size()-2);
2470 Directory = Path;
2471 Lex();
2472 } else {
2473 Filename = Path;
2474 }
2475
2476 if (getLexer().isNot(AsmToken::EndOfStatement))
2477 return TokError("unexpected token in '.file' directive");
2478
2479 if (FileNumber == -1)
2480 getStreamer().EmitFileDirective(Filename);
2481 else {
2482 if (getContext().getGenDwarfForAssembly() == true)
2483 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2484 "used to generate dwarf debug info for assembly code");
2485
2486 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2487 Error(FileNumberLoc, "file number already allocated");
2488 }
2489
2490 return false;
2491}
2492
2493/// ParseDirectiveLine
2494/// ::= .line [number]
2495bool AsmParser::ParseDirectiveLine() {
2496 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2497 if (getLexer().isNot(AsmToken::Integer))
2498 return TokError("unexpected token in '.line' directive");
2499
2500 int64_t LineNumber = getTok().getIntVal();
2501 (void) LineNumber;
2502 Lex();
2503
2504 // FIXME: Do something with the .line.
2505 }
2506
2507 if (getLexer().isNot(AsmToken::EndOfStatement))
2508 return TokError("unexpected token in '.line' directive");
2509
2510 return false;
2511}
2512
2513/// ParseDirectiveLoc
2514/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2515/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2516/// The first number is a file number, must have been previously assigned with
2517/// a .file directive, the second number is the line number and optionally the
2518/// third number is a column position (zero if not specified). The remaining
2519/// optional items are .loc sub-directives.
2520bool AsmParser::ParseDirectiveLoc() {
2521 if (getLexer().isNot(AsmToken::Integer))
2522 return TokError("unexpected token in '.loc' directive");
2523 int64_t FileNumber = getTok().getIntVal();
2524 if (FileNumber < 1)
2525 return TokError("file number less than one in '.loc' directive");
2526 if (!getContext().isValidDwarfFileNumber(FileNumber))
2527 return TokError("unassigned file number in '.loc' directive");
2528 Lex();
2529
2530 int64_t LineNumber = 0;
2531 if (getLexer().is(AsmToken::Integer)) {
2532 LineNumber = getTok().getIntVal();
2533 if (LineNumber < 1)
2534 return TokError("line number less than one in '.loc' directive");
2535 Lex();
2536 }
2537
2538 int64_t ColumnPos = 0;
2539 if (getLexer().is(AsmToken::Integer)) {
2540 ColumnPos = getTok().getIntVal();
2541 if (ColumnPos < 0)
2542 return TokError("column position less than zero in '.loc' directive");
2543 Lex();
2544 }
2545
2546 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2547 unsigned Isa = 0;
2548 int64_t Discriminator = 0;
2549 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2550 for (;;) {
2551 if (getLexer().is(AsmToken::EndOfStatement))
2552 break;
2553
2554 StringRef Name;
2555 SMLoc Loc = getTok().getLoc();
2556 if (ParseIdentifier(Name))
2557 return TokError("unexpected token in '.loc' directive");
2558
2559 if (Name == "basic_block")
2560 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2561 else if (Name == "prologue_end")
2562 Flags |= DWARF2_FLAG_PROLOGUE_END;
2563 else if (Name == "epilogue_begin")
2564 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2565 else if (Name == "is_stmt") {
2566 Loc = getTok().getLoc();
2567 const MCExpr *Value;
2568 if (ParseExpression(Value))
2569 return true;
2570 // The expression must be the constant 0 or 1.
2571 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2572 int Value = MCE->getValue();
2573 if (Value == 0)
2574 Flags &= ~DWARF2_FLAG_IS_STMT;
2575 else if (Value == 1)
2576 Flags |= DWARF2_FLAG_IS_STMT;
2577 else
2578 return Error(Loc, "is_stmt value not 0 or 1");
2579 }
2580 else {
2581 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2582 }
2583 }
2584 else if (Name == "isa") {
2585 Loc = getTok().getLoc();
2586 const MCExpr *Value;
2587 if (ParseExpression(Value))
2588 return true;
2589 // The expression must be a constant greater or equal to 0.
2590 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2591 int Value = MCE->getValue();
2592 if (Value < 0)
2593 return Error(Loc, "isa number less than zero");
2594 Isa = Value;
2595 }
2596 else {
2597 return Error(Loc, "isa number not a constant value");
2598 }
2599 }
2600 else if (Name == "discriminator") {
2601 if (ParseAbsoluteExpression(Discriminator))
2602 return true;
2603 }
2604 else {
2605 return Error(Loc, "unknown sub-directive in '.loc' directive");
2606 }
2607
2608 if (getLexer().is(AsmToken::EndOfStatement))
2609 break;
2610 }
2611 }
2612
2613 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2614 Isa, Discriminator, StringRef());
2615
2616 return false;
2617}
2618
2619/// ParseDirectiveStabs
2620/// ::= .stabs string, number, number, number
2621bool AsmParser::ParseDirectiveStabs() {
2622 return TokError("unsupported directive '.stabs'");
2623}
2624
2625/// ParseDirectiveCFISections
2626/// ::= .cfi_sections section [, section]
2627bool AsmParser::ParseDirectiveCFISections() {
2628 StringRef Name;
2629 bool EH = false;
2630 bool Debug = false;
2631
2632 if (ParseIdentifier(Name))
2633 return TokError("Expected an identifier");
2634
2635 if (Name == ".eh_frame")
2636 EH = true;
2637 else if (Name == ".debug_frame")
2638 Debug = true;
2639
2640 if (getLexer().is(AsmToken::Comma)) {
2641 Lex();
2642
2643 if (ParseIdentifier(Name))
2644 return TokError("Expected an identifier");
2645
2646 if (Name == ".eh_frame")
2647 EH = true;
2648 else if (Name == ".debug_frame")
2649 Debug = true;
2650 }
2651
2652 getStreamer().EmitCFISections(EH, Debug);
2653 return false;
2654}
2655
2656/// ParseDirectiveCFIStartProc
2657/// ::= .cfi_startproc
2658bool AsmParser::ParseDirectiveCFIStartProc() {
2659 getStreamer().EmitCFIStartProc();
2660 return false;
2661}
2662
2663/// ParseDirectiveCFIEndProc
2664/// ::= .cfi_endproc
2665bool AsmParser::ParseDirectiveCFIEndProc() {
2666 getStreamer().EmitCFIEndProc();
2667 return false;
2668}
2669
2670/// ParseRegisterOrRegisterNumber - parse register name or number.
2671bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2672 SMLoc DirectiveLoc) {
2673 unsigned RegNo;
2674
2675 if (getLexer().isNot(AsmToken::Integer)) {
2676 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2677 return true;
2678 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2679 } else
2680 return ParseAbsoluteExpression(Register);
2681
2682 return false;
2683}
2684
2685/// ParseDirectiveCFIDefCfa
2686/// ::= .cfi_def_cfa register, offset
2687bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2688 int64_t Register = 0;
2689 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2690 return true;
2691
2692 if (getLexer().isNot(AsmToken::Comma))
2693 return TokError("unexpected token in directive");
2694 Lex();
2695
2696 int64_t Offset = 0;
2697 if (ParseAbsoluteExpression(Offset))
2698 return true;
2699
2700 getStreamer().EmitCFIDefCfa(Register, Offset);
2701 return false;
2702}
2703
2704/// ParseDirectiveCFIDefCfaOffset
2705/// ::= .cfi_def_cfa_offset offset
2706bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2707 int64_t Offset = 0;
2708 if (ParseAbsoluteExpression(Offset))
2709 return true;
2710
2711 getStreamer().EmitCFIDefCfaOffset(Offset);
2712 return false;
2713}
2714
2715/// ParseDirectiveCFIRegister
2716/// ::= .cfi_register register, register
2717bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2718 int64_t Register1 = 0;
2719 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2720 return true;
2721
2722 if (getLexer().isNot(AsmToken::Comma))
2723 return TokError("unexpected token in directive");
2724 Lex();
2725
2726 int64_t Register2 = 0;
2727 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2728 return true;
2729
2730 getStreamer().EmitCFIRegister(Register1, Register2);
2731 return false;
2732}
2733
2734/// ParseDirectiveCFIAdjustCfaOffset
2735/// ::= .cfi_adjust_cfa_offset adjustment
2736bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2737 int64_t Adjustment = 0;
2738 if (ParseAbsoluteExpression(Adjustment))
2739 return true;
2740
2741 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2742 return false;
2743}
2744
2745/// ParseDirectiveCFIDefCfaRegister
2746/// ::= .cfi_def_cfa_register register
2747bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2748 int64_t Register = 0;
2749 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2750 return true;
2751
2752 getStreamer().EmitCFIDefCfaRegister(Register);
2753 return false;
2754}
2755
2756/// ParseDirectiveCFIOffset
2757/// ::= .cfi_offset register, offset
2758bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2759 int64_t Register = 0;
2760 int64_t Offset = 0;
2761
2762 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2763 return true;
2764
2765 if (getLexer().isNot(AsmToken::Comma))
2766 return TokError("unexpected token in directive");
2767 Lex();
2768
2769 if (ParseAbsoluteExpression(Offset))
2770 return true;
2771
2772 getStreamer().EmitCFIOffset(Register, Offset);
2773 return false;
2774}
2775
2776/// ParseDirectiveCFIRelOffset
2777/// ::= .cfi_rel_offset register, offset
2778bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2779 int64_t Register = 0;
2780
2781 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2782 return true;
2783
2784 if (getLexer().isNot(AsmToken::Comma))
2785 return TokError("unexpected token in directive");
2786 Lex();
2787
2788 int64_t Offset = 0;
2789 if (ParseAbsoluteExpression(Offset))
2790 return true;
2791
2792 getStreamer().EmitCFIRelOffset(Register, Offset);
2793 return false;
2794}
2795
2796static bool isValidEncoding(int64_t Encoding) {
2797 if (Encoding & ~0xff)
2798 return false;
2799
2800 if (Encoding == dwarf::DW_EH_PE_omit)
2801 return true;
2802
2803 const unsigned Format = Encoding & 0xf;
2804 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2805 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2806 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2807 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2808 return false;
2809
2810 const unsigned Application = Encoding & 0x70;
2811 if (Application != dwarf::DW_EH_PE_absptr &&
2812 Application != dwarf::DW_EH_PE_pcrel)
2813 return false;
2814
2815 return true;
2816}
2817
2818/// ParseDirectiveCFIPersonalityOrLsda
2819/// IsPersonality true for cfi_personality, false for cfi_lsda
2820/// ::= .cfi_personality encoding, [symbol_name]
2821/// ::= .cfi_lsda encoding, [symbol_name]
2822bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2823 int64_t Encoding = 0;
2824 if (ParseAbsoluteExpression(Encoding))
2825 return true;
2826 if (Encoding == dwarf::DW_EH_PE_omit)
2827 return false;
2828
2829 if (!isValidEncoding(Encoding))
2830 return TokError("unsupported encoding.");
2831
2832 if (getLexer().isNot(AsmToken::Comma))
2833 return TokError("unexpected token in directive");
2834 Lex();
2835
2836 StringRef Name;
2837 if (ParseIdentifier(Name))
2838 return TokError("expected identifier in directive");
2839
2840 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2841
2842 if (IsPersonality)
2843 getStreamer().EmitCFIPersonality(Sym, Encoding);
2844 else
2845 getStreamer().EmitCFILsda(Sym, Encoding);
2846 return false;
2847}
2848
2849/// ParseDirectiveCFIRememberState
2850/// ::= .cfi_remember_state
2851bool AsmParser::ParseDirectiveCFIRememberState() {
2852 getStreamer().EmitCFIRememberState();
2853 return false;
2854}
2855
2856/// ParseDirectiveCFIRestoreState
2857/// ::= .cfi_remember_state
2858bool AsmParser::ParseDirectiveCFIRestoreState() {
2859 getStreamer().EmitCFIRestoreState();
2860 return false;
2861}
2862
2863/// ParseDirectiveCFISameValue
2864/// ::= .cfi_same_value register
2865bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2866 int64_t Register = 0;
2867
2868 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2869 return true;
2870
2871 getStreamer().EmitCFISameValue(Register);
2872 return false;
2873}
2874
2875/// ParseDirectiveCFIRestore
2876/// ::= .cfi_restore register
2877bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2878 int64_t Register = 0;
2879 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2880 return true;
2881
2882 getStreamer().EmitCFIRestore(Register);
2883 return false;
2884}
2885
2886/// ParseDirectiveCFIEscape
2887/// ::= .cfi_escape expression[,...]
2888bool AsmParser::ParseDirectiveCFIEscape() {
2889 std::string Values;
2890 int64_t CurrValue;
2891 if (ParseAbsoluteExpression(CurrValue))
2892 return true;
2893
2894 Values.push_back((uint8_t)CurrValue);
2895
2896 while (getLexer().is(AsmToken::Comma)) {
2897 Lex();
2898
2899 if (ParseAbsoluteExpression(CurrValue))
2900 return true;
2901
2902 Values.push_back((uint8_t)CurrValue);
2903 }
2904
2905 getStreamer().EmitCFIEscape(Values);
2906 return false;
2907}
2908
2909/// ParseDirectiveCFISignalFrame
2910/// ::= .cfi_signal_frame
2911bool AsmParser::ParseDirectiveCFISignalFrame() {
2912 if (getLexer().isNot(AsmToken::EndOfStatement))
2913 return Error(getLexer().getLoc(),
2914 "unexpected token in '.cfi_signal_frame'");
2915
2916 getStreamer().EmitCFISignalFrame();
2917 return false;
2918}
2919
2920/// ParseDirectiveCFIUndefined
2921/// ::= .cfi_undefined register
2922bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2923 int64_t Register = 0;
2924
2925 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2926 return true;
2927
2928 getStreamer().EmitCFIUndefined(Register);
2929 return false;
2930}
2931
2932/// ParseDirectiveMacrosOnOff
2933/// ::= .macros_on
2934/// ::= .macros_off
2935bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2936 if (getLexer().isNot(AsmToken::EndOfStatement))
2937 return Error(getLexer().getLoc(),
2938 "unexpected token in '" + Directive + "' directive");
2939
2940 SetMacrosEnabled(Directive == ".macros_on");
2941 return false;
2942}
2943
2944/// ParseDirectiveMacro
2945/// ::= .macro name [parameters]
2946bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2947 StringRef Name;
2948 if (ParseIdentifier(Name))
2949 return TokError("expected identifier in '.macro' directive");
2950
2951 MCAsmMacroParameters Parameters;
2952 // Argument delimiter is initially unknown. It will be set by
2953 // ParseMacroArgument()
2954 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
2955 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2956 for (;;) {
2957 MCAsmMacroParameter Parameter;
2958 if (ParseIdentifier(Parameter.first))
2959 return TokError("expected identifier in '.macro' directive");
2960
2961 if (getLexer().is(AsmToken::Equal)) {
2962 Lex();
2963 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
2964 return true;
2965 }
2966
2967 Parameters.push_back(Parameter);
2968
2969 if (getLexer().is(AsmToken::Comma))
2970 Lex();
2971 else if (getLexer().is(AsmToken::EndOfStatement))
2972 break;
2973 }
2974 }
2975
2976 // Eat the end of statement.
2977 Lex();
2978
2979 AsmToken EndToken, StartToken = getTok();
2980
2981 // Lex the macro definition.
2982 for (;;) {
2983 // Check whether we have reached the end of the file.
2984 if (getLexer().is(AsmToken::Eof))
2985 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2986
2987 // Otherwise, check whether we have reach the .endmacro.
2988 if (getLexer().is(AsmToken::Identifier) &&
2989 (getTok().getIdentifier() == ".endm" ||
2990 getTok().getIdentifier() == ".endmacro")) {
2991 EndToken = getTok();
2992 Lex();
2993 if (getLexer().isNot(AsmToken::EndOfStatement))
2994 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2995 "' directive");
2996 break;
2997 }
2998
2999 // Otherwise, scan til the end of the statement.
3000 EatToEndOfStatement();
3001 }
3002
3003 if (LookupMacro(Name)) {
3004 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3005 }
3006
3007 const char *BodyStart = StartToken.getLoc().getPointer();
3008 const char *BodyEnd = EndToken.getLoc().getPointer();
3009 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3010 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3011 return false;
3012}
3013
3014/// ParseDirectiveEndMacro
3015/// ::= .endm
3016/// ::= .endmacro
3017bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3018 if (getLexer().isNot(AsmToken::EndOfStatement))
3019 return TokError("unexpected token in '" + Directive + "' directive");
3020
3021 // If we are inside a macro instantiation, terminate the current
3022 // instantiation.
3023 if (InsideMacroInstantiation()) {
3024 HandleMacroExit();
3025 return false;
3026 }
3027
3028 // Otherwise, this .endmacro is a stray entry in the file; well formed
3029 // .endmacro directives are handled during the macro definition parsing.
3030 return TokError("unexpected '" + Directive + "' in file, "
3031 "no current macro definition");
3032}
3033
3034/// ParseDirectivePurgeMacro
3035/// ::= .purgem
3036bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3037 StringRef Name;
3038 if (ParseIdentifier(Name))
3039 return TokError("expected identifier in '.purgem' directive");
3040
3041 if (getLexer().isNot(AsmToken::EndOfStatement))
3042 return TokError("unexpected token in '.purgem' directive");
3043
3044 if (!LookupMacro(Name))
3045 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3046
3047 UndefineMacro(Name);
3048 return false;
3049}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003050
3051/// ParseDirectiveBundleAlignMode
3052/// ::= {.bundle_align_mode} expression
3053bool AsmParser::ParseDirectiveBundleAlignMode() {
3054 CheckForValidSection();
3055
3056 // Expect a single argument: an expression that evaluates to a constant
3057 // in the inclusive range 0-30.
3058 SMLoc ExprLoc = getLexer().getLoc();
3059 int64_t AlignSizePow2;
3060 if (ParseAbsoluteExpression(AlignSizePow2))
3061 return true;
3062 else if (getLexer().isNot(AsmToken::EndOfStatement))
3063 return TokError("unexpected token after expression in"
3064 " '.bundle_align_mode' directive");
3065 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3066 return Error(ExprLoc,
3067 "invalid bundle alignment size (expected between 0 and 30)");
3068
3069 Lex();
3070
3071 // Because of AlignSizePow2's verified range we can safely truncate it to
3072 // unsigned.
3073 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3074 return false;
3075}
3076
3077/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003078/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003079bool AsmParser::ParseDirectiveBundleLock() {
3080 CheckForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003081 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003082
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003083 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3084 StringRef Option;
3085 SMLoc Loc = getTok().getLoc();
3086 const char *kInvalidOptionError =
3087 "invalid option for '.bundle_lock' directive";
3088
3089 if (ParseIdentifier(Option))
3090 return Error(Loc, kInvalidOptionError);
3091
3092 if (Option != "align_to_end")
3093 return Error(Loc, kInvalidOptionError);
3094 else if (getLexer().isNot(AsmToken::EndOfStatement))
3095 return Error(Loc,
3096 "unexpected token after '.bundle_lock' directive option");
3097 AlignToEnd = true;
3098 }
3099
Eli Bendersky4766ef42012-12-20 19:05:53 +00003100 Lex();
3101
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003102 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003103 return false;
3104}
3105
3106/// ParseDirectiveBundleLock
3107/// ::= {.bundle_lock}
3108bool AsmParser::ParseDirectiveBundleUnlock() {
3109 CheckForValidSection();
3110
3111 if (getLexer().isNot(AsmToken::EndOfStatement))
3112 return TokError("unexpected token in '.bundle_unlock' directive");
3113 Lex();
3114
3115 getStreamer().EmitBundleUnlock();
3116 return false;
3117}
3118
Eli Bendersky6ee13082013-01-15 22:59:42 +00003119/// ParseDirectiveSpace
3120/// ::= (.skip | .space) expression [ , expression ]
3121bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3122 CheckForValidSection();
3123
3124 int64_t NumBytes;
3125 if (ParseAbsoluteExpression(NumBytes))
3126 return true;
3127
3128 int64_t FillExpr = 0;
3129 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3130 if (getLexer().isNot(AsmToken::Comma))
3131 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3132 Lex();
3133
3134 if (ParseAbsoluteExpression(FillExpr))
3135 return true;
3136
3137 if (getLexer().isNot(AsmToken::EndOfStatement))
3138 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3139 }
3140
3141 Lex();
3142
3143 if (NumBytes <= 0)
3144 return TokError("invalid number of bytes in '" +
3145 Twine(IDVal) + "' directive");
3146
3147 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3148 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3149
3150 return false;
3151}
3152
3153/// ParseDirectiveLEB128
3154/// ::= (.sleb128 | .uleb128) expression
3155bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3156 CheckForValidSection();
3157 const MCExpr *Value;
3158
3159 if (ParseExpression(Value))
3160 return true;
3161
3162 if (getLexer().isNot(AsmToken::EndOfStatement))
3163 return TokError("unexpected token in directive");
3164
3165 if (Signed)
3166 getStreamer().EmitSLEB128Value(Value);
3167 else
3168 getStreamer().EmitULEB128Value(Value);
3169
3170 return false;
3171}
3172
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003173/// ParseDirectiveSymbolAttribute
3174/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003175bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003176 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003177 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003178 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003179 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003180
3181 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003182 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003183
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003184 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003185
Jim Grosbach10ec6502011-09-15 17:56:49 +00003186 // Assembler local symbols don't make any sense here. Complain loudly.
3187 if (Sym->isTemporary())
3188 return Error(Loc, "non-local symbol required in directive");
3189
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003190 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003191
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003192 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003193 break;
3194
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003195 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003196 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003197 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003198 }
3199 }
3200
Sean Callanan79ed1a82010-01-19 20:22:31 +00003201 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003202 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003203}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003204
3205/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003206/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3207bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003208 CheckForValidSection();
3209
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003210 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003211 StringRef Name;
3212 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003213 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003214
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003215 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003216 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003217
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003218 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003219 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003220 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003221
3222 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003223 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003224 if (ParseAbsoluteExpression(Size))
3225 return true;
3226
3227 int64_t Pow2Alignment = 0;
3228 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003229 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003230 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003231 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003232 if (ParseAbsoluteExpression(Pow2Alignment))
3233 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003234
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003235 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3236 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003237 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3238
Chris Lattner258281d2010-01-19 06:22:22 +00003239 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003240 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3241 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003242 if (!isPowerOf2_64(Pow2Alignment))
3243 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3244 Pow2Alignment = Log2_64(Pow2Alignment);
3245 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003246 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003247
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003248 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003249 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003250
Sean Callanan79ed1a82010-01-19 20:22:31 +00003251 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003252
Chris Lattner1fc3d752009-07-09 17:25:12 +00003253 // NOTE: a size of zero for a .comm should create a undefined symbol
3254 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003255 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003256 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3257 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003258
Eric Christopherc260a3e2010-05-14 01:38:54 +00003259 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003260 // may internally end up wanting an alignment in bytes.
3261 // FIXME: Diagnose overflow.
3262 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003263 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3264 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003265
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003266 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003267 return Error(IDLoc, "invalid symbol redefinition");
3268
Chris Lattner1fc3d752009-07-09 17:25:12 +00003269 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003270 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003271 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003272 return false;
3273 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003274
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003275 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003276 return false;
3277}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003278
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003279/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003280/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003281bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003282 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003283 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003284
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003285 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003286 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003287 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003288
Sean Callanan79ed1a82010-01-19 20:22:31 +00003289 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003290
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003291 if (Str.empty())
3292 Error(Loc, ".abort detected. Assembly stopping.");
3293 else
3294 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003295 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003296
3297 return false;
3298}
Kevin Enderby71148242009-07-14 21:35:03 +00003299
Kevin Enderby1f049b22009-07-14 23:21:55 +00003300/// ParseDirectiveInclude
3301/// ::= .include "filename"
3302bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003303 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003304 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003305
Sean Callanan18b83232010-01-19 21:44:56 +00003306 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003307 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003308 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003309
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003310 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003311 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003312
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003313 // Strip the quotes.
3314 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003315
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003316 // Attempt to switch the lexer to the included file before consuming the end
3317 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003318 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003319 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003320 return true;
3321 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003322
3323 return false;
3324}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003325
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003326/// ParseDirectiveIncbin
3327/// ::= .incbin "filename"
3328bool AsmParser::ParseDirectiveIncbin() {
3329 if (getLexer().isNot(AsmToken::String))
3330 return TokError("expected string in '.incbin' directive");
3331
3332 std::string Filename = getTok().getString();
3333 SMLoc IncbinLoc = getLexer().getLoc();
3334 Lex();
3335
3336 if (getLexer().isNot(AsmToken::EndOfStatement))
3337 return TokError("unexpected token in '.incbin' directive");
3338
3339 // Strip the quotes.
3340 Filename = Filename.substr(1, Filename.size()-2);
3341
3342 // Attempt to process the included file.
3343 if (ProcessIncbinFile(Filename)) {
3344 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3345 return true;
3346 }
3347
3348 return false;
3349}
3350
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003351/// ParseDirectiveIf
3352/// ::= .if expression
3353bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003354 TheCondStack.push_back(TheCondState);
3355 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003356 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003357 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003358 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003359 int64_t ExprValue;
3360 if (ParseAbsoluteExpression(ExprValue))
3361 return true;
3362
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003363 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003364 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003365
Sean Callanan79ed1a82010-01-19 20:22:31 +00003366 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003367
3368 TheCondState.CondMet = ExprValue;
3369 TheCondState.Ignore = !TheCondState.CondMet;
3370 }
3371
3372 return false;
3373}
3374
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003375/// ParseDirectiveIfb
3376/// ::= .ifb string
3377bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3378 TheCondStack.push_back(TheCondState);
3379 TheCondState.TheCond = AsmCond::IfCond;
3380
Benjamin Kramer29739e72012-05-12 16:52:21 +00003381 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003382 EatToEndOfStatement();
3383 } else {
3384 StringRef Str = ParseStringToEndOfStatement();
3385
3386 if (getLexer().isNot(AsmToken::EndOfStatement))
3387 return TokError("unexpected token in '.ifb' directive");
3388
3389 Lex();
3390
3391 TheCondState.CondMet = ExpectBlank == Str.empty();
3392 TheCondState.Ignore = !TheCondState.CondMet;
3393 }
3394
3395 return false;
3396}
3397
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003398/// ParseDirectiveIfc
3399/// ::= .ifc string1, string2
3400bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3401 TheCondStack.push_back(TheCondState);
3402 TheCondState.TheCond = AsmCond::IfCond;
3403
Benjamin Kramer29739e72012-05-12 16:52:21 +00003404 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003405 EatToEndOfStatement();
3406 } else {
3407 StringRef Str1 = ParseStringToComma();
3408
3409 if (getLexer().isNot(AsmToken::Comma))
3410 return TokError("unexpected token in '.ifc' directive");
3411
3412 Lex();
3413
3414 StringRef Str2 = ParseStringToEndOfStatement();
3415
3416 if (getLexer().isNot(AsmToken::EndOfStatement))
3417 return TokError("unexpected token in '.ifc' directive");
3418
3419 Lex();
3420
3421 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3422 TheCondState.Ignore = !TheCondState.CondMet;
3423 }
3424
3425 return false;
3426}
3427
3428/// ParseDirectiveIfdef
3429/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003430bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3431 StringRef Name;
3432 TheCondStack.push_back(TheCondState);
3433 TheCondState.TheCond = AsmCond::IfCond;
3434
3435 if (TheCondState.Ignore) {
3436 EatToEndOfStatement();
3437 } else {
3438 if (ParseIdentifier(Name))
3439 return TokError("expected identifier after '.ifdef'");
3440
3441 Lex();
3442
3443 MCSymbol *Sym = getContext().LookupSymbol(Name);
3444
3445 if (expect_defined)
3446 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3447 else
3448 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3449 TheCondState.Ignore = !TheCondState.CondMet;
3450 }
3451
3452 return false;
3453}
3454
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003455/// ParseDirectiveElseIf
3456/// ::= .elseif expression
3457bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3458 if (TheCondState.TheCond != AsmCond::IfCond &&
3459 TheCondState.TheCond != AsmCond::ElseIfCond)
3460 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3461 " an .elseif");
3462 TheCondState.TheCond = AsmCond::ElseIfCond;
3463
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003464 bool LastIgnoreState = false;
3465 if (!TheCondStack.empty())
3466 LastIgnoreState = TheCondStack.back().Ignore;
3467 if (LastIgnoreState || TheCondState.CondMet) {
3468 TheCondState.Ignore = true;
3469 EatToEndOfStatement();
3470 }
3471 else {
3472 int64_t ExprValue;
3473 if (ParseAbsoluteExpression(ExprValue))
3474 return true;
3475
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003476 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003477 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003478
Sean Callanan79ed1a82010-01-19 20:22:31 +00003479 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003480 TheCondState.CondMet = ExprValue;
3481 TheCondState.Ignore = !TheCondState.CondMet;
3482 }
3483
3484 return false;
3485}
3486
3487/// ParseDirectiveElse
3488/// ::= .else
3489bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003490 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003491 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003492
Sean Callanan79ed1a82010-01-19 20:22:31 +00003493 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003494
3495 if (TheCondState.TheCond != AsmCond::IfCond &&
3496 TheCondState.TheCond != AsmCond::ElseIfCond)
3497 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3498 ".elseif");
3499 TheCondState.TheCond = AsmCond::ElseCond;
3500 bool LastIgnoreState = false;
3501 if (!TheCondStack.empty())
3502 LastIgnoreState = TheCondStack.back().Ignore;
3503 if (LastIgnoreState || TheCondState.CondMet)
3504 TheCondState.Ignore = true;
3505 else
3506 TheCondState.Ignore = false;
3507
3508 return false;
3509}
3510
3511/// ParseDirectiveEndIf
3512/// ::= .endif
3513bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003514 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003515 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003516
Sean Callanan79ed1a82010-01-19 20:22:31 +00003517 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003518
3519 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3520 TheCondStack.empty())
3521 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3522 ".else");
3523 if (!TheCondStack.empty()) {
3524 TheCondState = TheCondStack.back();
3525 TheCondStack.pop_back();
3526 }
3527
3528 return false;
3529}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003530
Eli Bendersky6ee13082013-01-15 22:59:42 +00003531void AsmParser::initializeDirectiveKindMap() {
3532 DirectiveKindMap[".set"] = DK_SET;
3533 DirectiveKindMap[".equ"] = DK_EQU;
3534 DirectiveKindMap[".equiv"] = DK_EQUIV;
3535 DirectiveKindMap[".ascii"] = DK_ASCII;
3536 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3537 DirectiveKindMap[".string"] = DK_STRING;
3538 DirectiveKindMap[".byte"] = DK_BYTE;
3539 DirectiveKindMap[".short"] = DK_SHORT;
3540 DirectiveKindMap[".value"] = DK_VALUE;
3541 DirectiveKindMap[".2byte"] = DK_2BYTE;
3542 DirectiveKindMap[".long"] = DK_LONG;
3543 DirectiveKindMap[".int"] = DK_INT;
3544 DirectiveKindMap[".4byte"] = DK_4BYTE;
3545 DirectiveKindMap[".quad"] = DK_QUAD;
3546 DirectiveKindMap[".8byte"] = DK_8BYTE;
3547 DirectiveKindMap[".single"] = DK_SINGLE;
3548 DirectiveKindMap[".float"] = DK_FLOAT;
3549 DirectiveKindMap[".double"] = DK_DOUBLE;
3550 DirectiveKindMap[".align"] = DK_ALIGN;
3551 DirectiveKindMap[".align32"] = DK_ALIGN32;
3552 DirectiveKindMap[".balign"] = DK_BALIGN;
3553 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3554 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3555 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3556 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3557 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3558 DirectiveKindMap[".org"] = DK_ORG;
3559 DirectiveKindMap[".fill"] = DK_FILL;
3560 DirectiveKindMap[".zero"] = DK_ZERO;
3561 DirectiveKindMap[".extern"] = DK_EXTERN;
3562 DirectiveKindMap[".globl"] = DK_GLOBL;
3563 DirectiveKindMap[".global"] = DK_GLOBAL;
3564 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3565 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3566 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3567 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3568 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3569 DirectiveKindMap[".reference"] = DK_REFERENCE;
3570 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3571 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3572 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3573 DirectiveKindMap[".comm"] = DK_COMM;
3574 DirectiveKindMap[".common"] = DK_COMMON;
3575 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3576 DirectiveKindMap[".abort"] = DK_ABORT;
3577 DirectiveKindMap[".include"] = DK_INCLUDE;
3578 DirectiveKindMap[".incbin"] = DK_INCBIN;
3579 DirectiveKindMap[".code16"] = DK_CODE16;
3580 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3581 DirectiveKindMap[".rept"] = DK_REPT;
3582 DirectiveKindMap[".irp"] = DK_IRP;
3583 DirectiveKindMap[".irpc"] = DK_IRPC;
3584 DirectiveKindMap[".endr"] = DK_ENDR;
3585 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3586 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3587 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3588 DirectiveKindMap[".if"] = DK_IF;
3589 DirectiveKindMap[".ifb"] = DK_IFB;
3590 DirectiveKindMap[".ifnb"] = DK_IFNB;
3591 DirectiveKindMap[".ifc"] = DK_IFC;
3592 DirectiveKindMap[".ifnc"] = DK_IFNC;
3593 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3594 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3595 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3596 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3597 DirectiveKindMap[".else"] = DK_ELSE;
3598 DirectiveKindMap[".endif"] = DK_ENDIF;
3599 DirectiveKindMap[".skip"] = DK_SKIP;
3600 DirectiveKindMap[".space"] = DK_SPACE;
3601 DirectiveKindMap[".file"] = DK_FILE;
3602 DirectiveKindMap[".line"] = DK_LINE;
3603 DirectiveKindMap[".loc"] = DK_LOC;
3604 DirectiveKindMap[".stabs"] = DK_STABS;
3605 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3606 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3607 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3608 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3609 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3610 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3611 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3612 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3613 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3614 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3615 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3616 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3617 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3618 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3619 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3620 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3621 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3622 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3623 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3624 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3625 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3626 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3627 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3628 DirectiveKindMap[".macro"] = DK_MACRO;
3629 DirectiveKindMap[".endm"] = DK_ENDM;
3630 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3631 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003632}
3633
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003634
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003635MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003636 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003637
Rafael Espindola761cb062012-06-03 23:57:14 +00003638 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003639 for (;;) {
3640 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003641 if (getLexer().is(AsmToken::Eof)) {
3642 Error(DirectiveLoc, "no matching '.endr' in definition");
3643 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003644 }
3645
Rafael Espindola761cb062012-06-03 23:57:14 +00003646 if (Lexer.is(AsmToken::Identifier) &&
3647 (getTok().getIdentifier() == ".rept")) {
3648 ++NestLevel;
3649 }
3650
3651 // Otherwise, check whether we have reached the .endr.
3652 if (Lexer.is(AsmToken::Identifier) &&
3653 getTok().getIdentifier() == ".endr") {
3654 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003655 EndToken = getTok();
3656 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003657 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3658 TokError("unexpected token in '.endr' directive");
3659 return 0;
3660 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003661 break;
3662 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003663 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003664 }
3665
Rafael Espindola761cb062012-06-03 23:57:14 +00003666 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003667 EatToEndOfStatement();
3668 }
3669
3670 const char *BodyStart = StartToken.getLoc().getPointer();
3671 const char *BodyEnd = EndToken.getLoc().getPointer();
3672 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3673
Rafael Espindola761cb062012-06-03 23:57:14 +00003674 // We Are Anonymous.
3675 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003676 MCAsmMacroParameters Parameters;
3677 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003678}
3679
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003680void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003681 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003682 OS << ".endr\n";
3683
3684 MemoryBuffer *Instantiation =
3685 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3686
Rafael Espindola761cb062012-06-03 23:57:14 +00003687 // Create the macro instantiation object and add to the current macro
3688 // instantiation stack.
3689 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003690 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003691 getTok().getLoc(),
3692 Instantiation);
3693 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003694
Rafael Espindola761cb062012-06-03 23:57:14 +00003695 // Jump to the macro instantiation and prime the lexer.
3696 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3697 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3698 Lex();
3699}
3700
3701bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3702 int64_t Count;
3703 if (ParseAbsoluteExpression(Count))
3704 return TokError("unexpected token in '.rept' directive");
3705
3706 if (Count < 0)
3707 return TokError("Count is negative");
3708
3709 if (Lexer.isNot(AsmToken::EndOfStatement))
3710 return TokError("unexpected token in '.rept' directive");
3711
3712 // Eat the end of statement.
3713 Lex();
3714
3715 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003716 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003717 if (!M)
3718 return true;
3719
3720 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3721 // to hold the macro body with substitutions.
3722 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003723 MCAsmMacroParameters Parameters;
3724 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003725 raw_svector_ostream OS(Buf);
3726 while (Count--) {
3727 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3728 return true;
3729 }
3730 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003731
3732 return false;
3733}
3734
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003735/// ParseDirectiveIrp
3736/// ::= .irp symbol,values
3737bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003738 MCAsmMacroParameters Parameters;
3739 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003740
Preston Gurd6c9176a2012-09-19 20:29:04 +00003741 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003742 return TokError("expected identifier in '.irp' directive");
3743
3744 Parameters.push_back(Parameter);
3745
3746 if (Lexer.isNot(AsmToken::Comma))
3747 return TokError("expected comma in '.irp' directive");
3748
3749 Lex();
3750
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003751 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003752 if (ParseMacroArguments(0, A))
3753 return true;
3754
3755 // Eat the end of statement.
3756 Lex();
3757
3758 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003759 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003760 if (!M)
3761 return true;
3762
3763 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3764 // to hold the macro body with substitutions.
3765 SmallString<256> Buf;
3766 raw_svector_ostream OS(Buf);
3767
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003768 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3769 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003770 Args.push_back(*i);
3771
3772 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3773 return true;
3774 }
3775
3776 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3777
3778 return false;
3779}
3780
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003781/// ParseDirectiveIrpc
3782/// ::= .irpc symbol,values
3783bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003784 MCAsmMacroParameters Parameters;
3785 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003786
Preston Gurd6c9176a2012-09-19 20:29:04 +00003787 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003788 return TokError("expected identifier in '.irpc' directive");
3789
3790 Parameters.push_back(Parameter);
3791
3792 if (Lexer.isNot(AsmToken::Comma))
3793 return TokError("expected comma in '.irpc' directive");
3794
3795 Lex();
3796
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003797 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003798 if (ParseMacroArguments(0, A))
3799 return true;
3800
3801 if (A.size() != 1 || A.front().size() != 1)
3802 return TokError("unexpected token in '.irpc' directive");
3803
3804 // Eat the end of statement.
3805 Lex();
3806
3807 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003808 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003809 if (!M)
3810 return true;
3811
3812 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3813 // to hold the macro body with substitutions.
3814 SmallString<256> Buf;
3815 raw_svector_ostream OS(Buf);
3816
3817 StringRef Values = A.front().front().getString();
3818 std::size_t I, End = Values.size();
3819 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003820 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003821 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3822
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003823 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003824 Args.push_back(Arg);
3825
3826 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3827 return true;
3828 }
3829
3830 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3831
3832 return false;
3833}
3834
Rafael Espindola761cb062012-06-03 23:57:14 +00003835bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3836 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003837 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003838
3839 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003840 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003841 assert(getLexer().is(AsmToken::EndOfStatement));
3842
Rafael Espindola761cb062012-06-03 23:57:14 +00003843 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003844 return false;
3845}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003846
Eli Friedman2128aae2012-10-22 23:58:19 +00003847bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3848 const MCExpr *Value;
3849 SMLoc ExprLoc = getLexer().getLoc();
3850 if (ParseExpression(Value))
3851 return true;
3852 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3853 if (!MCE)
3854 return Error(ExprLoc, "unexpected expression in _emit");
3855 uint64_t IntValue = MCE->getValue();
3856 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3857 return Error(ExprLoc, "literal value out of range for directive");
3858
3859 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3860 return false;
3861}
3862
Chad Rosierb1f8c132012-10-18 15:49:34 +00003863bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3864 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003865 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003866 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003867 SmallVectorImpl<std::string> &Clobbers,
3868 const MCInstrInfo *MII,
3869 const MCInstPrinter *IP,
3870 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003871 SmallVector<void *, 4> InputDecls;
3872 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00003873 SmallVector<bool, 4> InputDeclsAddressOf;
3874 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003875 SmallVector<std::string, 4> InputConstraints;
3876 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003877 std::set<std::string> ClobberRegs;
3878
Chad Rosier4e472d22012-10-20 01:02:45 +00003879 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003880
3881 // Prime the lexer.
3882 Lex();
3883
3884 // While we have input, parse each statement.
3885 unsigned InputIdx = 0;
3886 unsigned OutputIdx = 0;
3887 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003888 ParseStatementInfo Info(&AsmStrRewrites);
3889 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003890 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003891
Chad Rosier57498012012-12-12 22:45:52 +00003892 if (Info.ParseError)
3893 return true;
3894
Eli Friedman2128aae2012-10-22 23:58:19 +00003895 if (Info.Opcode != ~0U) {
3896 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003897
3898 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003899 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3900 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003901
3902 // Immediate.
3903 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003904 if (Operand->needAsmRewrite())
3905 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3906 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003907 continue;
3908 }
3909
3910 // Register operand.
Chad Rosierc1ec2072013-01-10 22:10:27 +00003911 if (Operand->isReg() && !Operand->needAddressOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003912 unsigned NumDefs = Desc.getNumDefs();
3913 // Clobber.
3914 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3915 std::string Reg;
3916 raw_string_ostream OS(Reg);
3917 IP->printRegName(OS, Operand->getReg());
3918 ClobberRegs.insert(StringRef(OS.str()));
3919 }
3920 continue;
3921 }
3922
3923 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003924 unsigned Size;
Chad Rosierc1ec2072013-01-10 22:10:27 +00003925 bool IsVarDecl;
Chad Rosier32989592012-10-18 20:27:15 +00003926 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
Chad Rosierc1ec2072013-01-10 22:10:27 +00003927 Size, IsVarDecl);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003928 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003929 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc1ec2072013-01-10 22:10:27 +00003930 if (Operand->isMem() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003931 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003932 Operand->getStartLoc(),
3933 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003934 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003935 if (isOutput) {
3936 std::string Constraint = "=";
3937 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003938 OutputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003939 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003940 Constraint += Operand->getConstraint().str();
3941 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003942 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003943 Operand->getStartLoc(),
3944 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003945 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003946 InputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003947 InputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003948 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003949 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003950 Operand->getStartLoc(),
3951 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003952 }
3953 }
3954 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003955 }
3956 }
3957
3958 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003959 NumOutputs = OutputDecls.size();
3960 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003961
3962 // Set the unique clobbers.
3963 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3964 E = ClobberRegs.end(); I != E; ++I)
3965 Clobbers.push_back(*I);
3966
3967 // Merge the various outputs and inputs. Output are expected first.
3968 if (NumOutputs || NumInputs) {
3969 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003970 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003971 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003972 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00003973 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00003974 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003975 }
3976 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00003977 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00003978 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003979 }
3980 }
3981
3982 // Build the IR assembly string.
3983 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003984 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003985 raw_string_ostream OS(AsmStringIR);
3986 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003987 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003988 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3989 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003990
Chad Rosier4e472d22012-10-20 01:02:45 +00003991 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003992
3993 // Emit everything up to the immediate/expression. If the previous rewrite
3994 // was a size directive, then this has already been done.
3995 if (PrevKind != AOK_SizeDirective)
3996 OS << StringRef(Start, Loc - Start);
3997 PrevKind = Kind;
3998
Chad Rosier5a719fc2012-10-23 17:43:43 +00003999 // Skip the original expression.
4000 if (Kind == AOK_Skip) {
4001 Start = Loc + (*I).Len;
4002 continue;
4003 }
4004
Chad Rosierb1f8c132012-10-18 15:49:34 +00004005 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004006 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004007 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004008 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00004009 OS << Twine("$$");
4010 OS << (*I).Val;
4011 break;
4012 case AOK_ImmPrefix:
4013 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00004014 break;
4015 case AOK_Input:
4016 OS << '$';
4017 OS << InputIdx++;
4018 break;
4019 case AOK_Output:
4020 OS << '$';
4021 OS << OutputIdx++;
4022 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004023 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00004024 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004025 default: break;
4026 case 8: OS << "byte ptr "; break;
4027 case 16: OS << "word ptr "; break;
4028 case 32: OS << "dword ptr "; break;
4029 case 64: OS << "qword ptr "; break;
4030 case 80: OS << "xword ptr "; break;
4031 case 128: OS << "xmmword ptr "; break;
4032 case 256: OS << "ymmword ptr "; break;
4033 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004034 break;
4035 case AOK_Emit:
4036 OS << ".byte";
4037 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00004038 case AOK_DotOperator:
4039 OS << (*I).Val;
4040 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004041 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004042
Chad Rosierb1f8c132012-10-18 15:49:34 +00004043 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00004044 if (Kind != AOK_SizeDirective)
4045 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004046 }
4047
4048 // Emit the remainder of the asm string.
4049 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4050 if (Start != AsmEnd)
4051 OS << StringRef(Start, AsmEnd - Start);
4052
4053 AsmString = OS.str();
4054 return false;
4055}
4056
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004057/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004058MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004059 MCContext &C, MCStreamer &Out,
4060 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004061 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004062}