blob: 7c3fea5640086dfb1c720c3c691958a97012c948 [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 Dunbar6d8cf082010-07-18 18:47:21 +000053/// \brief Helper class for tracking macro definitions.
Rafael Espindola28c1f6662012-06-03 22:41:23 +000054typedef std::vector<AsmToken> MacroArgument;
Rafael Espindola8a403d32012-08-08 14:51:03 +000055typedef std::vector<MacroArgument> MacroArguments;
Preston Gurd6c9176a2012-09-19 20:29:04 +000056typedef std::pair<StringRef, MacroArgument> MacroParameter;
Rafael Espindola8a403d32012-08-08 14:51:03 +000057typedef std::vector<MacroParameter> MacroParameters;
Rafael Espindola28c1f6662012-06-03 22:41:23 +000058
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000059struct Macro {
60 StringRef Name;
61 StringRef Body;
Rafael Espindola8a403d32012-08-08 14:51:03 +000062 MacroParameters Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000063
64public:
Rafael Espindola8a403d32012-08-08 14:51:03 +000065 Macro(StringRef N, StringRef B, const MacroParameters &P) :
Rafael Espindola65366442011-06-05 02:43:45 +000066 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000067};
68
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000069/// \brief Helper class for storing information about an active macro
70/// instantiation.
71struct MacroInstantiation {
72 /// The macro being instantiated.
73 const Macro *TheMacro;
74
75 /// The macro instantiation with substitutions.
76 MemoryBuffer *Instantiation;
77
78 /// The location of the instantiation.
79 SMLoc InstantiationLoc;
80
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000081 /// The buffer where parsing should resume upon instantiation completion.
82 int ExitBuffer;
83
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000084 /// The location where parsing should resume upon instantiation completion.
85 SMLoc ExitLoc;
86
87public:
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000088 MacroInstantiation(const Macro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000089 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000090};
91
Chad Rosier6a020a72012-10-25 20:41:34 +000092//struct AsmRewrite;
Eli Friedman2128aae2012-10-22 23:58:19 +000093struct ParseStatementInfo {
94 /// ParsedOperands - The parsed operands from the last parsed statement.
95 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
96
97 /// Opcode - The opcode from the last parsed instruction.
98 unsigned Opcode;
99
Chad Rosier57498012012-12-12 22:45:52 +0000100 /// Error - Was there an error parsing the inline assembly?
101 bool ParseError;
102
Eli Friedman2128aae2012-10-22 23:58:19 +0000103 SmallVectorImpl<AsmRewrite> *AsmRewrites;
104
Chad Rosier57498012012-12-12 22:45:52 +0000105 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000106 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000107 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000108
109 ~ParseStatementInfo() {
110 // Free any parsed operands.
111 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
112 delete ParsedOperands[i];
113 ParsedOperands.clear();
114 }
115};
116
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000117/// \brief The concrete assembly parser instance.
118class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000119 friend class GenericAsmParser;
120
Craig Topper85aadc02012-09-15 16:23:52 +0000121 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
122 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000123private:
124 AsmLexer Lexer;
125 MCContext &Ctx;
126 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000127 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000128 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000129 SourceMgr::DiagHandlerTy SavedDiagHandler;
130 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000131 MCAsmParserExtension *GenericParser;
132 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000133
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
136 int CurBuffer;
137
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
140
141 /// DirectiveMap - This is a table handlers for directives. Each handler is
142 /// invoked after the directive identifier is read and is responsible for
143 /// parsing and validating the rest of the directive. The handler is passed
144 /// in the directive name and the location of the directive keyword.
145 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000146
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000147 /// MacroMap - Map of currently defined macros.
148 StringMap<Macro*> MacroMap;
149
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000150 /// ActiveMacros - Stack of active macro instantiations.
151 std::vector<MacroInstantiation*> ActiveMacros;
152
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000153 /// Boolean tracking whether macro substitution is enabled.
154 unsigned MacrosEnabled : 1;
155
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000156 /// Flag tracking whether any errors have been encountered.
157 unsigned HadError : 1;
158
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000159 /// The values from the last parsed cpp hash file line comment if any.
160 StringRef CppHashFilename;
161 int64_t CppHashLineNumber;
162 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000163 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000164
Devang Patel0db58bf2012-01-31 18:14:05 +0000165 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
166 unsigned AssemblerDialect;
167
Preston Gurd7b6f2032012-09-19 20:36:12 +0000168 /// IsDarwin - is Darwin compatibility enabled?
169 bool IsDarwin;
170
Chad Rosier8f138d12012-10-15 17:19:13 +0000171 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000172 bool ParsingInlineAsm;
173
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000174public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000175 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000176 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000177 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000178
179 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
180
Craig Topper345d16d2012-08-29 05:48:09 +0000181 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
182 StringRef Directive,
183 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000184 DirectiveMap[Directive] = std::make_pair(Object, Handler);
185 }
186
187public:
188 /// @name MCAsmParser Interface
189 /// {
190
191 virtual SourceMgr &getSourceManager() { return SrcMgr; }
192 virtual MCAsmLexer &getLexer() { return Lexer; }
193 virtual MCContext &getContext() { return Ctx; }
194 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000195 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000196 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000197 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000198 else
199 return AssemblerDialect;
200 }
201 virtual void setAssemblerDialect(unsigned i) {
202 AssemblerDialect = i;
203 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000204
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000205 virtual bool Warning(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
207 virtual bool Error(SMLoc L, const Twine &Msg,
208 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000209
Craig Topper345d16d2012-08-29 05:48:09 +0000210 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000211
Chad Rosier84125ca2012-10-13 00:26:04 +0000212 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000213 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000214
215 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
216 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000217 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000218 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000219 SmallVectorImpl<std::string> &Clobbers,
220 const MCInstrInfo *MII,
221 const MCInstPrinter *IP,
222 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000223
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000224 bool ParseExpression(const MCExpr *&Res);
225 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
226 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
227 virtual bool ParseAbsoluteExpression(int64_t &Res);
228
229 /// }
230
231private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000232 void CheckForValidSection();
233
Eli Friedman2128aae2012-10-22 23:58:19 +0000234 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000235 void EatToEndOfLine();
236 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000237
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000238 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000239 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000240 const MacroParameters &Parameters,
241 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000242 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000243 void HandleMacroExit();
244
245 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000246 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000247 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
248 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000249 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000250 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000251
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000252 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
253 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000254 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
255 /// This returns true on failure.
256 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000257
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000258 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000259 /// current token is not set; clients should ensure Lex() is called
260 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000261 ///
262 /// \param InBuffer If not -1, should be the known buffer id that contains the
263 /// location.
264 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000265
Craig Topper345d16d2012-08-29 05:48:09 +0000266 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000267
Preston Gurd7b6f2032012-09-19 20:36:12 +0000268 bool ParseMacroArgument(MacroArgument &MA,
269 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000270 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000271
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000272 /// \brief Parse up to the end of statement and a return the contents from the
273 /// current token until the end of the statement; the current token on exit
274 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000275 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000276
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000277 /// \brief Parse until the end of a statement or a comma is encountered,
278 /// return the contents from the current token up to the end or comma.
279 StringRef ParseStringToComma();
280
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000281 bool ParseAssignment(StringRef Name, bool allow_redef,
282 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000283
284 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
285 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
286 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000287 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000288
289 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000290 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000291 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000292
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000293 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000294
Eli Bendersky14b8f792012-12-17 22:50:56 +0000295 // ".ascii", ".asciiz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000296 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000297 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000298 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000299 bool ParseDirectiveFill(); // ".fill"
300 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000301 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000302 // ".set", ".equ", ".equiv"
303 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000304 bool ParseDirectiveOrg(); // ".org"
305 // ".align{,32}", ".p2align{,w,l}"
306 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
307
Eli Bendersky4766ef42012-12-20 19:05:53 +0000308 // ".bundle_align_mode"
309 bool ParseDirectiveBundleAlignMode();
310 // ".bundle_lock"
311 bool ParseDirectiveBundleLock();
312 // ".bundle_unlock"
313 bool ParseDirectiveBundleUnlock();
314
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000315 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
316 /// accepts a single symbol (which should be a label or an external).
317 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000318
319 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
320
321 bool ParseDirectiveAbort(); // ".abort"
322 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000323 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000324
325 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000326 // ".ifb" or ".ifnb", depending on ExpectBlank.
327 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000328 // ".ifc" or ".ifnc", depending on ExpectEqual.
329 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000330 // ".ifdef" or ".ifndef", depending on expect_defined
331 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000332 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
333 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
334 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
335
336 /// ParseEscapedString - Parse the current token as a string which may include
337 /// escaped characters and return the string contents.
338 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000339
340 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
341 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000342
Rafael Espindola761cb062012-06-03 23:57:14 +0000343 // Macro-like directives
344 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
345 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
346 raw_svector_ostream &OS);
347 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000348 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000349 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000350 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000351
Eli Friedman2128aae2012-10-22 23:58:19 +0000352 // "_emit"
353 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000354};
355
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000356/// \brief Generic implementations of directive handling, etc. which is shared
357/// (or the default, at least) for all assembler parser.
358class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000359 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
360 void AddDirectiveHandler(StringRef Directive) {
361 getParser().AddDirectiveHandler(this, Directive,
362 HandleDirective<GenericAsmParser, Handler>);
363 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000364public:
365 GenericAsmParser() {}
366
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000367 AsmParser &getParser() {
368 return (AsmParser&) this->MCAsmParserExtension::getParser();
369 }
370
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000371 virtual void Initialize(MCAsmParser &Parser) {
372 // Call the base implementation.
373 this->MCAsmParserExtension::Initialize(Parser);
374
375 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000376 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
377 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
378 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000379 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000380
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000381 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000382 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
383 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000384 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
385 ".cfi_startproc");
386 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
387 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000388 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
389 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
391 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000392 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
393 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000394 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
395 ".cfi_def_cfa_register");
396 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
397 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000398 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
399 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000400 AddDirectiveHandler<
401 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
402 AddDirectiveHandler<
403 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000404 AddDirectiveHandler<
405 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
406 AddDirectiveHandler<
407 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000408 AddDirectiveHandler<
409 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000410 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000411 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
412 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000413 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000414 AddDirectiveHandler<
415 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000416 AddDirectiveHandler<
417 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000418 AddDirectiveHandler<
419 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000420
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000421 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000422 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
423 ".macros_on");
424 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
425 ".macros_off");
426 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
427 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
428 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000429 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000430
431 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
432 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000433 }
434
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000435 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
436
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000437 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
438 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
439 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000440 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000441 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000442 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
443 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000444 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000445 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000446 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000447 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
448 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000449 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000450 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000451 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
452 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000453 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000454 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000455 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000456 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000457 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000458 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000459
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000460 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000461 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
462 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000463 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000464
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000465 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000466};
467
468}
469
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000470namespace llvm {
471
472extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000473extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000474extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000475
476}
477
Chris Lattneraaec2052010-01-19 19:46:13 +0000478enum { DEFAULT_ADDRSPACE = 0 };
479
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000480AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000481 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000482 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000483 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000484 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000485 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000486 // Save the old handler.
487 SavedDiagHandler = SrcMgr.getDiagHandler();
488 SavedDiagContext = SrcMgr.getDiagContext();
489 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000490 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000491 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000492
493 // Initialize the generic parser.
494 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000495
496 // Initialize the platform / file format parser.
497 //
498 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
499 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000500 if (_MAI.hasMicrosoftFastStdCallMangling()) {
501 PlatformParser = createCOFFAsmParser();
502 PlatformParser->Initialize(*this);
503 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000504 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000505 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000506 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000507 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000508 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000509 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000510 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000511}
512
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000513AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000514 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
515
516 // Destroy any macros.
517 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
518 ie = MacroMap.end(); it != ie; ++it)
519 delete it->getValue();
520
Daniel Dunbare4749702010-07-12 18:12:02 +0000521 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000522 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000523}
524
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000525void AsmParser::PrintMacroInstantiations() {
526 // Print the active macro instantiation stack.
527 for (std::vector<MacroInstantiation*>::const_reverse_iterator
528 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000529 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
530 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000531}
532
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000533bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000534 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000535 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000536 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000537 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000538 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000539}
540
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000541bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000542 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000543 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000544 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000545 return true;
546}
547
Sean Callananfd0b0282010-01-21 00:19:58 +0000548bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000549 std::string IncludedFile;
550 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000551 if (NewBuf == -1)
552 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000553
Sean Callananfd0b0282010-01-21 00:19:58 +0000554 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000555
Sean Callananfd0b0282010-01-21 00:19:58 +0000556 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000557
Sean Callananfd0b0282010-01-21 00:19:58 +0000558 return false;
559}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000560
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000561/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000562/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000563/// returns true on failure.
564bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
565 std::string IncludedFile;
566 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
567 if (NewBuf == -1)
568 return true;
569
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000570 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000571 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
572 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000573 return false;
574}
575
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000576void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
577 if (InBuffer != -1) {
578 CurBuffer = InBuffer;
579 } else {
580 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
581 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000582 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
583}
584
Sean Callananfd0b0282010-01-21 00:19:58 +0000585const AsmToken &AsmParser::Lex() {
586 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000587
Sean Callananfd0b0282010-01-21 00:19:58 +0000588 if (tok->is(AsmToken::Eof)) {
589 // If this is the end of an included file, pop the parent file off the
590 // include stack.
591 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
592 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000593 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000594 tok = &Lexer.Lex();
595 }
596 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000597
Sean Callananfd0b0282010-01-21 00:19:58 +0000598 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000599 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000600
Sean Callananfd0b0282010-01-21 00:19:58 +0000601 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000602}
603
Chris Lattner79180e22010-04-05 23:15:42 +0000604bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000605 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000606 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000607 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000608
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000609 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000610 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000611
612 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000613 AsmCond StartingCondState = TheCondState;
614
Kevin Enderby613b7572011-11-01 22:27:22 +0000615 // If we are generating dwarf for assembly source files save the initial text
616 // section and generate a .file directive.
617 if (getContext().getGenDwarfForAssembly()) {
618 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000619 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
620 getStreamer().EmitLabel(SectionStartSym);
621 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000622 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000623 StringRef(),
624 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000625 }
626
Chris Lattnerb717fb02009-07-02 21:53:43 +0000627 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000628 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000629 ParseStatementInfo Info;
630 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000631
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000632 // We had an error, validate that one was emitted and recover by skipping to
633 // the next line.
634 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000635 EatToEndOfStatement();
636 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000637
638 if (TheCondState.TheCond != StartingCondState.TheCond ||
639 TheCondState.Ignore != StartingCondState.Ignore)
640 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000641
642 // Check to see there are no empty DwarfFile slots.
643 const std::vector<MCDwarfFile *> &MCDwarfFiles =
644 getContext().getMCDwarfFiles();
645 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000646 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000647 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000648 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000649
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000650 // Check to see that all assembler local symbols were actually defined.
651 // Targets that don't do subsections via symbols may not want this, though,
652 // so conservatively exclude them. Only do this if we're finalizing, though,
653 // as otherwise we won't necessarilly have seen everything yet.
654 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
655 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
656 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
657 e = Symbols.end();
658 i != e; ++i) {
659 MCSymbol *Sym = i->getValue();
660 // Variable symbols may not be marked as defined, so check those
661 // explicitly. If we know it's a variable, we have a definition for
662 // the purposes of this check.
663 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
664 // FIXME: We would really like to refer back to where the symbol was
665 // first referenced for a source location. We need to add something
666 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000667 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
668 "assembler local symbol '" + Sym->getName() +
669 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000670 }
671 }
672
673
Chris Lattner79180e22010-04-05 23:15:42 +0000674 // Finalize the output stream if there are no errors and if the client wants
675 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000676 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000677 Out.Finish();
678
Chris Lattnerb717fb02009-07-02 21:53:43 +0000679 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000680}
681
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000682void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000683 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000684 TokError("expected section directive before assembly directive");
685 Out.SwitchSection(Ctx.getMachOSection(
686 "__TEXT", "__text",
687 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
688 0, SectionKind::getText()));
689 }
690}
691
Chris Lattner2cf5f142009-06-22 01:29:09 +0000692/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
693void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000694 while (Lexer.isNot(AsmToken::EndOfStatement) &&
695 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000696 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000697
Chris Lattner2cf5f142009-06-22 01:29:09 +0000698 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000699 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000700 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000701}
702
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000703StringRef AsmParser::ParseStringToEndOfStatement() {
704 const char *Start = getTok().getLoc().getPointer();
705
706 while (Lexer.isNot(AsmToken::EndOfStatement) &&
707 Lexer.isNot(AsmToken::Eof))
708 Lex();
709
710 const char *End = getTok().getLoc().getPointer();
711 return StringRef(Start, End - Start);
712}
Chris Lattnerc4193832009-06-22 05:51:26 +0000713
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000714StringRef AsmParser::ParseStringToComma() {
715 const char *Start = getTok().getLoc().getPointer();
716
717 while (Lexer.isNot(AsmToken::EndOfStatement) &&
718 Lexer.isNot(AsmToken::Comma) &&
719 Lexer.isNot(AsmToken::Eof))
720 Lex();
721
722 const char *End = getTok().getLoc().getPointer();
723 return StringRef(Start, End - Start);
724}
725
Chris Lattner74ec1a32009-06-22 06:32:03 +0000726/// ParseParenExpr - Parse a paren expression and return it.
727/// NOTE: This assumes the leading '(' has already been consumed.
728///
729/// parenexpr ::= expr)
730///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000731bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000732 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000733 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000734 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000735 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000736 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000737 return false;
738}
Chris Lattnerc4193832009-06-22 05:51:26 +0000739
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000740/// ParseBracketExpr - Parse a bracket expression and return it.
741/// NOTE: This assumes the leading '[' has already been consumed.
742///
743/// bracketexpr ::= expr]
744///
745bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
746 if (ParseExpression(Res)) return true;
747 if (Lexer.isNot(AsmToken::RBrac))
748 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000749 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000750 Lex();
751 return false;
752}
753
Chris Lattner74ec1a32009-06-22 06:32:03 +0000754/// ParsePrimaryExpr - Parse a primary expression and return it.
755/// primaryexpr ::= (parenexpr
756/// primaryexpr ::= symbol
757/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000758/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000759/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000760bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000761 switch (Lexer.getKind()) {
762 default:
763 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000764 // If we have an error assume that we've already handled it.
765 case AsmToken::Error:
766 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000767 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000768 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000769 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000770 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000771 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000772 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000773 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000774 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000775 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000776 StringRef Identifier;
777 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000778 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000779
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000780 EndLoc = SMLoc::getFromPointer(Identifier.end());
781
Daniel Dunbarfffff912009-10-16 01:34:54 +0000782 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000783 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000784 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000785
786 // Lookup the symbol variant if used.
787 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000788 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000789 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000790 if (Variant == MCSymbolRefExpr::VK_Invalid) {
791 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000792 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000793 }
794 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000795
Daniel Dunbarfffff912009-10-16 01:34:54 +0000796 // If this is an absolute variable reference, substitute it now to preserve
797 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000798 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000799 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000800 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000801
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000802 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000803 return false;
804 }
805
806 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000807 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000808 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000809 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000810 case AsmToken::Integer: {
811 SMLoc Loc = getTok().getLoc();
812 int64_t IntVal = getTok().getIntVal();
813 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000814 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000815 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000816 // Look for 'b' or 'f' following an Integer as a directional label
817 if (Lexer.getKind() == AsmToken::Identifier) {
818 StringRef IDVal = getTok().getString();
819 if (IDVal == "f" || IDVal == "b"){
820 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
821 IDVal == "f" ? 1 : 0);
822 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
823 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000824 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000825 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000826 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000827 Lex(); // Eat identifier.
828 }
829 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000830 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000831 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000832 case AsmToken::Real: {
833 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000834 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000835 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000836 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000837 Lex(); // Eat token.
838 return false;
839 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000840 case AsmToken::Dot: {
841 // This is a '.' reference, which references the current PC. Emit a
842 // temporary label to the streamer and refer to it.
843 MCSymbol *Sym = Ctx.CreateTempSymbol();
844 Out.EmitLabel(Sym);
845 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000846 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000847 Lex(); // Eat identifier.
848 return false;
849 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000850 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000851 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000852 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000853 case AsmToken::LBrac:
854 if (!PlatformParser->HasBracketExpressions())
855 return TokError("brackets expression not supported on this target");
856 Lex(); // Eat the '['.
857 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000858 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000859 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000860 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000861 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000862 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000863 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000864 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000865 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000866 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000867 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000868 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000869 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000870 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000871 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000872 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000873 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000874 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000875 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000876 }
877}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000878
Chris Lattnerb4307b32010-01-15 19:28:38 +0000879bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000880 SMLoc EndLoc;
881 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000882}
883
Daniel Dunbarcceba832010-09-17 02:47:07 +0000884const MCExpr *
885AsmParser::ApplyModifierToExpr(const MCExpr *E,
886 MCSymbolRefExpr::VariantKind Variant) {
887 // Recurse over the given expression, rebuilding it to apply the given variant
888 // if there is exactly one symbol.
889 switch (E->getKind()) {
890 case MCExpr::Target:
891 case MCExpr::Constant:
892 return 0;
893
894 case MCExpr::SymbolRef: {
895 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
896
897 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
898 TokError("invalid variant on expression '" +
899 getTok().getIdentifier() + "' (already modified)");
900 return E;
901 }
902
903 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
904 }
905
906 case MCExpr::Unary: {
907 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
908 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
909 if (!Sub)
910 return 0;
911 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
912 }
913
914 case MCExpr::Binary: {
915 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
916 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
917 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
918
919 if (!LHS && !RHS)
920 return 0;
921
922 if (!LHS) LHS = BE->getLHS();
923 if (!RHS) RHS = BE->getRHS();
924
925 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
926 }
927 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000928
Craig Topper85814382012-02-07 05:05:23 +0000929 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000930}
931
Chris Lattner74ec1a32009-06-22 06:32:03 +0000932/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000933///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000934/// expr ::= expr &&,|| expr -> lowest.
935/// expr ::= expr |,^,&,! expr
936/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
937/// expr ::= expr <<,>> expr
938/// expr ::= expr +,- expr
939/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000940/// expr ::= primaryexpr
941///
Chris Lattner54482b42010-01-15 19:39:23 +0000942bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000943 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000944 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000945 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
946 return true;
947
Daniel Dunbarcceba832010-09-17 02:47:07 +0000948 // As a special case, we support 'a op b @ modifier' by rewriting the
949 // expression to include the modifier. This is inefficient, but in general we
950 // expect users to use 'a@modifier op b'.
951 if (Lexer.getKind() == AsmToken::At) {
952 Lex();
953
954 if (Lexer.isNot(AsmToken::Identifier))
955 return TokError("unexpected symbol modifier following '@'");
956
957 MCSymbolRefExpr::VariantKind Variant =
958 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
959 if (Variant == MCSymbolRefExpr::VK_Invalid)
960 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
961
962 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
963 if (!ModifiedRes) {
964 return TokError("invalid modifier '" + getTok().getIdentifier() +
965 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000966 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000967
Daniel Dunbarcceba832010-09-17 02:47:07 +0000968 Res = ModifiedRes;
969 Lex();
970 }
971
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000972 // Try to constant fold it up front, if possible.
973 int64_t Value;
974 if (Res->EvaluateAsAbsolute(Value))
975 Res = MCConstantExpr::Create(Value, getContext());
976
977 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000978}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000979
Chris Lattnerb4307b32010-01-15 19:28:38 +0000980bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000981 Res = 0;
982 return ParseParenExpr(Res, EndLoc) ||
983 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000984}
985
Daniel Dunbar475839e2009-06-29 20:37:27 +0000986bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000987 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000988
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000989 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000990 if (ParseExpression(Expr))
991 return true;
992
Daniel Dunbare00b0112009-10-16 01:57:52 +0000993 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000994 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000995
996 return false;
997}
998
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000999static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001000 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001001 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001002 default:
1003 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +00001004
Jim Grosbachfbe16812011-08-20 16:24:13 +00001005 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +00001006 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001007 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001008 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001009 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001010 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001011 return 1;
1012
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001013
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001014 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001015 //
1016 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001017 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001018 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001019 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001020 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001021 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001022 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001023 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001024 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001025 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001026
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001027 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001028 case AsmToken::EqualEqual:
1029 Kind = MCBinaryExpr::EQ;
1030 return 3;
1031 case AsmToken::ExclaimEqual:
1032 case AsmToken::LessGreater:
1033 Kind = MCBinaryExpr::NE;
1034 return 3;
1035 case AsmToken::Less:
1036 Kind = MCBinaryExpr::LT;
1037 return 3;
1038 case AsmToken::LessEqual:
1039 Kind = MCBinaryExpr::LTE;
1040 return 3;
1041 case AsmToken::Greater:
1042 Kind = MCBinaryExpr::GT;
1043 return 3;
1044 case AsmToken::GreaterEqual:
1045 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001046 return 3;
1047
Jim Grosbachfbe16812011-08-20 16:24:13 +00001048 // Intermediate Precedence: <<, >>
1049 case AsmToken::LessLess:
1050 Kind = MCBinaryExpr::Shl;
1051 return 4;
1052 case AsmToken::GreaterGreater:
1053 Kind = MCBinaryExpr::Shr;
1054 return 4;
1055
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001056 // High Intermediate Precedence: +, -
1057 case AsmToken::Plus:
1058 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001059 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001060 case AsmToken::Minus:
1061 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001062 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001063
Jim Grosbachfbe16812011-08-20 16:24:13 +00001064 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001065 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001066 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001067 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001068 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001069 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001070 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001071 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001072 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001073 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001074 }
1075}
1076
1077
1078/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1079/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001080bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1081 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001082 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001083 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001084 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001085
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001086 // If the next token is lower precedence than we are allowed to eat, return
1087 // successfully with what we ate already.
1088 if (TokPrec < Precedence)
1089 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001090
Sean Callanan79ed1a82010-01-19 20:22:31 +00001091 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001092
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001093 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001094 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001095 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001096
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001097 // If BinOp binds less tightly with RHS than the operator after RHS, let
1098 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001099 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001100 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001101 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001102 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001103 }
1104
Daniel Dunbar475839e2009-06-29 20:37:27 +00001105 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001106 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001107 }
1108}
1109
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001110/// ParseStatement:
1111/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001112/// ::= Label* Directive ...Operands... EndOfStatement
1113/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001114bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001115 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001116 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001117 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001118 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001119 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001120
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001121 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001122 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001123 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001124 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001125 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001126 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001127 if (Lexer.is(AsmToken::Hash))
1128 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001129
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001130 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001131 if (Lexer.is(AsmToken::Integer)) {
1132 LocalLabelVal = getTok().getIntVal();
1133 if (LocalLabelVal < 0) {
1134 if (!TheCondState.Ignore)
1135 return TokError("unexpected token at start of statement");
1136 IDVal = "";
1137 }
1138 else {
1139 IDVal = getTok().getString();
1140 Lex(); // Consume the integer token to be used as an identifier token.
1141 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001142 if (!TheCondState.Ignore)
1143 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001144 }
1145 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001146
1147 } else if (Lexer.is(AsmToken::Dot)) {
1148 // Treat '.' as a valid identifier in this context.
1149 Lex();
1150 IDVal = ".";
1151
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001152 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001153 if (!TheCondState.Ignore)
1154 return TokError("unexpected token at start of statement");
1155 IDVal = "";
1156 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001157
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001158
Chris Lattner7834fac2010-04-17 18:14:27 +00001159 // Handle conditional assembly here before checking for skipping. We
1160 // have to do this so that .endif isn't skipped in a ".if 0" block for
1161 // example.
1162 if (IDVal == ".if")
1163 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001164 if (IDVal == ".ifb")
1165 return ParseDirectiveIfb(IDLoc, true);
1166 if (IDVal == ".ifnb")
1167 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001168 if (IDVal == ".ifc")
1169 return ParseDirectiveIfc(IDLoc, true);
1170 if (IDVal == ".ifnc")
1171 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001172 if (IDVal == ".ifdef")
1173 return ParseDirectiveIfdef(IDLoc, true);
1174 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1175 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001176 if (IDVal == ".elseif")
1177 return ParseDirectiveElseIf(IDLoc);
1178 if (IDVal == ".else")
1179 return ParseDirectiveElse(IDLoc);
1180 if (IDVal == ".endif")
1181 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001182
Chris Lattner7834fac2010-04-17 18:14:27 +00001183 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001184 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001185 EatToEndOfStatement();
1186 return false;
1187 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001188
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001189 // FIXME: Recurse on local labels?
1190
1191 // See what kind of statement we have.
1192 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001193 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001194 CheckForValidSection();
1195
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001196 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001197 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001198
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001199 // Diagnose attempt to use '.' as a label.
1200 if (IDVal == ".")
1201 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1202
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001203 // Diagnose attempt to use a variable as a label.
1204 //
1205 // FIXME: Diagnostics. Note the location of the definition as a label.
1206 // FIXME: This doesn't diagnose assignment to a symbol which has been
1207 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001208 MCSymbol *Sym;
1209 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001210 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001211 else
1212 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001213 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001214 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001215
Daniel Dunbar959fd882009-08-26 22:13:22 +00001216 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001217 if (!ParsingInlineAsm)
1218 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001219
Kevin Enderby94c2e852011-12-09 18:09:40 +00001220 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001221 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001222 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001223 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1224 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001225
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001226 // Consume any end of statement token, if present, to avoid spurious
1227 // AddBlankLine calls().
1228 if (Lexer.is(AsmToken::EndOfStatement)) {
1229 Lex();
1230 if (Lexer.is(AsmToken::Eof))
1231 return false;
1232 }
1233
Eli Friedman2128aae2012-10-22 23:58:19 +00001234 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001235 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001236
Daniel Dunbar3f872332009-07-28 16:08:33 +00001237 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001238 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001239 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001240
Nico Weber4c4c7322011-01-28 03:04:41 +00001241 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001242
1243 default: // Normal instruction or directive.
1244 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001245 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001246
1247 // If macros are enabled, check to see if this is a macro instantiation.
1248 if (MacrosEnabled)
1249 if (const Macro *M = MacroMap.lookup(IDVal))
1250 return HandleMacroEntry(IDVal, IDLoc, M);
1251
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001252 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001253 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001254
1255 // Target hook for parsing target specific directives.
1256 if (!getTargetParser().ParseDirective(ID))
1257 return false;
1258
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001259 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001260 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001261 return ParseDirectiveSet(IDVal, true);
1262 if (IDVal == ".equiv")
1263 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001264
Daniel Dunbara0d14262009-06-24 23:30:00 +00001265 // Data directives
1266
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001267 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001268 return ParseDirectiveAscii(IDVal, false);
1269 if (IDVal == ".asciz" || IDVal == ".string")
1270 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001271
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001272 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001273 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001274 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001275 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001276 if (IDVal == ".value")
1277 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001278 if (IDVal == ".2byte")
1279 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001280 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001281 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001282 if (IDVal == ".int")
1283 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001284 if (IDVal == ".4byte")
1285 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001286 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001287 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001288 if (IDVal == ".8byte")
1289 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001290 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001291 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1292 if (IDVal == ".double")
1293 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001294
Eli Friedman5d68ec22010-07-19 04:17:25 +00001295 if (IDVal == ".align") {
1296 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1297 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1298 }
1299 if (IDVal == ".align32") {
1300 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1301 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1302 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001303 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001304 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001305 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001306 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001307 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001308 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001309 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001310 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001311 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001312 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001313 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001314 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1315
Eli Bendersky4766ef42012-12-20 19:05:53 +00001316 if (IDVal == ".bundle_align_mode")
1317 return ParseDirectiveBundleAlignMode();
1318 if (IDVal == ".bundle_lock")
1319 return ParseDirectiveBundleLock();
1320 if (IDVal == ".bundle_unlock")
1321 return ParseDirectiveBundleUnlock();
1322
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001323 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001324 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001325
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001326 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001327 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001328 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001329 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001330 if (IDVal == ".zero")
1331 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001332
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001333 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001334
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001335 if (IDVal == ".extern") {
1336 EatToEndOfStatement(); // .extern is the default, ignore it.
1337 return false;
1338 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001339 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001340 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001341 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001342 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001343 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001344 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001345 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001346 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001347 if (IDVal == ".symbol_resolver")
1348 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001349 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001350 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001351 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001352 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001353 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001354 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001355 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001356 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001357 if (IDVal == ".weak_def_can_be_hidden")
1358 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001359
Hans Wennborg5cc64912011-06-18 13:51:54 +00001360 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001361 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001362 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001363 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001364
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001365 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001366 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001367 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001368 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001369 if (IDVal == ".incbin")
1370 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001371
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001372 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001373 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001374
Rafael Espindola761cb062012-06-03 23:57:14 +00001375 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001376 if (IDVal == ".rept")
1377 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001378 if (IDVal == ".irp")
1379 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001380 if (IDVal == ".irpc")
1381 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001382 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001383 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001384
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001385 // Look up the handler in the handler table.
1386 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1387 DirectiveMap.lookup(IDVal);
1388 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001389 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001390
Kevin Enderby9c656452009-09-10 20:51:44 +00001391
Jim Grosbach686c0182012-05-01 18:38:27 +00001392 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001393 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001394
Eli Friedman2128aae2012-10-22 23:58:19 +00001395 // _emit
1396 if (ParsingInlineAsm && IDVal == "_emit")
1397 return ParseDirectiveEmit(IDLoc, Info);
1398
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001399 CheckForValidSection();
1400
Chris Lattnera7f13542010-05-19 23:34:33 +00001401 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001402 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001403 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001404 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001405
Chad Rosier6a020a72012-10-25 20:41:34 +00001406 ParseInstructionInfo IInfo(Info.AsmRewrites);
1407 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1408 IDLoc,Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001409 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001410
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001411 // Dump the parsed representation, if requested.
1412 if (getShowParsedOperands()) {
1413 SmallString<256> Str;
1414 raw_svector_ostream OS(Str);
1415 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001416 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001417 if (i != 0)
1418 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001419 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001420 }
1421 OS << "]";
1422
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001423 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001424 }
1425
Kevin Enderby613b7572011-11-01 22:27:22 +00001426 // If we are generating dwarf for assembly source files and the current
1427 // section is the initial text section then generate a .loc directive for
1428 // the instruction.
1429 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001430 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001431
1432 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1433
1434 // If we previously parsed a cpp hash file line comment then make sure the
1435 // current Dwarf File is for the CppHashFilename if not then emit the
1436 // Dwarf File table for it and adjust the line number for the .loc.
1437 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1438 getContext().getMCDwarfFiles();
1439 if (CppHashFilename.size() != 0) {
1440 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1441 CppHashFilename)
Eric Christopher2318ba12012-12-18 00:30:54 +00001442 getStreamer().EmitDwarfFileDirective(
1443 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001444
Kevin Enderby32c1a822012-11-05 21:55:41 +00001445 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001446 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1447 }
1448
Kevin Enderby613b7572011-11-01 22:27:22 +00001449 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001450 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001451 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001452 StringRef());
1453 }
1454
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001455 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001456 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001457 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001458 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1459 Info.ParsedOperands,
1460 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001461 ParsingInlineAsm);
1462 }
Chris Lattner98986712010-01-14 22:21:20 +00001463
Chris Lattnercbf8a982010-09-11 16:18:25 +00001464 // Don't skip the rest of the line, the instruction parser is responsible for
1465 // that.
1466 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001467}
Chris Lattner9a023f72009-06-24 04:43:34 +00001468
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001469/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1470/// since they may not be able to be tokenized to get to the end of line token.
1471void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001472 if (!Lexer.is(AsmToken::EndOfStatement))
1473 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001474 // Eat EOL.
1475 Lex();
1476}
1477
1478/// ParseCppHashLineFilenameComment as this:
1479/// ::= # number "filename"
1480/// or just as a full line comment if it doesn't have a number and a string.
1481bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1482 Lex(); // Eat the hash token.
1483
1484 if (getLexer().isNot(AsmToken::Integer)) {
1485 // Consume the line since in cases it is not a well-formed line directive,
1486 // as if were simply a full line comment.
1487 EatToEndOfLine();
1488 return false;
1489 }
1490
1491 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001492 Lex();
1493
1494 if (getLexer().isNot(AsmToken::String)) {
1495 EatToEndOfLine();
1496 return false;
1497 }
1498
1499 StringRef Filename = getTok().getString();
1500 // Get rid of the enclosing quotes.
1501 Filename = Filename.substr(1, Filename.size()-2);
1502
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001503 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1504 CppHashLoc = L;
1505 CppHashFilename = Filename;
1506 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001507 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001508
1509 // Ignore any trailing characters, they're just comment.
1510 EatToEndOfLine();
1511 return false;
1512}
1513
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001514/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001515/// for the Filename and LineNo if any in the diagnostic.
1516void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1517 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1518 raw_ostream &OS = errs();
1519
1520 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1521 const SMLoc &DiagLoc = Diag.getLoc();
1522 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1523 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1524
1525 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1526 // before printing the message.
1527 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001528 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001529 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1530 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1531 }
1532
Eric Christopher2318ba12012-12-18 00:30:54 +00001533 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001534 // manager changed or buffer changed (like in a nested include) then just
1535 // print the normal diagnostic using its Filename and LineNo.
1536 if (!Parser->CppHashLineNumber ||
1537 &DiagSrcMgr != &Parser->SrcMgr ||
1538 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001539 if (Parser->SavedDiagHandler)
1540 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1541 else
1542 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001543 return;
1544 }
1545
Eric Christopher2318ba12012-12-18 00:30:54 +00001546 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001547 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1548 // the diagnostic.
1549 const std::string Filename = Parser->CppHashFilename;
1550
1551 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1552 int CppHashLocLineNo =
1553 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1554 int LineNo = Parser->CppHashLineNumber - 1 +
1555 (DiagLocLineNo - CppHashLocLineNo);
1556
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001557 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1558 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001559 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001560 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001561
Benjamin Kramer04a04262011-10-16 10:48:29 +00001562 if (Parser->SavedDiagHandler)
1563 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1564 else
1565 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001566}
1567
Rafael Espindola799aacf2012-08-21 18:29:30 +00001568// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1569// difference being that that function accepts '@' as part of identifiers and
1570// we can't do that. AsmLexer.cpp should probably be changed to handle
1571// '@' as a special case when needed.
1572static bool isIdentifierChar(char c) {
1573 return isalnum(c) || c == '_' || c == '$' || c == '.';
1574}
1575
Rafael Espindola761cb062012-06-03 23:57:14 +00001576bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001577 const MacroParameters &Parameters,
1578 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001579 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001580 unsigned NParameters = Parameters.size();
1581 if (NParameters != 0 && NParameters != A.size())
1582 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001583
Preston Gurd7b6f2032012-09-19 20:36:12 +00001584 // A macro without parameters is handled differently on Darwin:
1585 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001586 while (!Body.empty()) {
1587 // Scan for the next substitution.
1588 std::size_t End = Body.size(), Pos = 0;
1589 for (; Pos != End; ++Pos) {
1590 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001591 if (!NParameters) {
1592 // This macro has no parameters, look for $0, $1, etc.
1593 if (Body[Pos] != '$' || Pos + 1 == End)
1594 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001595
Rafael Espindola65366442011-06-05 02:43:45 +00001596 char Next = Body[Pos + 1];
1597 if (Next == '$' || Next == 'n' || isdigit(Next))
1598 break;
1599 } else {
1600 // This macro has parameters, look for \foo, \bar, etc.
1601 if (Body[Pos] == '\\' && Pos + 1 != End)
1602 break;
1603 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001604 }
1605
1606 // Add the prefix.
1607 OS << Body.slice(0, Pos);
1608
1609 // Check if we reached the end.
1610 if (Pos == End)
1611 break;
1612
Rafael Espindola65366442011-06-05 02:43:45 +00001613 if (!NParameters) {
1614 switch (Body[Pos+1]) {
1615 // $$ => $
1616 case '$':
1617 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001618 break;
1619
Rafael Espindola65366442011-06-05 02:43:45 +00001620 // $n => number of arguments
1621 case 'n':
1622 OS << A.size();
1623 break;
1624
1625 // $[0-9] => argument
1626 default: {
1627 // Missing arguments are ignored.
1628 unsigned Index = Body[Pos+1] - '0';
1629 if (Index >= A.size())
1630 break;
1631
1632 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001633 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001634 ie = A[Index].end(); it != ie; ++it)
1635 OS << it->getString();
1636 break;
1637 }
1638 }
1639 Pos += 2;
1640 } else {
1641 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001642 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001643 ++I;
1644
1645 const char *Begin = Body.data() + Pos +1;
1646 StringRef Argument(Begin, I - (Pos +1));
1647 unsigned Index = 0;
1648 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001649 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001650 break;
1651
Preston Gurd7b6f2032012-09-19 20:36:12 +00001652 if (Index == NParameters) {
1653 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1654 Pos += 3;
1655 else {
1656 OS << '\\' << Argument;
1657 Pos = I;
1658 }
1659 } else {
1660 for (MacroArgument::const_iterator it = A[Index].begin(),
1661 ie = A[Index].end(); it != ie; ++it)
1662 if (it->getKind() == AsmToken::String)
1663 OS << it->getStringContents();
1664 else
1665 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001666
Preston Gurd7b6f2032012-09-19 20:36:12 +00001667 Pos += 1 + Argument.size();
1668 }
Rafael Espindola65366442011-06-05 02:43:45 +00001669 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001670 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001671 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001672 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001673
Rafael Espindola65366442011-06-05 02:43:45 +00001674 return false;
1675}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001676
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001677MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1678 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001679 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001680 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1681 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001682{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001683}
1684
Preston Gurd7b6f2032012-09-19 20:36:12 +00001685static bool IsOperator(AsmToken::TokenKind kind)
1686{
1687 switch (kind)
1688 {
1689 default:
1690 return false;
1691 case AsmToken::Plus:
1692 case AsmToken::Minus:
1693 case AsmToken::Tilde:
1694 case AsmToken::Slash:
1695 case AsmToken::Star:
1696 case AsmToken::Dot:
1697 case AsmToken::Equal:
1698 case AsmToken::EqualEqual:
1699 case AsmToken::Pipe:
1700 case AsmToken::PipePipe:
1701 case AsmToken::Caret:
1702 case AsmToken::Amp:
1703 case AsmToken::AmpAmp:
1704 case AsmToken::Exclaim:
1705 case AsmToken::ExclaimEqual:
1706 case AsmToken::Percent:
1707 case AsmToken::Less:
1708 case AsmToken::LessEqual:
1709 case AsmToken::LessLess:
1710 case AsmToken::LessGreater:
1711 case AsmToken::Greater:
1712 case AsmToken::GreaterEqual:
1713 case AsmToken::GreaterGreater:
1714 return true;
1715 }
1716}
1717
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001718/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1719/// This is used for both default macro parameter values and the
1720/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001721bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1722 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001723 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001724 unsigned AddTokens = 0;
1725
1726 // gas accepts arguments separated by whitespace, except on Darwin
1727 if (!IsDarwin)
1728 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001729
1730 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001731 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1732 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001733 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001734 }
1735
1736 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1737 // Spaces and commas cannot be mixed to delimit parameters
1738 if (ArgumentDelimiter == AsmToken::Eof)
1739 ArgumentDelimiter = AsmToken::Comma;
1740 else if (ArgumentDelimiter != AsmToken::Comma) {
1741 Lexer.setSkipSpace(true);
1742 return TokError("expected ' ' for macro argument separator");
1743 }
1744 break;
1745 }
1746
1747 if (Lexer.is(AsmToken::Space)) {
1748 Lex(); // Eat spaces
1749
1750 // Spaces can delimit parameters, but could also be part an expression.
1751 // If the token after a space is an operator, add the token and the next
1752 // one into this argument
1753 if (ArgumentDelimiter == AsmToken::Space ||
1754 ArgumentDelimiter == AsmToken::Eof) {
1755 if (IsOperator(Lexer.getKind())) {
1756 // Check to see whether the token is used as an operator,
1757 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001758 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001759 if (*NextChar == ' ')
1760 AddTokens = 2;
1761 }
1762
1763 if (!AddTokens && ParenLevel == 0) {
1764 if (ArgumentDelimiter == AsmToken::Eof &&
1765 !IsOperator(Lexer.getKind()))
1766 ArgumentDelimiter = AsmToken::Space;
1767 break;
1768 }
1769 }
1770 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001771
1772 // HandleMacroEntry relies on not advancing the lexer here
1773 // to be able to fill in the remaining default parameter values
1774 if (Lexer.is(AsmToken::EndOfStatement))
1775 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001776
1777 // Adjust the current parentheses level.
1778 if (Lexer.is(AsmToken::LParen))
1779 ++ParenLevel;
1780 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1781 --ParenLevel;
1782
1783 // Append the token to the current argument list.
1784 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001785 if (AddTokens)
1786 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001787 Lex();
1788 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001789
1790 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001791 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001792 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001793 return false;
1794}
1795
1796// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001797bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001798 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001799 // Argument delimiter is initially unknown. It will be set by
1800 // ParseMacroArgument()
1801 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001802
1803 // Parse two kinds of macro invocations:
1804 // - macros defined without any parameters accept an arbitrary number of them
1805 // - macros defined with parameters accept at most that many of them
1806 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1807 ++Parameter) {
1808 MacroArgument MA;
1809
Preston Gurd7b6f2032012-09-19 20:36:12 +00001810 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001811 return true;
1812
Preston Gurd6c9176a2012-09-19 20:29:04 +00001813 if (!MA.empty() || !NParameters)
1814 A.push_back(MA);
1815 else if (NParameters) {
1816 if (!M->Parameters[Parameter].second.empty())
1817 A.push_back(M->Parameters[Parameter].second);
1818 }
Jim Grosbach97146442012-07-30 22:44:17 +00001819
Preston Gurd6c9176a2012-09-19 20:29:04 +00001820 // At the end of the statement, fill in remaining arguments that have
1821 // default values. If there aren't any, then the next argument is
1822 // required but missing
1823 if (Lexer.is(AsmToken::EndOfStatement)) {
1824 if (NParameters && Parameter < NParameters - 1) {
1825 if (M->Parameters[Parameter + 1].second.empty())
1826 return TokError("macro argument '" +
1827 Twine(M->Parameters[Parameter + 1].first) +
1828 "' is missing");
1829 else
1830 continue;
1831 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001832 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001833 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001834
1835 if (Lexer.is(AsmToken::Comma))
1836 Lex();
1837 }
1838 return TokError("Too many arguments");
1839}
1840
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001841bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1842 const Macro *M) {
1843 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1844 // this, although we should protect against infinite loops.
1845 if (ActiveMacros.size() == 20)
1846 return TokError("macros cannot be nested more than 20 levels deep");
1847
Rafael Espindola8a403d32012-08-08 14:51:03 +00001848 MacroArguments A;
1849 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001850 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001851
Jim Grosbach97146442012-07-30 22:44:17 +00001852 // Remove any trailing empty arguments. Do this after-the-fact as we have
1853 // to keep empty arguments in the middle of the list or positionality
1854 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001855 while (!A.empty() && A.back().empty())
1856 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001857
Rafael Espindola65366442011-06-05 02:43:45 +00001858 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1859 // to hold the macro body with substitutions.
1860 SmallString<256> Buf;
1861 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001862 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001863
Rafael Espindola8a403d32012-08-08 14:51:03 +00001864 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001865 return true;
1866
Rafael Espindola761cb062012-06-03 23:57:14 +00001867 // We include the .endmacro in the buffer as our queue to exit the macro
1868 // instantiation.
1869 OS << ".endmacro\n";
1870
Rafael Espindola65366442011-06-05 02:43:45 +00001871 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001872 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001873
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001874 // Create the macro instantiation object and add to the current macro
1875 // instantiation stack.
1876 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001877 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001878 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001879 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001880 ActiveMacros.push_back(MI);
1881
1882 // Jump to the macro instantiation and prime the lexer.
1883 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1884 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1885 Lex();
1886
1887 return false;
1888}
1889
1890void AsmParser::HandleMacroExit() {
1891 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001892 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001893 Lex();
1894
1895 // Pop the instantiation entry.
1896 delete ActiveMacros.back();
1897 ActiveMacros.pop_back();
1898}
1899
Rafael Espindolae71cc862012-01-28 05:57:00 +00001900static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001901 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001902 case MCExpr::Binary: {
1903 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1904 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001905 break;
1906 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001907 case MCExpr::Target:
1908 case MCExpr::Constant:
1909 return false;
1910 case MCExpr::SymbolRef: {
1911 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001912 if (S.isVariable())
1913 return IsUsedIn(Sym, S.getVariableValue());
1914 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001915 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001916 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001917 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001918 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001919
1920 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001921}
1922
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001923bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1924 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001925 // FIXME: Use better location, we should use proper tokens.
1926 SMLoc EqualLoc = Lexer.getLoc();
1927
Daniel Dunbar821e3332009-08-31 08:09:28 +00001928 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001929 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001930 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001931
Rafael Espindolae71cc862012-01-28 05:57:00 +00001932 // Note: we don't count b as used in "a = b". This is to allow
1933 // a = b
1934 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001935
Daniel Dunbar3f872332009-07-28 16:08:33 +00001936 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001937 return TokError("unexpected token in assignment");
1938
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001939 // Error on assignment to '.'.
1940 if (Name == ".") {
1941 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1942 "(use '.space' or '.org').)"));
1943 }
1944
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001945 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001946 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001947
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001948 // Validate that the LHS is allowed to be a variable (either it has not been
1949 // used as a symbol, or it is an absolute symbol).
1950 MCSymbol *Sym = getContext().LookupSymbol(Name);
1951 if (Sym) {
1952 // Diagnose assignment to a label.
1953 //
1954 // FIXME: Diagnostics. Note the location of the definition as a label.
1955 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001956 if (IsUsedIn(Sym, Value))
1957 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1958 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001959 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001960 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1961 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001962 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001963 return Error(EqualLoc, "redefinition of '" + Name + "'");
1964 else if (!Sym->isVariable())
1965 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001966 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001967 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1968 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001969
1970 // Don't count these checks as uses.
1971 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001972 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001973 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001974
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001975 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001976
1977 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001978 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001979 if (NoDeadStrip)
1980 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1981
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001982
1983 return false;
1984}
1985
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001986/// ParseIdentifier:
1987/// ::= identifier
1988/// ::= string
1989bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001990 // The assembler has relaxed rules for accepting identifiers, in particular we
1991 // allow things like '.globl $foo', which would normally be separate
1992 // tokens. At this level, we have already lexed so we cannot (currently)
1993 // handle this as a context dependent token, instead we detect adjacent tokens
1994 // and return the combined identifier.
1995 if (Lexer.is(AsmToken::Dollar)) {
1996 SMLoc DollarLoc = getLexer().getLoc();
1997
1998 // Consume the dollar sign, and check for a following identifier.
1999 Lex();
2000 if (Lexer.isNot(AsmToken::Identifier))
2001 return true;
2002
2003 // We have a '$' followed by an identifier, make sure they are adjacent.
2004 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2005 return true;
2006
2007 // Construct the joined identifier and consume the token.
2008 Res = StringRef(DollarLoc.getPointer(),
2009 getTok().getIdentifier().size() + 1);
2010 Lex();
2011 return false;
2012 }
2013
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002014 if (Lexer.isNot(AsmToken::Identifier) &&
2015 Lexer.isNot(AsmToken::String))
2016 return true;
2017
Sean Callanan18b83232010-01-19 21:44:56 +00002018 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002019
Sean Callanan79ed1a82010-01-19 20:22:31 +00002020 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002021
2022 return false;
2023}
2024
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002025/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002026/// ::= .equ identifier ',' expression
2027/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002028/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002029bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002030 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002031
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002032 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002033 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002034
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002035 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002036 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002037 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002038
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002039 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002040}
2041
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002042bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002043 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002044
2045 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002046 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002047 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2048 if (Str[i] != '\\') {
2049 Data += Str[i];
2050 continue;
2051 }
2052
2053 // Recognize escaped characters. Note that this escape semantics currently
2054 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2055 ++i;
2056 if (i == e)
2057 return TokError("unexpected backslash at end of string");
2058
2059 // Recognize octal sequences.
2060 if ((unsigned) (Str[i] - '0') <= 7) {
2061 // Consume up to three octal characters.
2062 unsigned Value = Str[i] - '0';
2063
2064 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2065 ++i;
2066 Value = Value * 8 + (Str[i] - '0');
2067
2068 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2069 ++i;
2070 Value = Value * 8 + (Str[i] - '0');
2071 }
2072 }
2073
2074 if (Value > 255)
2075 return TokError("invalid octal escape sequence (out of range)");
2076
2077 Data += (unsigned char) Value;
2078 continue;
2079 }
2080
2081 // Otherwise recognize individual escapes.
2082 switch (Str[i]) {
2083 default:
2084 // Just reject invalid escape sequences for now.
2085 return TokError("invalid escape sequence (unrecognized character)");
2086
2087 case 'b': Data += '\b'; break;
2088 case 'f': Data += '\f'; break;
2089 case 'n': Data += '\n'; break;
2090 case 'r': Data += '\r'; break;
2091 case 't': Data += '\t'; break;
2092 case '"': Data += '"'; break;
2093 case '\\': Data += '\\'; break;
2094 }
2095 }
2096
2097 return false;
2098}
2099
Daniel Dunbara0d14262009-06-24 23:30:00 +00002100/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002101/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2102bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002103 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002104 CheckForValidSection();
2105
Daniel Dunbara0d14262009-06-24 23:30:00 +00002106 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002107 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002108 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002109
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002110 std::string Data;
2111 if (ParseEscapedString(Data))
2112 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002113
2114 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002115 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002116 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2117
Sean Callanan79ed1a82010-01-19 20:22:31 +00002118 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002119
2120 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002121 break;
2122
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002123 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002124 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002125 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002126 }
2127 }
2128
Sean Callanan79ed1a82010-01-19 20:22:31 +00002129 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002130 return false;
2131}
2132
2133/// ParseDirectiveValue
2134/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2135bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002136 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002137 CheckForValidSection();
2138
Daniel Dunbara0d14262009-06-24 23:30:00 +00002139 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002140 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002141 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002142 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002143 return true;
2144
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002145 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002146 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2147 assert(Size <= 8 && "Invalid size");
2148 uint64_t IntValue = MCE->getValue();
2149 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2150 return Error(ExprLoc, "literal value out of range for directive");
2151 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2152 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002153 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002154
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002155 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002156 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002157
Daniel Dunbara0d14262009-06-24 23:30:00 +00002158 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002159 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002160 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002161 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002162 }
2163 }
2164
Sean Callanan79ed1a82010-01-19 20:22:31 +00002165 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002166 return false;
2167}
2168
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002169/// ParseDirectiveRealValue
2170/// ::= (.single | .double) [ expression (, expression)* ]
2171bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2172 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2173 CheckForValidSection();
2174
2175 for (;;) {
2176 // We don't truly support arithmetic on floating point expressions, so we
2177 // have to manually parse unary prefixes.
2178 bool IsNeg = false;
2179 if (getLexer().is(AsmToken::Minus)) {
2180 Lex();
2181 IsNeg = true;
2182 } else if (getLexer().is(AsmToken::Plus))
2183 Lex();
2184
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002185 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002186 getLexer().isNot(AsmToken::Real) &&
2187 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002188 return TokError("unexpected token in directive");
2189
2190 // Convert to an APFloat.
2191 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002192 StringRef IDVal = getTok().getString();
2193 if (getLexer().is(AsmToken::Identifier)) {
2194 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2195 Value = APFloat::getInf(Semantics);
2196 else if (!IDVal.compare_lower("nan"))
2197 Value = APFloat::getNaN(Semantics, false, ~0);
2198 else
2199 return TokError("invalid floating point literal");
2200 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002201 APFloat::opInvalidOp)
2202 return TokError("invalid floating point literal");
2203 if (IsNeg)
2204 Value.changeSign();
2205
2206 // Consume the numeric token.
2207 Lex();
2208
2209 // Emit the value as an integer.
2210 APInt AsInt = Value.bitcastToAPInt();
2211 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2212 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2213
2214 if (getLexer().is(AsmToken::EndOfStatement))
2215 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002216
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002217 if (getLexer().isNot(AsmToken::Comma))
2218 return TokError("unexpected token in directive");
2219 Lex();
2220 }
2221 }
2222
2223 Lex();
2224 return false;
2225}
2226
Daniel Dunbara0d14262009-06-24 23:30:00 +00002227/// ParseDirectiveSpace
2228/// ::= .space expression [ , expression ]
2229bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002230 CheckForValidSection();
2231
Daniel Dunbara0d14262009-06-24 23:30:00 +00002232 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002233 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002234 return true;
2235
2236 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002237 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2238 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002239 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002240 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002241
Daniel Dunbar475839e2009-06-29 20:37:27 +00002242 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002243 return true;
2244
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002245 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002246 return TokError("unexpected token in '.space' directive");
2247 }
2248
Sean Callanan79ed1a82010-01-19 20:22:31 +00002249 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002250
2251 if (NumBytes <= 0)
2252 return TokError("invalid number of bytes in '.space' directive");
2253
2254 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002255 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002256
2257 return false;
2258}
2259
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002260/// ParseDirectiveZero
2261/// ::= .zero expression
2262bool AsmParser::ParseDirectiveZero() {
2263 CheckForValidSection();
2264
2265 int64_t NumBytes;
2266 if (ParseAbsoluteExpression(NumBytes))
2267 return true;
2268
Rafael Espindolae452b172010-10-05 19:42:57 +00002269 int64_t Val = 0;
2270 if (getLexer().is(AsmToken::Comma)) {
2271 Lex();
2272 if (ParseAbsoluteExpression(Val))
2273 return true;
2274 }
2275
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002276 if (getLexer().isNot(AsmToken::EndOfStatement))
2277 return TokError("unexpected token in '.zero' directive");
2278
2279 Lex();
2280
Rafael Espindolae452b172010-10-05 19:42:57 +00002281 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002282
2283 return false;
2284}
2285
Daniel Dunbara0d14262009-06-24 23:30:00 +00002286/// ParseDirectiveFill
2287/// ::= .fill expression , expression , expression
2288bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002289 CheckForValidSection();
2290
Daniel Dunbara0d14262009-06-24 23:30:00 +00002291 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002292 if (ParseAbsoluteExpression(NumValues))
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 FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002300 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002301 return true;
2302
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002303 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002304 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002305 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002306
Daniel Dunbara0d14262009-06-24 23:30:00 +00002307 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002308 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002309 return true;
2310
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002311 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002312 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002313
Sean Callanan79ed1a82010-01-19 20:22:31 +00002314 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002315
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002316 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2317 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002318
2319 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002320 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002321
2322 return false;
2323}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002324
2325/// ParseDirectiveOrg
2326/// ::= .org expression [ , expression ]
2327bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002328 CheckForValidSection();
2329
Daniel Dunbar821e3332009-08-31 08:09:28 +00002330 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002331 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002332 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002333 return true;
2334
2335 // Parse optional fill expression.
2336 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002337 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2338 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002339 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002340 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002341
Daniel Dunbar475839e2009-06-29 20:37:27 +00002342 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002343 return true;
2344
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002345 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002346 return TokError("unexpected token in '.org' directive");
2347 }
2348
Sean Callanan79ed1a82010-01-19 20:22:31 +00002349 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002350
Jim Grosbachebd4c052012-01-27 00:37:08 +00002351 // Only limited forms of relocatable expressions are accepted here, it
2352 // has to be relative to the current section. The streamer will return
2353 // 'true' if the expression wasn't evaluatable.
2354 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2355 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002356
2357 return false;
2358}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002359
2360/// ParseDirectiveAlign
2361/// ::= {.align, ...} expression [ , expression [ , expression ]]
2362bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002363 CheckForValidSection();
2364
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002365 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002366 int64_t Alignment;
2367 if (ParseAbsoluteExpression(Alignment))
2368 return true;
2369
2370 SMLoc MaxBytesLoc;
2371 bool HasFillExpr = false;
2372 int64_t FillExpr = 0;
2373 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002374 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2375 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002376 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002377 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002378
2379 // The fill expression can be omitted while specifying a maximum number of
2380 // alignment bytes, e.g:
2381 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002382 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002383 HasFillExpr = true;
2384 if (ParseAbsoluteExpression(FillExpr))
2385 return true;
2386 }
2387
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002388 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2389 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002390 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002391 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002392
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002393 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002394 if (ParseAbsoluteExpression(MaxBytesToFill))
2395 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002396
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002397 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002398 return TokError("unexpected token in directive");
2399 }
2400 }
2401
Sean Callanan79ed1a82010-01-19 20:22:31 +00002402 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002403
Daniel Dunbar648ac512010-05-17 21:54:30 +00002404 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002405 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002406
2407 // Compute alignment in bytes.
2408 if (IsPow2) {
2409 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002410 if (Alignment >= 32) {
2411 Error(AlignmentLoc, "invalid alignment value");
2412 Alignment = 31;
2413 }
2414
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002415 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002416 }
2417
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002418 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002419 if (MaxBytesLoc.isValid()) {
2420 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002421 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2422 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002423 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002424 }
2425
2426 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002427 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2428 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002429 MaxBytesToFill = 0;
2430 }
2431 }
2432
Daniel Dunbar648ac512010-05-17 21:54:30 +00002433 // Check whether we should use optimal code alignment for this .align
2434 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002435 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002436 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2437 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002438 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002439 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002440 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002441 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2442 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002443 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002444
2445 return false;
2446}
2447
Eli Bendersky4766ef42012-12-20 19:05:53 +00002448
2449/// ParseDirectiveBundleAlignMode
2450/// ::= {.bundle_align_mode} expression
2451bool AsmParser::ParseDirectiveBundleAlignMode() {
2452 CheckForValidSection();
2453
2454 // Expect a single argument: an expression that evaluates to a constant
2455 // in the inclusive range 0-30.
2456 SMLoc ExprLoc = getLexer().getLoc();
2457 int64_t AlignSizePow2;
2458 if (ParseAbsoluteExpression(AlignSizePow2))
2459 return true;
2460 else if (getLexer().isNot(AsmToken::EndOfStatement))
2461 return TokError("unexpected token after expression in"
2462 " '.bundle_align_mode' directive");
2463 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2464 return Error(ExprLoc,
2465 "invalid bundle alignment size (expected between 0 and 30)");
2466
2467 Lex();
2468
2469 // Because of AlignSizePow2's verified range we can safely truncate it to
2470 // unsigned.
2471 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2472 return false;
2473}
2474
2475/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00002476/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00002477bool AsmParser::ParseDirectiveBundleLock() {
2478 CheckForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00002479 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00002480
Eli Bendersky6c1d4972013-01-07 21:51:08 +00002481 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2482 StringRef Option;
2483 SMLoc Loc = getTok().getLoc();
2484 const char *kInvalidOptionError =
2485 "invalid option for '.bundle_lock' directive";
2486
2487 if (ParseIdentifier(Option))
2488 return Error(Loc, kInvalidOptionError);
2489
2490 if (Option != "align_to_end")
2491 return Error(Loc, kInvalidOptionError);
2492 else if (getLexer().isNot(AsmToken::EndOfStatement))
2493 return Error(Loc,
2494 "unexpected token after '.bundle_lock' directive option");
2495 AlignToEnd = true;
2496 }
2497
Eli Bendersky4766ef42012-12-20 19:05:53 +00002498 Lex();
2499
Eli Bendersky6c1d4972013-01-07 21:51:08 +00002500 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00002501 return false;
2502}
2503
2504/// ParseDirectiveBundleLock
2505/// ::= {.bundle_lock}
2506bool AsmParser::ParseDirectiveBundleUnlock() {
2507 CheckForValidSection();
2508
2509 if (getLexer().isNot(AsmToken::EndOfStatement))
2510 return TokError("unexpected token in '.bundle_unlock' directive");
2511 Lex();
2512
2513 getStreamer().EmitBundleUnlock();
2514 return false;
2515}
2516
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002517/// ParseDirectiveSymbolAttribute
2518/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002519bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002520 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002521 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002522 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002523 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002524
2525 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002526 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002527
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002528 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002529
Jim Grosbach10ec6502011-09-15 17:56:49 +00002530 // Assembler local symbols don't make any sense here. Complain loudly.
2531 if (Sym->isTemporary())
2532 return Error(Loc, "non-local symbol required in directive");
2533
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002534 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002535
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002536 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002537 break;
2538
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002539 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002540 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002541 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002542 }
2543 }
2544
Sean Callanan79ed1a82010-01-19 20:22:31 +00002545 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002546 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002547}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002548
2549/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002550/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2551bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002552 CheckForValidSection();
2553
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002554 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002555 StringRef Name;
2556 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002557 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002558
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002559 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002560 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002561
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002562 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002563 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002564 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002565
2566 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002567 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002568 if (ParseAbsoluteExpression(Size))
2569 return true;
2570
2571 int64_t Pow2Alignment = 0;
2572 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002573 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002574 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002575 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002576 if (ParseAbsoluteExpression(Pow2Alignment))
2577 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002578
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002579 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2580 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002581 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2582
Chris Lattner258281d2010-01-19 06:22:22 +00002583 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002584 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2585 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002586 if (!isPowerOf2_64(Pow2Alignment))
2587 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2588 Pow2Alignment = Log2_64(Pow2Alignment);
2589 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002590 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002591
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002592 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002593 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002594
Sean Callanan79ed1a82010-01-19 20:22:31 +00002595 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002596
Chris Lattner1fc3d752009-07-09 17:25:12 +00002597 // NOTE: a size of zero for a .comm should create a undefined symbol
2598 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002599 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002600 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2601 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002602
Eric Christopherc260a3e2010-05-14 01:38:54 +00002603 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002604 // may internally end up wanting an alignment in bytes.
2605 // FIXME: Diagnose overflow.
2606 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002607 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2608 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002609
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002610 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002611 return Error(IDLoc, "invalid symbol redefinition");
2612
Chris Lattner1fc3d752009-07-09 17:25:12 +00002613 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002614 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002615 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002616 return false;
2617 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002618
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002619 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002620 return false;
2621}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002622
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002623/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002624/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002625bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002626 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002627 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002628
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002629 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002630 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002631 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002632
Sean Callanan79ed1a82010-01-19 20:22:31 +00002633 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002634
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002635 if (Str.empty())
2636 Error(Loc, ".abort detected. Assembly stopping.");
2637 else
2638 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002639 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002640
2641 return false;
2642}
Kevin Enderby71148242009-07-14 21:35:03 +00002643
Kevin Enderby1f049b22009-07-14 23:21:55 +00002644/// ParseDirectiveInclude
2645/// ::= .include "filename"
2646bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002647 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002648 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002649
Sean Callanan18b83232010-01-19 21:44:56 +00002650 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002651 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002652 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002653
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002654 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002655 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002656
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002657 // Strip the quotes.
2658 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002659
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002660 // Attempt to switch the lexer to the included file before consuming the end
2661 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002662 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002663 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002664 return true;
2665 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002666
2667 return false;
2668}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002669
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002670/// ParseDirectiveIncbin
2671/// ::= .incbin "filename"
2672bool AsmParser::ParseDirectiveIncbin() {
2673 if (getLexer().isNot(AsmToken::String))
2674 return TokError("expected string in '.incbin' directive");
2675
2676 std::string Filename = getTok().getString();
2677 SMLoc IncbinLoc = getLexer().getLoc();
2678 Lex();
2679
2680 if (getLexer().isNot(AsmToken::EndOfStatement))
2681 return TokError("unexpected token in '.incbin' directive");
2682
2683 // Strip the quotes.
2684 Filename = Filename.substr(1, Filename.size()-2);
2685
2686 // Attempt to process the included file.
2687 if (ProcessIncbinFile(Filename)) {
2688 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2689 return true;
2690 }
2691
2692 return false;
2693}
2694
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002695/// ParseDirectiveIf
2696/// ::= .if expression
2697bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002698 TheCondStack.push_back(TheCondState);
2699 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002700 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002701 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002702 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002703 int64_t ExprValue;
2704 if (ParseAbsoluteExpression(ExprValue))
2705 return true;
2706
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002707 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002708 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002709
Sean Callanan79ed1a82010-01-19 20:22:31 +00002710 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002711
2712 TheCondState.CondMet = ExprValue;
2713 TheCondState.Ignore = !TheCondState.CondMet;
2714 }
2715
2716 return false;
2717}
2718
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002719/// ParseDirectiveIfb
2720/// ::= .ifb string
2721bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2722 TheCondStack.push_back(TheCondState);
2723 TheCondState.TheCond = AsmCond::IfCond;
2724
Benjamin Kramer29739e72012-05-12 16:52:21 +00002725 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002726 EatToEndOfStatement();
2727 } else {
2728 StringRef Str = ParseStringToEndOfStatement();
2729
2730 if (getLexer().isNot(AsmToken::EndOfStatement))
2731 return TokError("unexpected token in '.ifb' directive");
2732
2733 Lex();
2734
2735 TheCondState.CondMet = ExpectBlank == Str.empty();
2736 TheCondState.Ignore = !TheCondState.CondMet;
2737 }
2738
2739 return false;
2740}
2741
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002742/// ParseDirectiveIfc
2743/// ::= .ifc string1, string2
2744bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2745 TheCondStack.push_back(TheCondState);
2746 TheCondState.TheCond = AsmCond::IfCond;
2747
Benjamin Kramer29739e72012-05-12 16:52:21 +00002748 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002749 EatToEndOfStatement();
2750 } else {
2751 StringRef Str1 = ParseStringToComma();
2752
2753 if (getLexer().isNot(AsmToken::Comma))
2754 return TokError("unexpected token in '.ifc' directive");
2755
2756 Lex();
2757
2758 StringRef Str2 = ParseStringToEndOfStatement();
2759
2760 if (getLexer().isNot(AsmToken::EndOfStatement))
2761 return TokError("unexpected token in '.ifc' directive");
2762
2763 Lex();
2764
2765 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2766 TheCondState.Ignore = !TheCondState.CondMet;
2767 }
2768
2769 return false;
2770}
2771
2772/// ParseDirectiveIfdef
2773/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002774bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2775 StringRef Name;
2776 TheCondStack.push_back(TheCondState);
2777 TheCondState.TheCond = AsmCond::IfCond;
2778
2779 if (TheCondState.Ignore) {
2780 EatToEndOfStatement();
2781 } else {
2782 if (ParseIdentifier(Name))
2783 return TokError("expected identifier after '.ifdef'");
2784
2785 Lex();
2786
2787 MCSymbol *Sym = getContext().LookupSymbol(Name);
2788
2789 if (expect_defined)
2790 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2791 else
2792 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2793 TheCondState.Ignore = !TheCondState.CondMet;
2794 }
2795
2796 return false;
2797}
2798
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002799/// ParseDirectiveElseIf
2800/// ::= .elseif expression
2801bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2802 if (TheCondState.TheCond != AsmCond::IfCond &&
2803 TheCondState.TheCond != AsmCond::ElseIfCond)
2804 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2805 " an .elseif");
2806 TheCondState.TheCond = AsmCond::ElseIfCond;
2807
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002808 bool LastIgnoreState = false;
2809 if (!TheCondStack.empty())
2810 LastIgnoreState = TheCondStack.back().Ignore;
2811 if (LastIgnoreState || TheCondState.CondMet) {
2812 TheCondState.Ignore = true;
2813 EatToEndOfStatement();
2814 }
2815 else {
2816 int64_t ExprValue;
2817 if (ParseAbsoluteExpression(ExprValue))
2818 return true;
2819
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002820 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002821 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002822
Sean Callanan79ed1a82010-01-19 20:22:31 +00002823 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002824 TheCondState.CondMet = ExprValue;
2825 TheCondState.Ignore = !TheCondState.CondMet;
2826 }
2827
2828 return false;
2829}
2830
2831/// ParseDirectiveElse
2832/// ::= .else
2833bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002834 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002835 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002836
Sean Callanan79ed1a82010-01-19 20:22:31 +00002837 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002838
2839 if (TheCondState.TheCond != AsmCond::IfCond &&
2840 TheCondState.TheCond != AsmCond::ElseIfCond)
2841 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2842 ".elseif");
2843 TheCondState.TheCond = AsmCond::ElseCond;
2844 bool LastIgnoreState = false;
2845 if (!TheCondStack.empty())
2846 LastIgnoreState = TheCondStack.back().Ignore;
2847 if (LastIgnoreState || TheCondState.CondMet)
2848 TheCondState.Ignore = true;
2849 else
2850 TheCondState.Ignore = false;
2851
2852 return false;
2853}
2854
2855/// ParseDirectiveEndIf
2856/// ::= .endif
2857bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002858 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002859 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002860
Sean Callanan79ed1a82010-01-19 20:22:31 +00002861 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002862
2863 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2864 TheCondStack.empty())
2865 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2866 ".else");
2867 if (!TheCondStack.empty()) {
2868 TheCondState = TheCondStack.back();
2869 TheCondStack.pop_back();
2870 }
2871
2872 return false;
2873}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002874
2875/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002876/// ::= .file [number] filename
2877/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002878bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002879 // FIXME: I'm not sure what this is.
2880 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002881 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002882 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002883 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002884 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002885
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002886 if (FileNumber < 1)
2887 return TokError("file number less than one");
2888 }
2889
Daniel Dunbareceec052010-07-12 17:45:27 +00002890 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002891 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002892
Nick Lewycky44d798d2011-10-17 23:05:28 +00002893 // Usually the directory and filename together, otherwise just the directory.
2894 StringRef Path = getTok().getString();
2895 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002896 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002897
Nick Lewycky44d798d2011-10-17 23:05:28 +00002898 StringRef Directory;
2899 StringRef Filename;
2900 if (getLexer().is(AsmToken::String)) {
2901 if (FileNumber == -1)
2902 return TokError("explicit path specified, but no file number");
2903 Filename = getTok().getString();
2904 Filename = Filename.substr(1, Filename.size()-2);
2905 Directory = Path;
2906 Lex();
2907 } else {
2908 Filename = Path;
2909 }
2910
Daniel Dunbareceec052010-07-12 17:45:27 +00002911 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002912 return TokError("unexpected token in '.file' directive");
2913
Chris Lattnerd32e8032010-01-25 19:02:58 +00002914 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002915 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002916 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002917 if (getContext().getGenDwarfForAssembly() == true)
2918 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2919 "used to generate dwarf debug info for assembly code");
2920
Nick Lewycky44d798d2011-10-17 23:05:28 +00002921 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002922 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002923 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002924
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002925 return false;
2926}
2927
2928/// ParseDirectiveLine
2929/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002930bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002931 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2932 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002933 return TokError("unexpected token in '.line' directive");
2934
Sean Callanan18b83232010-01-19 21:44:56 +00002935 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002936 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002937 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002938
2939 // FIXME: Do something with the .line.
2940 }
2941
Daniel Dunbareceec052010-07-12 17:45:27 +00002942 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002943 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002944
2945 return false;
2946}
2947
2948
2949/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002950/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002951/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2952/// The first number is a file number, must have been previously assigned with
2953/// a .file directive, the second number is the line number and optionally the
2954/// third number is a column position (zero if not specified). The remaining
2955/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002956bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002957
Daniel Dunbareceec052010-07-12 17:45:27 +00002958 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002959 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002960 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002961 if (FileNumber < 1)
2962 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002963 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002964 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002965 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002966
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002967 int64_t LineNumber = 0;
2968 if (getLexer().is(AsmToken::Integer)) {
2969 LineNumber = getTok().getIntVal();
2970 if (LineNumber < 1)
2971 return TokError("line number less than one in '.loc' directive");
2972 Lex();
2973 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002974
2975 int64_t ColumnPos = 0;
2976 if (getLexer().is(AsmToken::Integer)) {
2977 ColumnPos = getTok().getIntVal();
2978 if (ColumnPos < 0)
2979 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002980 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002981 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002982
Kevin Enderbyc0957932010-09-30 16:52:03 +00002983 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002984 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002985 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002986 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2987 for (;;) {
2988 if (getLexer().is(AsmToken::EndOfStatement))
2989 break;
2990
2991 StringRef Name;
2992 SMLoc Loc = getTok().getLoc();
2993 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002994 return TokError("unexpected token in '.loc' directive");
2995
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002996 if (Name == "basic_block")
2997 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2998 else if (Name == "prologue_end")
2999 Flags |= DWARF2_FLAG_PROLOGUE_END;
3000 else if (Name == "epilogue_begin")
3001 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3002 else if (Name == "is_stmt") {
Jordan Rose3ebe59c2013-01-07 19:00:49 +00003003 Loc = getTok().getLoc();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003004 const MCExpr *Value;
3005 if (getParser().ParseExpression(Value))
3006 return true;
3007 // The expression must be the constant 0 or 1.
3008 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3009 int Value = MCE->getValue();
3010 if (Value == 0)
3011 Flags &= ~DWARF2_FLAG_IS_STMT;
3012 else if (Value == 1)
3013 Flags |= DWARF2_FLAG_IS_STMT;
3014 else
3015 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003016 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003017 else {
3018 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3019 }
3020 }
3021 else if (Name == "isa") {
Jordan Rose3ebe59c2013-01-07 19:00:49 +00003022 Loc = getTok().getLoc();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003023 const MCExpr *Value;
3024 if (getParser().ParseExpression(Value))
3025 return true;
3026 // The expression must be a constant greater or equal to 0.
3027 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3028 int Value = MCE->getValue();
3029 if (Value < 0)
3030 return Error(Loc, "isa number less than zero");
3031 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003032 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003033 else {
3034 return Error(Loc, "isa number not a constant value");
3035 }
3036 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00003037 else if (Name == "discriminator") {
3038 if (getParser().ParseAbsoluteExpression(Discriminator))
3039 return true;
3040 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003041 else {
3042 return Error(Loc, "unknown sub-directive in '.loc' directive");
3043 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003044
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003045 if (getLexer().is(AsmToken::EndOfStatement))
3046 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003047 }
3048 }
3049
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00003050 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00003051 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003052
3053 return false;
3054}
3055
Daniel Dunbar138abae2010-10-16 04:56:42 +00003056/// ParseDirectiveStabs
3057/// ::= .stabs string, number, number, number
3058bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3059 SMLoc DirectiveLoc) {
3060 return TokError("unsupported directive '" + Directive + "'");
3061}
3062
Rafael Espindolaf9efd832011-05-10 01:10:18 +00003063/// ParseDirectiveCFISections
3064/// ::= .cfi_sections section [, section]
3065bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3066 SMLoc DirectiveLoc) {
3067 StringRef Name;
3068 bool EH = false;
3069 bool Debug = false;
3070
3071 if (getParser().ParseIdentifier(Name))
3072 return TokError("Expected an identifier");
3073
3074 if (Name == ".eh_frame")
3075 EH = true;
3076 else if (Name == ".debug_frame")
3077 Debug = true;
3078
3079 if (getLexer().is(AsmToken::Comma)) {
3080 Lex();
3081
3082 if (getParser().ParseIdentifier(Name))
3083 return TokError("Expected an identifier");
3084
3085 if (Name == ".eh_frame")
3086 EH = true;
3087 else if (Name == ".debug_frame")
3088 Debug = true;
3089 }
3090
3091 getStreamer().EmitCFISections(EH, Debug);
3092
3093 return false;
3094}
3095
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003096/// ParseDirectiveCFIStartProc
3097/// ::= .cfi_startproc
3098bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3099 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003100 getStreamer().EmitCFIStartProc();
3101 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003102}
3103
3104/// ParseDirectiveCFIEndProc
3105/// ::= .cfi_endproc
3106bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003107 getStreamer().EmitCFIEndProc();
3108 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003109}
3110
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003111/// ParseRegisterOrRegisterNumber - parse register name or number.
3112bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3113 SMLoc DirectiveLoc) {
3114 unsigned RegNo;
3115
Jim Grosbach6f888a82011-06-02 17:14:04 +00003116 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003117 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3118 DirectiveLoc))
3119 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00003120 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003121 } else
3122 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00003123
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003124 return false;
3125}
3126
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003127/// ParseDirectiveCFIDefCfa
3128/// ::= .cfi_def_cfa register, offset
3129bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3130 SMLoc DirectiveLoc) {
3131 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003132 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003133 return true;
3134
3135 if (getLexer().isNot(AsmToken::Comma))
3136 return TokError("unexpected token in directive");
3137 Lex();
3138
3139 int64_t Offset = 0;
3140 if (getParser().ParseAbsoluteExpression(Offset))
3141 return true;
3142
Rafael Espindola066c2f42011-04-12 23:59:07 +00003143 getStreamer().EmitCFIDefCfa(Register, Offset);
3144 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003145}
3146
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003147/// ParseDirectiveCFIDefCfaOffset
3148/// ::= .cfi_def_cfa_offset offset
3149bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3150 SMLoc DirectiveLoc) {
3151 int64_t Offset = 0;
3152 if (getParser().ParseAbsoluteExpression(Offset))
3153 return true;
3154
Rafael Espindola066c2f42011-04-12 23:59:07 +00003155 getStreamer().EmitCFIDefCfaOffset(Offset);
3156 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003157}
3158
3159/// ParseDirectiveCFIAdjustCfaOffset
3160/// ::= .cfi_adjust_cfa_offset adjustment
3161bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3162 SMLoc DirectiveLoc) {
3163 int64_t Adjustment = 0;
3164 if (getParser().ParseAbsoluteExpression(Adjustment))
3165 return true;
3166
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003167 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3168 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003169}
3170
3171/// ParseDirectiveCFIDefCfaRegister
3172/// ::= .cfi_def_cfa_register register
3173bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3174 SMLoc DirectiveLoc) {
3175 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003176 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003177 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003178
Rafael Espindola066c2f42011-04-12 23:59:07 +00003179 getStreamer().EmitCFIDefCfaRegister(Register);
3180 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003181}
3182
3183/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003184/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003185bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3186 int64_t Register = 0;
3187 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003188
3189 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003190 return true;
3191
3192 if (getLexer().isNot(AsmToken::Comma))
3193 return TokError("unexpected token in directive");
3194 Lex();
3195
3196 if (getParser().ParseAbsoluteExpression(Offset))
3197 return true;
3198
Rafael Espindola066c2f42011-04-12 23:59:07 +00003199 getStreamer().EmitCFIOffset(Register, Offset);
3200 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003201}
3202
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003203/// ParseDirectiveCFIRelOffset
3204/// ::= .cfi_rel_offset register, offset
3205bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3206 SMLoc DirectiveLoc) {
3207 int64_t Register = 0;
3208
3209 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3210 return true;
3211
3212 if (getLexer().isNot(AsmToken::Comma))
3213 return TokError("unexpected token in directive");
3214 Lex();
3215
3216 int64_t Offset = 0;
3217 if (getParser().ParseAbsoluteExpression(Offset))
3218 return true;
3219
Rafael Espindola25f492e2011-04-12 16:12:03 +00003220 getStreamer().EmitCFIRelOffset(Register, Offset);
3221 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003222}
3223
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003224static bool isValidEncoding(int64_t Encoding) {
3225 if (Encoding & ~0xff)
3226 return false;
3227
3228 if (Encoding == dwarf::DW_EH_PE_omit)
3229 return true;
3230
3231 const unsigned Format = Encoding & 0xf;
3232 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3233 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3234 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3235 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3236 return false;
3237
Rafael Espindolacaf11582010-12-29 04:31:26 +00003238 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003239 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003240 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003241 return false;
3242
3243 return true;
3244}
3245
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003246/// ParseDirectiveCFIPersonalityOrLsda
3247/// ::= .cfi_personality encoding, [symbol_name]
3248/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003249bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003250 SMLoc DirectiveLoc) {
3251 int64_t Encoding = 0;
3252 if (getParser().ParseAbsoluteExpression(Encoding))
3253 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003254 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003255 return false;
3256
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003257 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003258 return TokError("unsupported encoding.");
3259
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003260 if (getLexer().isNot(AsmToken::Comma))
3261 return TokError("unexpected token in directive");
3262 Lex();
3263
3264 StringRef Name;
3265 if (getParser().ParseIdentifier(Name))
3266 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003267
3268 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3269
3270 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003271 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003272 else {
3273 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003274 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003275 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003276 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003277}
3278
Rafael Espindolafe024d02010-12-28 18:36:23 +00003279/// ParseDirectiveCFIRememberState
3280/// ::= .cfi_remember_state
3281bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3282 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003283 getStreamer().EmitCFIRememberState();
3284 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003285}
3286
3287/// ParseDirectiveCFIRestoreState
3288/// ::= .cfi_remember_state
3289bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3290 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003291 getStreamer().EmitCFIRestoreState();
3292 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003293}
3294
Rafael Espindolac5754392011-04-12 15:31:05 +00003295/// ParseDirectiveCFISameValue
3296/// ::= .cfi_same_value register
3297bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3298 SMLoc DirectiveLoc) {
3299 int64_t Register = 0;
3300
3301 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3302 return true;
3303
3304 getStreamer().EmitCFISameValue(Register);
3305
3306 return false;
3307}
3308
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003309/// ParseDirectiveCFIRestore
3310/// ::= .cfi_restore register
3311bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003312 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003313 int64_t Register = 0;
3314 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3315 return true;
3316
3317 getStreamer().EmitCFIRestore(Register);
3318
3319 return false;
3320}
3321
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003322/// ParseDirectiveCFIEscape
3323/// ::= .cfi_escape expression[,...]
3324bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003325 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003326 std::string Values;
3327 int64_t CurrValue;
3328 if (getParser().ParseAbsoluteExpression(CurrValue))
3329 return true;
3330
3331 Values.push_back((uint8_t)CurrValue);
3332
3333 while (getLexer().is(AsmToken::Comma)) {
3334 Lex();
3335
3336 if (getParser().ParseAbsoluteExpression(CurrValue))
3337 return true;
3338
3339 Values.push_back((uint8_t)CurrValue);
3340 }
3341
3342 getStreamer().EmitCFIEscape(Values);
3343 return false;
3344}
3345
Rafael Espindola16d7d432012-01-23 21:51:52 +00003346/// ParseDirectiveCFISignalFrame
3347/// ::= .cfi_signal_frame
3348bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3349 SMLoc DirectiveLoc) {
3350 if (getLexer().isNot(AsmToken::EndOfStatement))
3351 return Error(getLexer().getLoc(),
3352 "unexpected token in '" + Directive + "' directive");
3353
3354 getStreamer().EmitCFISignalFrame();
3355
3356 return false;
3357}
3358
Rafael Espindolac8fec7e2012-11-23 16:59:41 +00003359/// ParseDirectiveCFIUndefined
3360/// ::= .cfi_undefined register
3361bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3362 SMLoc DirectiveLoc) {
3363 int64_t Register = 0;
3364
3365 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3366 return true;
3367
3368 getStreamer().EmitCFIUndefined(Register);
3369
3370 return false;
3371}
3372
Rafael Espindolaf4f14f62012-11-25 15:14:49 +00003373/// ParseDirectiveCFIRegister
3374/// ::= .cfi_register register, register
3375bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3376 SMLoc DirectiveLoc) {
3377 int64_t Register1 = 0;
3378
3379 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3380 return true;
3381
3382 if (getLexer().isNot(AsmToken::Comma))
3383 return TokError("unexpected token in directive");
3384 Lex();
3385
3386 int64_t Register2 = 0;
3387
3388 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3389 return true;
3390
3391 getStreamer().EmitCFIRegister(Register1, Register2);
3392
3393 return false;
3394}
3395
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003396/// ParseDirectiveMacrosOnOff
3397/// ::= .macros_on
3398/// ::= .macros_off
3399bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3400 SMLoc DirectiveLoc) {
3401 if (getLexer().isNot(AsmToken::EndOfStatement))
3402 return Error(getLexer().getLoc(),
3403 "unexpected token in '" + Directive + "' directive");
3404
3405 getParser().MacrosEnabled = Directive == ".macros_on";
3406
3407 return false;
3408}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003409
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003410/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003411/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003412bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3413 SMLoc DirectiveLoc) {
3414 StringRef Name;
3415 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003416 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003417
Rafael Espindola8a403d32012-08-08 14:51:03 +00003418 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003419 // Argument delimiter is initially unknown. It will be set by
3420 // ParseMacroArgument()
3421 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003422 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003423 for (;;) {
3424 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003425 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003426 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003427
3428 if (getLexer().is(AsmToken::Equal)) {
3429 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003430 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003431 return true;
3432 }
3433
Rafael Espindola65366442011-06-05 02:43:45 +00003434 Parameters.push_back(Parameter);
3435
Preston Gurd7b6f2032012-09-19 20:36:12 +00003436 if (getLexer().is(AsmToken::Comma))
3437 Lex();
3438 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003439 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003440 }
3441 }
3442
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003443 // Eat the end of statement.
3444 Lex();
3445
3446 AsmToken EndToken, StartToken = getTok();
3447
3448 // Lex the macro definition.
3449 for (;;) {
3450 // Check whether we have reached the end of the file.
3451 if (getLexer().is(AsmToken::Eof))
3452 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3453
3454 // Otherwise, check whether we have reach the .endmacro.
3455 if (getLexer().is(AsmToken::Identifier) &&
3456 (getTok().getIdentifier() == ".endm" ||
3457 getTok().getIdentifier() == ".endmacro")) {
3458 EndToken = getTok();
3459 Lex();
3460 if (getLexer().isNot(AsmToken::EndOfStatement))
3461 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3462 "' directive");
3463 break;
3464 }
3465
3466 // Otherwise, scan til the end of the statement.
3467 getParser().EatToEndOfStatement();
3468 }
3469
3470 if (getParser().MacroMap.lookup(Name)) {
3471 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3472 }
3473
3474 const char *BodyStart = StartToken.getLoc().getPointer();
3475 const char *BodyEnd = EndToken.getLoc().getPointer();
3476 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003477 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003478 return false;
3479}
3480
3481/// ParseDirectiveEndMacro
3482/// ::= .endm
3483/// ::= .endmacro
3484bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003485 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003486 if (getLexer().isNot(AsmToken::EndOfStatement))
3487 return TokError("unexpected token in '" + Directive + "' directive");
3488
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003489 // If we are inside a macro instantiation, terminate the current
3490 // instantiation.
3491 if (!getParser().ActiveMacros.empty()) {
3492 getParser().HandleMacroExit();
3493 return false;
3494 }
3495
3496 // Otherwise, this .endmacro is a stray entry in the file; well formed
3497 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003498 return TokError("unexpected '" + Directive + "' in file, "
3499 "no current macro definition");
3500}
3501
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003502/// ParseDirectivePurgeMacro
3503/// ::= .purgem
3504bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3505 SMLoc DirectiveLoc) {
3506 StringRef Name;
3507 if (getParser().ParseIdentifier(Name))
3508 return TokError("expected identifier in '.purgem' directive");
3509
3510 if (getLexer().isNot(AsmToken::EndOfStatement))
3511 return TokError("unexpected token in '.purgem' directive");
3512
3513 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3514 if (I == getParser().MacroMap.end())
3515 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3516
3517 // Undefine the macro.
3518 delete I->getValue();
3519 getParser().MacroMap.erase(I);
3520 return false;
3521}
3522
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003523bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003524 getParser().CheckForValidSection();
3525
3526 const MCExpr *Value;
3527
3528 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003529 return true;
3530
3531 if (getLexer().isNot(AsmToken::EndOfStatement))
3532 return TokError("unexpected token in directive");
3533
3534 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003535 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003536 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003537 getStreamer().EmitULEB128Value(Value);
3538
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003539 return false;
3540}
3541
Rafael Espindola761cb062012-06-03 23:57:14 +00003542Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003543 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003544
Rafael Espindola761cb062012-06-03 23:57:14 +00003545 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003546 for (;;) {
3547 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003548 if (getLexer().is(AsmToken::Eof)) {
3549 Error(DirectiveLoc, "no matching '.endr' in definition");
3550 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003551 }
3552
Rafael Espindola761cb062012-06-03 23:57:14 +00003553 if (Lexer.is(AsmToken::Identifier) &&
3554 (getTok().getIdentifier() == ".rept")) {
3555 ++NestLevel;
3556 }
3557
3558 // Otherwise, check whether we have reached the .endr.
3559 if (Lexer.is(AsmToken::Identifier) &&
3560 getTok().getIdentifier() == ".endr") {
3561 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003562 EndToken = getTok();
3563 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003564 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3565 TokError("unexpected token in '.endr' directive");
3566 return 0;
3567 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003568 break;
3569 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003570 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003571 }
3572
Rafael Espindola761cb062012-06-03 23:57:14 +00003573 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003574 EatToEndOfStatement();
3575 }
3576
3577 const char *BodyStart = StartToken.getLoc().getPointer();
3578 const char *BodyEnd = EndToken.getLoc().getPointer();
3579 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3580
Rafael Espindola761cb062012-06-03 23:57:14 +00003581 // We Are Anonymous.
3582 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003583 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003584 return new Macro(Name, Body, Parameters);
3585}
3586
3587void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3588 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003589 OS << ".endr\n";
3590
3591 MemoryBuffer *Instantiation =
3592 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3593
Rafael Espindola761cb062012-06-03 23:57:14 +00003594 // Create the macro instantiation object and add to the current macro
3595 // instantiation stack.
3596 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003597 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003598 getTok().getLoc(),
3599 Instantiation);
3600 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003601
Rafael Espindola761cb062012-06-03 23:57:14 +00003602 // Jump to the macro instantiation and prime the lexer.
3603 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3604 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3605 Lex();
3606}
3607
3608bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3609 int64_t Count;
3610 if (ParseAbsoluteExpression(Count))
3611 return TokError("unexpected token in '.rept' directive");
3612
3613 if (Count < 0)
3614 return TokError("Count is negative");
3615
3616 if (Lexer.isNot(AsmToken::EndOfStatement))
3617 return TokError("unexpected token in '.rept' directive");
3618
3619 // Eat the end of statement.
3620 Lex();
3621
3622 // Lex the rept definition.
3623 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3624 if (!M)
3625 return true;
3626
3627 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3628 // to hold the macro body with substitutions.
3629 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003630 MacroParameters Parameters;
3631 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003632 raw_svector_ostream OS(Buf);
3633 while (Count--) {
3634 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3635 return true;
3636 }
3637 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003638
3639 return false;
3640}
3641
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003642/// ParseDirectiveIrp
3643/// ::= .irp symbol,values
3644bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003645 MacroParameters Parameters;
3646 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003647
Preston Gurd6c9176a2012-09-19 20:29:04 +00003648 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003649 return TokError("expected identifier in '.irp' directive");
3650
3651 Parameters.push_back(Parameter);
3652
3653 if (Lexer.isNot(AsmToken::Comma))
3654 return TokError("expected comma in '.irp' directive");
3655
3656 Lex();
3657
Rafael Espindola8a403d32012-08-08 14:51:03 +00003658 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003659 if (ParseMacroArguments(0, A))
3660 return true;
3661
3662 // Eat the end of statement.
3663 Lex();
3664
3665 // Lex the irp definition.
3666 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3667 if (!M)
3668 return true;
3669
3670 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3671 // to hold the macro body with substitutions.
3672 SmallString<256> Buf;
3673 raw_svector_ostream OS(Buf);
3674
Rafael Espindola7996d042012-08-21 16:06:48 +00003675 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3676 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003677 Args.push_back(*i);
3678
3679 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3680 return true;
3681 }
3682
3683 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3684
3685 return false;
3686}
3687
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003688/// ParseDirectiveIrpc
3689/// ::= .irpc symbol,values
3690bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003691 MacroParameters Parameters;
3692 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003693
Preston Gurd6c9176a2012-09-19 20:29:04 +00003694 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003695 return TokError("expected identifier in '.irpc' directive");
3696
3697 Parameters.push_back(Parameter);
3698
3699 if (Lexer.isNot(AsmToken::Comma))
3700 return TokError("expected comma in '.irpc' directive");
3701
3702 Lex();
3703
Rafael Espindola8a403d32012-08-08 14:51:03 +00003704 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003705 if (ParseMacroArguments(0, A))
3706 return true;
3707
3708 if (A.size() != 1 || A.front().size() != 1)
3709 return TokError("unexpected token in '.irpc' directive");
3710
3711 // Eat the end of statement.
3712 Lex();
3713
3714 // Lex the irpc definition.
3715 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3716 if (!M)
3717 return true;
3718
3719 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3720 // to hold the macro body with substitutions.
3721 SmallString<256> Buf;
3722 raw_svector_ostream OS(Buf);
3723
3724 StringRef Values = A.front().front().getString();
3725 std::size_t I, End = Values.size();
3726 for (I = 0; I < End; ++I) {
3727 MacroArgument Arg;
3728 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3729
Rafael Espindola8a403d32012-08-08 14:51:03 +00003730 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003731 Args.push_back(Arg);
3732
3733 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3734 return true;
3735 }
3736
3737 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3738
3739 return false;
3740}
3741
Rafael Espindola761cb062012-06-03 23:57:14 +00003742bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3743 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003744 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003745
3746 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003747 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003748 assert(getLexer().is(AsmToken::EndOfStatement));
3749
Rafael Espindola761cb062012-06-03 23:57:14 +00003750 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003751 return false;
3752}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003753
Eli Friedman2128aae2012-10-22 23:58:19 +00003754bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3755 const MCExpr *Value;
3756 SMLoc ExprLoc = getLexer().getLoc();
3757 if (ParseExpression(Value))
3758 return true;
3759 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3760 if (!MCE)
3761 return Error(ExprLoc, "unexpected expression in _emit");
3762 uint64_t IntValue = MCE->getValue();
3763 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3764 return Error(ExprLoc, "literal value out of range for directive");
3765
3766 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3767 return false;
3768}
3769
Chad Rosierb1f8c132012-10-18 15:49:34 +00003770bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3771 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003772 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003773 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003774 SmallVectorImpl<std::string> &Clobbers,
3775 const MCInstrInfo *MII,
3776 const MCInstPrinter *IP,
3777 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003778 SmallVector<void *, 4> InputDecls;
3779 SmallVector<void *, 4> OutputDecls;
3780 SmallVector<bool, 4> InputDeclsOffsetOf;
3781 SmallVector<bool, 4> OutputDeclsOffsetOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003782 SmallVector<std::string, 4> InputConstraints;
3783 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003784 std::set<std::string> ClobberRegs;
3785
Chad Rosier4e472d22012-10-20 01:02:45 +00003786 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003787
3788 // Prime the lexer.
3789 Lex();
3790
3791 // While we have input, parse each statement.
3792 unsigned InputIdx = 0;
3793 unsigned OutputIdx = 0;
3794 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003795 ParseStatementInfo Info(&AsmStrRewrites);
3796 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003797 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003798
Chad Rosier57498012012-12-12 22:45:52 +00003799 if (Info.ParseError)
3800 return true;
3801
Eli Friedman2128aae2012-10-22 23:58:19 +00003802 if (Info.Opcode != ~0U) {
3803 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003804
3805 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003806 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3807 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003808
3809 // Immediate.
3810 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003811 if (Operand->needAsmRewrite())
3812 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3813 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003814 continue;
3815 }
3816
3817 // Register operand.
Chad Rosierc0a14b82012-10-24 17:22:29 +00003818 if (Operand->isReg() && !Operand->isOffsetOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003819 unsigned NumDefs = Desc.getNumDefs();
3820 // Clobber.
3821 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3822 std::string Reg;
3823 raw_string_ostream OS(Reg);
3824 IP->printRegName(OS, Operand->getReg());
3825 ClobberRegs.insert(StringRef(OS.str()));
3826 }
3827 continue;
3828 }
3829
3830 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003831 unsigned Size;
3832 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3833 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003834 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003835 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc0a14b82012-10-24 17:22:29 +00003836 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003837 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003838 Operand->getStartLoc(),
3839 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003840 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003841 if (isOutput) {
3842 std::string Constraint = "=";
3843 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003844 OutputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003845 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003846 Constraint += Operand->getConstraint().str();
3847 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003848 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003849 Operand->getStartLoc(),
3850 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003851 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003852 InputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003853 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003854 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003855 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003856 Operand->getStartLoc(),
3857 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003858 }
3859 }
3860 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003861 }
3862 }
3863
3864 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003865 NumOutputs = OutputDecls.size();
3866 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003867
3868 // Set the unique clobbers.
3869 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3870 E = ClobberRegs.end(); I != E; ++I)
3871 Clobbers.push_back(*I);
3872
3873 // Merge the various outputs and inputs. Output are expected first.
3874 if (NumOutputs || NumInputs) {
3875 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003876 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003877 Constraints.resize(NumExprs);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003878 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3879 // constraint for offsetof. This needs to be cleaned up!
Chad Rosierb1f8c132012-10-18 15:49:34 +00003880 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003881 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3882 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003883 }
3884 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003885 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3886 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003887 }
3888 }
3889
3890 // Build the IR assembly string.
3891 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003892 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003893 raw_string_ostream OS(AsmStringIR);
3894 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003895 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003896 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3897 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003898
Chad Rosier4e472d22012-10-20 01:02:45 +00003899 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003900
3901 // Emit everything up to the immediate/expression. If the previous rewrite
3902 // was a size directive, then this has already been done.
3903 if (PrevKind != AOK_SizeDirective)
3904 OS << StringRef(Start, Loc - Start);
3905 PrevKind = Kind;
3906
Chad Rosier5a719fc2012-10-23 17:43:43 +00003907 // Skip the original expression.
3908 if (Kind == AOK_Skip) {
3909 Start = Loc + (*I).Len;
3910 continue;
3911 }
3912
Chad Rosierb1f8c132012-10-18 15:49:34 +00003913 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00003914 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003915 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003916 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00003917 OS << Twine("$$");
3918 OS << (*I).Val;
3919 break;
3920 case AOK_ImmPrefix:
3921 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00003922 break;
3923 case AOK_Input:
3924 OS << '$';
3925 OS << InputIdx++;
3926 break;
3927 case AOK_Output:
3928 OS << '$';
3929 OS << OutputIdx++;
3930 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00003931 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00003932 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00003933 default: break;
3934 case 8: OS << "byte ptr "; break;
3935 case 16: OS << "word ptr "; break;
3936 case 32: OS << "dword ptr "; break;
3937 case 64: OS << "qword ptr "; break;
3938 case 80: OS << "xword ptr "; break;
3939 case 128: OS << "xmmword ptr "; break;
3940 case 256: OS << "ymmword ptr "; break;
3941 }
Eli Friedman2128aae2012-10-22 23:58:19 +00003942 break;
3943 case AOK_Emit:
3944 OS << ".byte";
3945 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00003946 case AOK_DotOperator:
3947 OS << (*I).Val;
3948 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003949 }
Chad Rosier96d58e62012-10-19 20:57:14 +00003950
Chad Rosierb1f8c132012-10-18 15:49:34 +00003951 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00003952 if (Kind != AOK_SizeDirective)
3953 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003954 }
3955
3956 // Emit the remainder of the asm string.
3957 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3958 if (Start != AsmEnd)
3959 OS << StringRef(Start, AsmEnd - Start);
3960
3961 AsmString = OS.str();
3962 return false;
3963}
3964
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003965/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003966MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003967 MCContext &C, MCStreamer &Out,
3968 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003969 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003970}