blob: 7eddd341f5adb27e57cb6da77f9287e042b939bb [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.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001217 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001218
Kevin Enderby94c2e852011-12-09 18:09:40 +00001219 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001220 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001221 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001222 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1223 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001224
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001225 // Consume any end of statement token, if present, to avoid spurious
1226 // AddBlankLine calls().
1227 if (Lexer.is(AsmToken::EndOfStatement)) {
1228 Lex();
1229 if (Lexer.is(AsmToken::Eof))
1230 return false;
1231 }
1232
Eli Friedman2128aae2012-10-22 23:58:19 +00001233 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001234 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001235
Daniel Dunbar3f872332009-07-28 16:08:33 +00001236 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001237 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001238 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001239
Nico Weber4c4c7322011-01-28 03:04:41 +00001240 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001241
1242 default: // Normal instruction or directive.
1243 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001244 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001245
1246 // If macros are enabled, check to see if this is a macro instantiation.
1247 if (MacrosEnabled)
1248 if (const Macro *M = MacroMap.lookup(IDVal))
1249 return HandleMacroEntry(IDVal, IDLoc, M);
1250
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001251 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001252 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001253
1254 // Target hook for parsing target specific directives.
1255 if (!getTargetParser().ParseDirective(ID))
1256 return false;
1257
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001258 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001259 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001260 return ParseDirectiveSet(IDVal, true);
1261 if (IDVal == ".equiv")
1262 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001263
Daniel Dunbara0d14262009-06-24 23:30:00 +00001264 // Data directives
1265
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001266 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001267 return ParseDirectiveAscii(IDVal, false);
1268 if (IDVal == ".asciz" || IDVal == ".string")
1269 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001270
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001271 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001272 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001273 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001274 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001275 if (IDVal == ".value")
1276 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001277 if (IDVal == ".2byte")
1278 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001279 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001280 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001281 if (IDVal == ".int")
1282 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001283 if (IDVal == ".4byte")
1284 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001285 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001286 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001287 if (IDVal == ".8byte")
1288 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001289 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001290 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1291 if (IDVal == ".double")
1292 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001293
Eli Friedman5d68ec22010-07-19 04:17:25 +00001294 if (IDVal == ".align") {
1295 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1296 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1297 }
1298 if (IDVal == ".align32") {
1299 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1300 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1301 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001302 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001303 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001304 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001305 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001306 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001307 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001308 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001309 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001310 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001311 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001312 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001313 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1314
Eli Bendersky4766ef42012-12-20 19:05:53 +00001315 if (IDVal == ".bundle_align_mode")
1316 return ParseDirectiveBundleAlignMode();
1317 if (IDVal == ".bundle_lock")
1318 return ParseDirectiveBundleLock();
1319 if (IDVal == ".bundle_unlock")
1320 return ParseDirectiveBundleUnlock();
1321
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001322 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001323 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001324
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001325 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001326 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001327 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001328 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001329 if (IDVal == ".zero")
1330 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001331
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001332 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001333
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001334 if (IDVal == ".extern") {
1335 EatToEndOfStatement(); // .extern is the default, ignore it.
1336 return false;
1337 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001338 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001339 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001340 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001341 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001342 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001343 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001344 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001345 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001346 if (IDVal == ".symbol_resolver")
1347 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001348 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001349 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001350 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001351 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001352 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001353 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001354 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001355 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001356 if (IDVal == ".weak_def_can_be_hidden")
1357 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001358
Hans Wennborg5cc64912011-06-18 13:51:54 +00001359 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001360 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001361 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001362 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001363
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001364 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001365 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001366 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001367 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001368 if (IDVal == ".incbin")
1369 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001370
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001371 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001372 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001373
Rafael Espindola761cb062012-06-03 23:57:14 +00001374 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001375 if (IDVal == ".rept")
1376 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001377 if (IDVal == ".irp")
1378 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001379 if (IDVal == ".irpc")
1380 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001381 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001382 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001383
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001384 // Look up the handler in the handler table.
1385 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1386 DirectiveMap.lookup(IDVal);
1387 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001388 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001389
Kevin Enderby9c656452009-09-10 20:51:44 +00001390
Jim Grosbach686c0182012-05-01 18:38:27 +00001391 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001392 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001393
Eli Friedman2128aae2012-10-22 23:58:19 +00001394 // _emit
1395 if (ParsingInlineAsm && IDVal == "_emit")
1396 return ParseDirectiveEmit(IDLoc, Info);
1397
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001398 CheckForValidSection();
1399
Chris Lattnera7f13542010-05-19 23:34:33 +00001400 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001401 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001402 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001403 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001404
Chad Rosier6a020a72012-10-25 20:41:34 +00001405 ParseInstructionInfo IInfo(Info.AsmRewrites);
1406 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1407 IDLoc,Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001408 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001409
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001410 // Dump the parsed representation, if requested.
1411 if (getShowParsedOperands()) {
1412 SmallString<256> Str;
1413 raw_svector_ostream OS(Str);
1414 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001415 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001416 if (i != 0)
1417 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001418 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001419 }
1420 OS << "]";
1421
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001422 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001423 }
1424
Kevin Enderby613b7572011-11-01 22:27:22 +00001425 // If we are generating dwarf for assembly source files and the current
1426 // section is the initial text section then generate a .loc directive for
1427 // the instruction.
1428 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001429 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001430
1431 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1432
1433 // If we previously parsed a cpp hash file line comment then make sure the
1434 // current Dwarf File is for the CppHashFilename if not then emit the
1435 // Dwarf File table for it and adjust the line number for the .loc.
1436 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1437 getContext().getMCDwarfFiles();
1438 if (CppHashFilename.size() != 0) {
1439 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1440 CppHashFilename)
Eric Christopher2318ba12012-12-18 00:30:54 +00001441 getStreamer().EmitDwarfFileDirective(
1442 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001443
Kevin Enderby32c1a822012-11-05 21:55:41 +00001444 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001445 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1446 }
1447
Kevin Enderby613b7572011-11-01 22:27:22 +00001448 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001449 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001450 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001451 StringRef());
1452 }
1453
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001454 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001455 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001456 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001457 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1458 Info.ParsedOperands,
1459 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001460 ParsingInlineAsm);
1461 }
Chris Lattner98986712010-01-14 22:21:20 +00001462
Chris Lattnercbf8a982010-09-11 16:18:25 +00001463 // Don't skip the rest of the line, the instruction parser is responsible for
1464 // that.
1465 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001466}
Chris Lattner9a023f72009-06-24 04:43:34 +00001467
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001468/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1469/// since they may not be able to be tokenized to get to the end of line token.
1470void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001471 if (!Lexer.is(AsmToken::EndOfStatement))
1472 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001473 // Eat EOL.
1474 Lex();
1475}
1476
1477/// ParseCppHashLineFilenameComment as this:
1478/// ::= # number "filename"
1479/// or just as a full line comment if it doesn't have a number and a string.
1480bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1481 Lex(); // Eat the hash token.
1482
1483 if (getLexer().isNot(AsmToken::Integer)) {
1484 // Consume the line since in cases it is not a well-formed line directive,
1485 // as if were simply a full line comment.
1486 EatToEndOfLine();
1487 return false;
1488 }
1489
1490 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001491 Lex();
1492
1493 if (getLexer().isNot(AsmToken::String)) {
1494 EatToEndOfLine();
1495 return false;
1496 }
1497
1498 StringRef Filename = getTok().getString();
1499 // Get rid of the enclosing quotes.
1500 Filename = Filename.substr(1, Filename.size()-2);
1501
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001502 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1503 CppHashLoc = L;
1504 CppHashFilename = Filename;
1505 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001506 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001507
1508 // Ignore any trailing characters, they're just comment.
1509 EatToEndOfLine();
1510 return false;
1511}
1512
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001513/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001514/// for the Filename and LineNo if any in the diagnostic.
1515void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1516 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1517 raw_ostream &OS = errs();
1518
1519 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1520 const SMLoc &DiagLoc = Diag.getLoc();
1521 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1522 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1523
1524 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1525 // before printing the message.
1526 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001527 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001528 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1529 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1530 }
1531
Eric Christopher2318ba12012-12-18 00:30:54 +00001532 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001533 // manager changed or buffer changed (like in a nested include) then just
1534 // print the normal diagnostic using its Filename and LineNo.
1535 if (!Parser->CppHashLineNumber ||
1536 &DiagSrcMgr != &Parser->SrcMgr ||
1537 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001538 if (Parser->SavedDiagHandler)
1539 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1540 else
1541 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001542 return;
1543 }
1544
Eric Christopher2318ba12012-12-18 00:30:54 +00001545 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001546 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1547 // the diagnostic.
1548 const std::string Filename = Parser->CppHashFilename;
1549
1550 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1551 int CppHashLocLineNo =
1552 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1553 int LineNo = Parser->CppHashLineNumber - 1 +
1554 (DiagLocLineNo - CppHashLocLineNo);
1555
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001556 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1557 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001558 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001559 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001560
Benjamin Kramer04a04262011-10-16 10:48:29 +00001561 if (Parser->SavedDiagHandler)
1562 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1563 else
1564 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001565}
1566
Rafael Espindola799aacf2012-08-21 18:29:30 +00001567// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1568// difference being that that function accepts '@' as part of identifiers and
1569// we can't do that. AsmLexer.cpp should probably be changed to handle
1570// '@' as a special case when needed.
1571static bool isIdentifierChar(char c) {
1572 return isalnum(c) || c == '_' || c == '$' || c == '.';
1573}
1574
Rafael Espindola761cb062012-06-03 23:57:14 +00001575bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001576 const MacroParameters &Parameters,
1577 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001578 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001579 unsigned NParameters = Parameters.size();
1580 if (NParameters != 0 && NParameters != A.size())
1581 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001582
Preston Gurd7b6f2032012-09-19 20:36:12 +00001583 // A macro without parameters is handled differently on Darwin:
1584 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001585 while (!Body.empty()) {
1586 // Scan for the next substitution.
1587 std::size_t End = Body.size(), Pos = 0;
1588 for (; Pos != End; ++Pos) {
1589 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001590 if (!NParameters) {
1591 // This macro has no parameters, look for $0, $1, etc.
1592 if (Body[Pos] != '$' || Pos + 1 == End)
1593 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001594
Rafael Espindola65366442011-06-05 02:43:45 +00001595 char Next = Body[Pos + 1];
1596 if (Next == '$' || Next == 'n' || isdigit(Next))
1597 break;
1598 } else {
1599 // This macro has parameters, look for \foo, \bar, etc.
1600 if (Body[Pos] == '\\' && Pos + 1 != End)
1601 break;
1602 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001603 }
1604
1605 // Add the prefix.
1606 OS << Body.slice(0, Pos);
1607
1608 // Check if we reached the end.
1609 if (Pos == End)
1610 break;
1611
Rafael Espindola65366442011-06-05 02:43:45 +00001612 if (!NParameters) {
1613 switch (Body[Pos+1]) {
1614 // $$ => $
1615 case '$':
1616 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001617 break;
1618
Rafael Espindola65366442011-06-05 02:43:45 +00001619 // $n => number of arguments
1620 case 'n':
1621 OS << A.size();
1622 break;
1623
1624 // $[0-9] => argument
1625 default: {
1626 // Missing arguments are ignored.
1627 unsigned Index = Body[Pos+1] - '0';
1628 if (Index >= A.size())
1629 break;
1630
1631 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001632 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001633 ie = A[Index].end(); it != ie; ++it)
1634 OS << it->getString();
1635 break;
1636 }
1637 }
1638 Pos += 2;
1639 } else {
1640 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001641 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001642 ++I;
1643
1644 const char *Begin = Body.data() + Pos +1;
1645 StringRef Argument(Begin, I - (Pos +1));
1646 unsigned Index = 0;
1647 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001648 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001649 break;
1650
Preston Gurd7b6f2032012-09-19 20:36:12 +00001651 if (Index == NParameters) {
1652 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1653 Pos += 3;
1654 else {
1655 OS << '\\' << Argument;
1656 Pos = I;
1657 }
1658 } else {
1659 for (MacroArgument::const_iterator it = A[Index].begin(),
1660 ie = A[Index].end(); it != ie; ++it)
1661 if (it->getKind() == AsmToken::String)
1662 OS << it->getStringContents();
1663 else
1664 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001665
Preston Gurd7b6f2032012-09-19 20:36:12 +00001666 Pos += 1 + Argument.size();
1667 }
Rafael Espindola65366442011-06-05 02:43:45 +00001668 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001669 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001670 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001671 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001672
Rafael Espindola65366442011-06-05 02:43:45 +00001673 return false;
1674}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001675
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001676MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1677 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001678 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001679 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1680 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001681{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001682}
1683
Preston Gurd7b6f2032012-09-19 20:36:12 +00001684static bool IsOperator(AsmToken::TokenKind kind)
1685{
1686 switch (kind)
1687 {
1688 default:
1689 return false;
1690 case AsmToken::Plus:
1691 case AsmToken::Minus:
1692 case AsmToken::Tilde:
1693 case AsmToken::Slash:
1694 case AsmToken::Star:
1695 case AsmToken::Dot:
1696 case AsmToken::Equal:
1697 case AsmToken::EqualEqual:
1698 case AsmToken::Pipe:
1699 case AsmToken::PipePipe:
1700 case AsmToken::Caret:
1701 case AsmToken::Amp:
1702 case AsmToken::AmpAmp:
1703 case AsmToken::Exclaim:
1704 case AsmToken::ExclaimEqual:
1705 case AsmToken::Percent:
1706 case AsmToken::Less:
1707 case AsmToken::LessEqual:
1708 case AsmToken::LessLess:
1709 case AsmToken::LessGreater:
1710 case AsmToken::Greater:
1711 case AsmToken::GreaterEqual:
1712 case AsmToken::GreaterGreater:
1713 return true;
1714 }
1715}
1716
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001717/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1718/// This is used for both default macro parameter values and the
1719/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001720bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1721 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001722 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001723 unsigned AddTokens = 0;
1724
1725 // gas accepts arguments separated by whitespace, except on Darwin
1726 if (!IsDarwin)
1727 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001728
1729 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001730 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1731 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001732 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001733 }
1734
1735 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1736 // Spaces and commas cannot be mixed to delimit parameters
1737 if (ArgumentDelimiter == AsmToken::Eof)
1738 ArgumentDelimiter = AsmToken::Comma;
1739 else if (ArgumentDelimiter != AsmToken::Comma) {
1740 Lexer.setSkipSpace(true);
1741 return TokError("expected ' ' for macro argument separator");
1742 }
1743 break;
1744 }
1745
1746 if (Lexer.is(AsmToken::Space)) {
1747 Lex(); // Eat spaces
1748
1749 // Spaces can delimit parameters, but could also be part an expression.
1750 // If the token after a space is an operator, add the token and the next
1751 // one into this argument
1752 if (ArgumentDelimiter == AsmToken::Space ||
1753 ArgumentDelimiter == AsmToken::Eof) {
1754 if (IsOperator(Lexer.getKind())) {
1755 // Check to see whether the token is used as an operator,
1756 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001757 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001758 if (*NextChar == ' ')
1759 AddTokens = 2;
1760 }
1761
1762 if (!AddTokens && ParenLevel == 0) {
1763 if (ArgumentDelimiter == AsmToken::Eof &&
1764 !IsOperator(Lexer.getKind()))
1765 ArgumentDelimiter = AsmToken::Space;
1766 break;
1767 }
1768 }
1769 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001770
1771 // HandleMacroEntry relies on not advancing the lexer here
1772 // to be able to fill in the remaining default parameter values
1773 if (Lexer.is(AsmToken::EndOfStatement))
1774 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001775
1776 // Adjust the current parentheses level.
1777 if (Lexer.is(AsmToken::LParen))
1778 ++ParenLevel;
1779 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1780 --ParenLevel;
1781
1782 // Append the token to the current argument list.
1783 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001784 if (AddTokens)
1785 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001786 Lex();
1787 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001788
1789 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001790 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001791 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001792 return false;
1793}
1794
1795// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001796bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001797 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001798 // Argument delimiter is initially unknown. It will be set by
1799 // ParseMacroArgument()
1800 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001801
1802 // Parse two kinds of macro invocations:
1803 // - macros defined without any parameters accept an arbitrary number of them
1804 // - macros defined with parameters accept at most that many of them
1805 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1806 ++Parameter) {
1807 MacroArgument MA;
1808
Preston Gurd7b6f2032012-09-19 20:36:12 +00001809 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001810 return true;
1811
Preston Gurd6c9176a2012-09-19 20:29:04 +00001812 if (!MA.empty() || !NParameters)
1813 A.push_back(MA);
1814 else if (NParameters) {
1815 if (!M->Parameters[Parameter].second.empty())
1816 A.push_back(M->Parameters[Parameter].second);
1817 }
Jim Grosbach97146442012-07-30 22:44:17 +00001818
Preston Gurd6c9176a2012-09-19 20:29:04 +00001819 // At the end of the statement, fill in remaining arguments that have
1820 // default values. If there aren't any, then the next argument is
1821 // required but missing
1822 if (Lexer.is(AsmToken::EndOfStatement)) {
1823 if (NParameters && Parameter < NParameters - 1) {
1824 if (M->Parameters[Parameter + 1].second.empty())
1825 return TokError("macro argument '" +
1826 Twine(M->Parameters[Parameter + 1].first) +
1827 "' is missing");
1828 else
1829 continue;
1830 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001831 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001832 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001833
1834 if (Lexer.is(AsmToken::Comma))
1835 Lex();
1836 }
1837 return TokError("Too many arguments");
1838}
1839
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001840bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1841 const Macro *M) {
1842 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1843 // this, although we should protect against infinite loops.
1844 if (ActiveMacros.size() == 20)
1845 return TokError("macros cannot be nested more than 20 levels deep");
1846
Rafael Espindola8a403d32012-08-08 14:51:03 +00001847 MacroArguments A;
1848 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001849 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001850
Jim Grosbach97146442012-07-30 22:44:17 +00001851 // Remove any trailing empty arguments. Do this after-the-fact as we have
1852 // to keep empty arguments in the middle of the list or positionality
1853 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001854 while (!A.empty() && A.back().empty())
1855 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001856
Rafael Espindola65366442011-06-05 02:43:45 +00001857 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1858 // to hold the macro body with substitutions.
1859 SmallString<256> Buf;
1860 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001861 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001862
Rafael Espindola8a403d32012-08-08 14:51:03 +00001863 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001864 return true;
1865
Rafael Espindola761cb062012-06-03 23:57:14 +00001866 // We include the .endmacro in the buffer as our queue to exit the macro
1867 // instantiation.
1868 OS << ".endmacro\n";
1869
Rafael Espindola65366442011-06-05 02:43:45 +00001870 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001871 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001872
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001873 // Create the macro instantiation object and add to the current macro
1874 // instantiation stack.
1875 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001876 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001877 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001878 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001879 ActiveMacros.push_back(MI);
1880
1881 // Jump to the macro instantiation and prime the lexer.
1882 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1883 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1884 Lex();
1885
1886 return false;
1887}
1888
1889void AsmParser::HandleMacroExit() {
1890 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001891 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001892 Lex();
1893
1894 // Pop the instantiation entry.
1895 delete ActiveMacros.back();
1896 ActiveMacros.pop_back();
1897}
1898
Rafael Espindolae71cc862012-01-28 05:57:00 +00001899static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001900 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001901 case MCExpr::Binary: {
1902 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1903 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001904 break;
1905 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001906 case MCExpr::Target:
1907 case MCExpr::Constant:
1908 return false;
1909 case MCExpr::SymbolRef: {
1910 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001911 if (S.isVariable())
1912 return IsUsedIn(Sym, S.getVariableValue());
1913 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001914 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001915 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001916 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001917 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001918
1919 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001920}
1921
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001922bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1923 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001924 // FIXME: Use better location, we should use proper tokens.
1925 SMLoc EqualLoc = Lexer.getLoc();
1926
Daniel Dunbar821e3332009-08-31 08:09:28 +00001927 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001928 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001929 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001930
Rafael Espindolae71cc862012-01-28 05:57:00 +00001931 // Note: we don't count b as used in "a = b". This is to allow
1932 // a = b
1933 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001934
Daniel Dunbar3f872332009-07-28 16:08:33 +00001935 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001936 return TokError("unexpected token in assignment");
1937
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001938 // Error on assignment to '.'.
1939 if (Name == ".") {
1940 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1941 "(use '.space' or '.org').)"));
1942 }
1943
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001944 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001945 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001946
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001947 // Validate that the LHS is allowed to be a variable (either it has not been
1948 // used as a symbol, or it is an absolute symbol).
1949 MCSymbol *Sym = getContext().LookupSymbol(Name);
1950 if (Sym) {
1951 // Diagnose assignment to a label.
1952 //
1953 // FIXME: Diagnostics. Note the location of the definition as a label.
1954 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001955 if (IsUsedIn(Sym, Value))
1956 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1957 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001958 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001959 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1960 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001961 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001962 return Error(EqualLoc, "redefinition of '" + Name + "'");
1963 else if (!Sym->isVariable())
1964 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001965 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001966 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1967 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001968
1969 // Don't count these checks as uses.
1970 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001971 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001972 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001973
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001974 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001975
1976 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001977 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001978 if (NoDeadStrip)
1979 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1980
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001981
1982 return false;
1983}
1984
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001985/// ParseIdentifier:
1986/// ::= identifier
1987/// ::= string
1988bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001989 // The assembler has relaxed rules for accepting identifiers, in particular we
1990 // allow things like '.globl $foo', which would normally be separate
1991 // tokens. At this level, we have already lexed so we cannot (currently)
1992 // handle this as a context dependent token, instead we detect adjacent tokens
1993 // and return the combined identifier.
1994 if (Lexer.is(AsmToken::Dollar)) {
1995 SMLoc DollarLoc = getLexer().getLoc();
1996
1997 // Consume the dollar sign, and check for a following identifier.
1998 Lex();
1999 if (Lexer.isNot(AsmToken::Identifier))
2000 return true;
2001
2002 // We have a '$' followed by an identifier, make sure they are adjacent.
2003 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2004 return true;
2005
2006 // Construct the joined identifier and consume the token.
2007 Res = StringRef(DollarLoc.getPointer(),
2008 getTok().getIdentifier().size() + 1);
2009 Lex();
2010 return false;
2011 }
2012
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002013 if (Lexer.isNot(AsmToken::Identifier) &&
2014 Lexer.isNot(AsmToken::String))
2015 return true;
2016
Sean Callanan18b83232010-01-19 21:44:56 +00002017 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002018
Sean Callanan79ed1a82010-01-19 20:22:31 +00002019 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002020
2021 return false;
2022}
2023
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002024/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002025/// ::= .equ identifier ',' expression
2026/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002027/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002028bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002029 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002030
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002031 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002032 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002033
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002034 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002035 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002036 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002037
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002038 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002039}
2040
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002041bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002042 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002043
2044 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002045 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002046 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2047 if (Str[i] != '\\') {
2048 Data += Str[i];
2049 continue;
2050 }
2051
2052 // Recognize escaped characters. Note that this escape semantics currently
2053 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2054 ++i;
2055 if (i == e)
2056 return TokError("unexpected backslash at end of string");
2057
2058 // Recognize octal sequences.
2059 if ((unsigned) (Str[i] - '0') <= 7) {
2060 // Consume up to three octal characters.
2061 unsigned Value = Str[i] - '0';
2062
2063 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2064 ++i;
2065 Value = Value * 8 + (Str[i] - '0');
2066
2067 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2068 ++i;
2069 Value = Value * 8 + (Str[i] - '0');
2070 }
2071 }
2072
2073 if (Value > 255)
2074 return TokError("invalid octal escape sequence (out of range)");
2075
2076 Data += (unsigned char) Value;
2077 continue;
2078 }
2079
2080 // Otherwise recognize individual escapes.
2081 switch (Str[i]) {
2082 default:
2083 // Just reject invalid escape sequences for now.
2084 return TokError("invalid escape sequence (unrecognized character)");
2085
2086 case 'b': Data += '\b'; break;
2087 case 'f': Data += '\f'; break;
2088 case 'n': Data += '\n'; break;
2089 case 'r': Data += '\r'; break;
2090 case 't': Data += '\t'; break;
2091 case '"': Data += '"'; break;
2092 case '\\': Data += '\\'; break;
2093 }
2094 }
2095
2096 return false;
2097}
2098
Daniel Dunbara0d14262009-06-24 23:30:00 +00002099/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002100/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2101bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002102 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002103 CheckForValidSection();
2104
Daniel Dunbara0d14262009-06-24 23:30:00 +00002105 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002106 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002107 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002108
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002109 std::string Data;
2110 if (ParseEscapedString(Data))
2111 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002112
2113 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002114 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002115 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2116
Sean Callanan79ed1a82010-01-19 20:22:31 +00002117 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002118
2119 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002120 break;
2121
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002122 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002123 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002124 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002125 }
2126 }
2127
Sean Callanan79ed1a82010-01-19 20:22:31 +00002128 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002129 return false;
2130}
2131
2132/// ParseDirectiveValue
2133/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2134bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002135 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002136 CheckForValidSection();
2137
Daniel Dunbara0d14262009-06-24 23:30:00 +00002138 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002139 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002140 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002141 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002142 return true;
2143
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002144 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002145 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2146 assert(Size <= 8 && "Invalid size");
2147 uint64_t IntValue = MCE->getValue();
2148 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2149 return Error(ExprLoc, "literal value out of range for directive");
2150 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2151 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002152 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002153
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002154 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002155 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002156
Daniel Dunbara0d14262009-06-24 23:30:00 +00002157 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002158 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002159 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002160 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002161 }
2162 }
2163
Sean Callanan79ed1a82010-01-19 20:22:31 +00002164 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002165 return false;
2166}
2167
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002168/// ParseDirectiveRealValue
2169/// ::= (.single | .double) [ expression (, expression)* ]
2170bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2171 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2172 CheckForValidSection();
2173
2174 for (;;) {
2175 // We don't truly support arithmetic on floating point expressions, so we
2176 // have to manually parse unary prefixes.
2177 bool IsNeg = false;
2178 if (getLexer().is(AsmToken::Minus)) {
2179 Lex();
2180 IsNeg = true;
2181 } else if (getLexer().is(AsmToken::Plus))
2182 Lex();
2183
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002184 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002185 getLexer().isNot(AsmToken::Real) &&
2186 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002187 return TokError("unexpected token in directive");
2188
2189 // Convert to an APFloat.
2190 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002191 StringRef IDVal = getTok().getString();
2192 if (getLexer().is(AsmToken::Identifier)) {
2193 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2194 Value = APFloat::getInf(Semantics);
2195 else if (!IDVal.compare_lower("nan"))
2196 Value = APFloat::getNaN(Semantics, false, ~0);
2197 else
2198 return TokError("invalid floating point literal");
2199 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002200 APFloat::opInvalidOp)
2201 return TokError("invalid floating point literal");
2202 if (IsNeg)
2203 Value.changeSign();
2204
2205 // Consume the numeric token.
2206 Lex();
2207
2208 // Emit the value as an integer.
2209 APInt AsInt = Value.bitcastToAPInt();
2210 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2211 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2212
2213 if (getLexer().is(AsmToken::EndOfStatement))
2214 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002215
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002216 if (getLexer().isNot(AsmToken::Comma))
2217 return TokError("unexpected token in directive");
2218 Lex();
2219 }
2220 }
2221
2222 Lex();
2223 return false;
2224}
2225
Daniel Dunbara0d14262009-06-24 23:30:00 +00002226/// ParseDirectiveSpace
2227/// ::= .space expression [ , expression ]
2228bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002229 CheckForValidSection();
2230
Daniel Dunbara0d14262009-06-24 23:30:00 +00002231 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002232 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002233 return true;
2234
2235 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002236 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2237 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002238 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002239 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002240
Daniel Dunbar475839e2009-06-29 20:37:27 +00002241 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002242 return true;
2243
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002244 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002245 return TokError("unexpected token in '.space' directive");
2246 }
2247
Sean Callanan79ed1a82010-01-19 20:22:31 +00002248 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002249
2250 if (NumBytes <= 0)
2251 return TokError("invalid number of bytes in '.space' directive");
2252
2253 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002254 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002255
2256 return false;
2257}
2258
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002259/// ParseDirectiveZero
2260/// ::= .zero expression
2261bool AsmParser::ParseDirectiveZero() {
2262 CheckForValidSection();
2263
2264 int64_t NumBytes;
2265 if (ParseAbsoluteExpression(NumBytes))
2266 return true;
2267
Rafael Espindolae452b172010-10-05 19:42:57 +00002268 int64_t Val = 0;
2269 if (getLexer().is(AsmToken::Comma)) {
2270 Lex();
2271 if (ParseAbsoluteExpression(Val))
2272 return true;
2273 }
2274
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002275 if (getLexer().isNot(AsmToken::EndOfStatement))
2276 return TokError("unexpected token in '.zero' directive");
2277
2278 Lex();
2279
Rafael Espindolae452b172010-10-05 19:42:57 +00002280 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002281
2282 return false;
2283}
2284
Daniel Dunbara0d14262009-06-24 23:30:00 +00002285/// ParseDirectiveFill
2286/// ::= .fill expression , expression , expression
2287bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002288 CheckForValidSection();
2289
Daniel Dunbara0d14262009-06-24 23:30:00 +00002290 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002291 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002292 return true;
2293
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002294 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002295 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002296 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002297
Daniel Dunbara0d14262009-06-24 23:30:00 +00002298 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002299 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002300 return true;
2301
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002302 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002303 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002304 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002305
Daniel Dunbara0d14262009-06-24 23:30:00 +00002306 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002307 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002308 return true;
2309
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002310 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002311 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002312
Sean Callanan79ed1a82010-01-19 20:22:31 +00002313 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002314
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002315 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2316 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002317
2318 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002319 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002320
2321 return false;
2322}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002323
2324/// ParseDirectiveOrg
2325/// ::= .org expression [ , expression ]
2326bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002327 CheckForValidSection();
2328
Daniel Dunbar821e3332009-08-31 08:09:28 +00002329 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002330 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002331 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002332 return true;
2333
2334 // Parse optional fill expression.
2335 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002336 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2337 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002338 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002339 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002340
Daniel Dunbar475839e2009-06-29 20:37:27 +00002341 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002342 return true;
2343
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002344 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002345 return TokError("unexpected token in '.org' directive");
2346 }
2347
Sean Callanan79ed1a82010-01-19 20:22:31 +00002348 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002349
Jim Grosbachebd4c052012-01-27 00:37:08 +00002350 // Only limited forms of relocatable expressions are accepted here, it
2351 // has to be relative to the current section. The streamer will return
2352 // 'true' if the expression wasn't evaluatable.
2353 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2354 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002355
2356 return false;
2357}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002358
2359/// ParseDirectiveAlign
2360/// ::= {.align, ...} expression [ , expression [ , expression ]]
2361bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002362 CheckForValidSection();
2363
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002364 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002365 int64_t Alignment;
2366 if (ParseAbsoluteExpression(Alignment))
2367 return true;
2368
2369 SMLoc MaxBytesLoc;
2370 bool HasFillExpr = false;
2371 int64_t FillExpr = 0;
2372 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002373 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2374 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002375 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002376 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002377
2378 // The fill expression can be omitted while specifying a maximum number of
2379 // alignment bytes, e.g:
2380 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002381 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002382 HasFillExpr = true;
2383 if (ParseAbsoluteExpression(FillExpr))
2384 return true;
2385 }
2386
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002387 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2388 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002389 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002390 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002391
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002392 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002393 if (ParseAbsoluteExpression(MaxBytesToFill))
2394 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002395
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002396 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002397 return TokError("unexpected token in directive");
2398 }
2399 }
2400
Sean Callanan79ed1a82010-01-19 20:22:31 +00002401 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002402
Daniel Dunbar648ac512010-05-17 21:54:30 +00002403 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002404 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002405
2406 // Compute alignment in bytes.
2407 if (IsPow2) {
2408 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002409 if (Alignment >= 32) {
2410 Error(AlignmentLoc, "invalid alignment value");
2411 Alignment = 31;
2412 }
2413
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002414 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002415 }
2416
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002417 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002418 if (MaxBytesLoc.isValid()) {
2419 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002420 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2421 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002422 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002423 }
2424
2425 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002426 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2427 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002428 MaxBytesToFill = 0;
2429 }
2430 }
2431
Daniel Dunbar648ac512010-05-17 21:54:30 +00002432 // Check whether we should use optimal code alignment for this .align
2433 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002434 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002435 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2436 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002437 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002438 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002439 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002440 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2441 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002442 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002443
2444 return false;
2445}
2446
Eli Bendersky4766ef42012-12-20 19:05:53 +00002447
2448/// ParseDirectiveBundleAlignMode
2449/// ::= {.bundle_align_mode} expression
2450bool AsmParser::ParseDirectiveBundleAlignMode() {
2451 CheckForValidSection();
2452
2453 // Expect a single argument: an expression that evaluates to a constant
2454 // in the inclusive range 0-30.
2455 SMLoc ExprLoc = getLexer().getLoc();
2456 int64_t AlignSizePow2;
2457 if (ParseAbsoluteExpression(AlignSizePow2))
2458 return true;
2459 else if (getLexer().isNot(AsmToken::EndOfStatement))
2460 return TokError("unexpected token after expression in"
2461 " '.bundle_align_mode' directive");
2462 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2463 return Error(ExprLoc,
2464 "invalid bundle alignment size (expected between 0 and 30)");
2465
2466 Lex();
2467
2468 // Because of AlignSizePow2's verified range we can safely truncate it to
2469 // unsigned.
2470 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2471 return false;
2472}
2473
2474/// ParseDirectiveBundleLock
2475/// ::= {.bundle_lock}
2476bool AsmParser::ParseDirectiveBundleLock() {
2477 CheckForValidSection();
2478
2479 if (getLexer().isNot(AsmToken::EndOfStatement))
2480 return TokError("unexpected token in '.bundle_lock' directive");
2481 Lex();
2482
2483 getStreamer().EmitBundleLock();
2484 return false;
2485}
2486
2487/// ParseDirectiveBundleLock
2488/// ::= {.bundle_lock}
2489bool AsmParser::ParseDirectiveBundleUnlock() {
2490 CheckForValidSection();
2491
2492 if (getLexer().isNot(AsmToken::EndOfStatement))
2493 return TokError("unexpected token in '.bundle_unlock' directive");
2494 Lex();
2495
2496 getStreamer().EmitBundleUnlock();
2497 return false;
2498}
2499
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002500/// ParseDirectiveSymbolAttribute
2501/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002502bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002503 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002504 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002505 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002506 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002507
2508 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002509 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002510
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002511 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002512
Jim Grosbach10ec6502011-09-15 17:56:49 +00002513 // Assembler local symbols don't make any sense here. Complain loudly.
2514 if (Sym->isTemporary())
2515 return Error(Loc, "non-local symbol required in directive");
2516
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002517 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002518
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002519 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002520 break;
2521
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002522 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002523 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002524 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002525 }
2526 }
2527
Sean Callanan79ed1a82010-01-19 20:22:31 +00002528 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002529 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002530}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002531
2532/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002533/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2534bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002535 CheckForValidSection();
2536
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002537 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002538 StringRef Name;
2539 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002540 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002541
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002542 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002543 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002544
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002545 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002546 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002547 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002548
2549 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002550 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002551 if (ParseAbsoluteExpression(Size))
2552 return true;
2553
2554 int64_t Pow2Alignment = 0;
2555 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002556 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002557 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002558 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002559 if (ParseAbsoluteExpression(Pow2Alignment))
2560 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002561
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002562 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2563 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002564 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2565
Chris Lattner258281d2010-01-19 06:22:22 +00002566 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002567 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2568 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002569 if (!isPowerOf2_64(Pow2Alignment))
2570 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2571 Pow2Alignment = Log2_64(Pow2Alignment);
2572 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002573 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002574
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002575 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002576 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002577
Sean Callanan79ed1a82010-01-19 20:22:31 +00002578 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002579
Chris Lattner1fc3d752009-07-09 17:25:12 +00002580 // NOTE: a size of zero for a .comm should create a undefined symbol
2581 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002582 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002583 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2584 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002585
Eric Christopherc260a3e2010-05-14 01:38:54 +00002586 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002587 // may internally end up wanting an alignment in bytes.
2588 // FIXME: Diagnose overflow.
2589 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002590 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2591 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002592
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002593 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002594 return Error(IDLoc, "invalid symbol redefinition");
2595
Chris Lattner1fc3d752009-07-09 17:25:12 +00002596 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002597 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002598 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002599 return false;
2600 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002601
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002602 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002603 return false;
2604}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002605
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002606/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002607/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002608bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002609 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002610 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002611
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002612 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002613 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002614 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002615
Sean Callanan79ed1a82010-01-19 20:22:31 +00002616 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002617
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002618 if (Str.empty())
2619 Error(Loc, ".abort detected. Assembly stopping.");
2620 else
2621 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002622 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002623
2624 return false;
2625}
Kevin Enderby71148242009-07-14 21:35:03 +00002626
Kevin Enderby1f049b22009-07-14 23:21:55 +00002627/// ParseDirectiveInclude
2628/// ::= .include "filename"
2629bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002630 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002631 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002632
Sean Callanan18b83232010-01-19 21:44:56 +00002633 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002634 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002635 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002636
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002637 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002638 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002639
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002640 // Strip the quotes.
2641 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002642
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002643 // Attempt to switch the lexer to the included file before consuming the end
2644 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002645 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002646 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002647 return true;
2648 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002649
2650 return false;
2651}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002652
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002653/// ParseDirectiveIncbin
2654/// ::= .incbin "filename"
2655bool AsmParser::ParseDirectiveIncbin() {
2656 if (getLexer().isNot(AsmToken::String))
2657 return TokError("expected string in '.incbin' directive");
2658
2659 std::string Filename = getTok().getString();
2660 SMLoc IncbinLoc = getLexer().getLoc();
2661 Lex();
2662
2663 if (getLexer().isNot(AsmToken::EndOfStatement))
2664 return TokError("unexpected token in '.incbin' directive");
2665
2666 // Strip the quotes.
2667 Filename = Filename.substr(1, Filename.size()-2);
2668
2669 // Attempt to process the included file.
2670 if (ProcessIncbinFile(Filename)) {
2671 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2672 return true;
2673 }
2674
2675 return false;
2676}
2677
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002678/// ParseDirectiveIf
2679/// ::= .if expression
2680bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002681 TheCondStack.push_back(TheCondState);
2682 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002683 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002684 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002685 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002686 int64_t ExprValue;
2687 if (ParseAbsoluteExpression(ExprValue))
2688 return true;
2689
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002690 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002691 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002692
Sean Callanan79ed1a82010-01-19 20:22:31 +00002693 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002694
2695 TheCondState.CondMet = ExprValue;
2696 TheCondState.Ignore = !TheCondState.CondMet;
2697 }
2698
2699 return false;
2700}
2701
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002702/// ParseDirectiveIfb
2703/// ::= .ifb string
2704bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2705 TheCondStack.push_back(TheCondState);
2706 TheCondState.TheCond = AsmCond::IfCond;
2707
Benjamin Kramer29739e72012-05-12 16:52:21 +00002708 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002709 EatToEndOfStatement();
2710 } else {
2711 StringRef Str = ParseStringToEndOfStatement();
2712
2713 if (getLexer().isNot(AsmToken::EndOfStatement))
2714 return TokError("unexpected token in '.ifb' directive");
2715
2716 Lex();
2717
2718 TheCondState.CondMet = ExpectBlank == Str.empty();
2719 TheCondState.Ignore = !TheCondState.CondMet;
2720 }
2721
2722 return false;
2723}
2724
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002725/// ParseDirectiveIfc
2726/// ::= .ifc string1, string2
2727bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2728 TheCondStack.push_back(TheCondState);
2729 TheCondState.TheCond = AsmCond::IfCond;
2730
Benjamin Kramer29739e72012-05-12 16:52:21 +00002731 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002732 EatToEndOfStatement();
2733 } else {
2734 StringRef Str1 = ParseStringToComma();
2735
2736 if (getLexer().isNot(AsmToken::Comma))
2737 return TokError("unexpected token in '.ifc' directive");
2738
2739 Lex();
2740
2741 StringRef Str2 = ParseStringToEndOfStatement();
2742
2743 if (getLexer().isNot(AsmToken::EndOfStatement))
2744 return TokError("unexpected token in '.ifc' directive");
2745
2746 Lex();
2747
2748 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2749 TheCondState.Ignore = !TheCondState.CondMet;
2750 }
2751
2752 return false;
2753}
2754
2755/// ParseDirectiveIfdef
2756/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002757bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2758 StringRef Name;
2759 TheCondStack.push_back(TheCondState);
2760 TheCondState.TheCond = AsmCond::IfCond;
2761
2762 if (TheCondState.Ignore) {
2763 EatToEndOfStatement();
2764 } else {
2765 if (ParseIdentifier(Name))
2766 return TokError("expected identifier after '.ifdef'");
2767
2768 Lex();
2769
2770 MCSymbol *Sym = getContext().LookupSymbol(Name);
2771
2772 if (expect_defined)
2773 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2774 else
2775 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2776 TheCondState.Ignore = !TheCondState.CondMet;
2777 }
2778
2779 return false;
2780}
2781
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002782/// ParseDirectiveElseIf
2783/// ::= .elseif expression
2784bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2785 if (TheCondState.TheCond != AsmCond::IfCond &&
2786 TheCondState.TheCond != AsmCond::ElseIfCond)
2787 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2788 " an .elseif");
2789 TheCondState.TheCond = AsmCond::ElseIfCond;
2790
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002791 bool LastIgnoreState = false;
2792 if (!TheCondStack.empty())
2793 LastIgnoreState = TheCondStack.back().Ignore;
2794 if (LastIgnoreState || TheCondState.CondMet) {
2795 TheCondState.Ignore = true;
2796 EatToEndOfStatement();
2797 }
2798 else {
2799 int64_t ExprValue;
2800 if (ParseAbsoluteExpression(ExprValue))
2801 return true;
2802
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002803 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002804 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002805
Sean Callanan79ed1a82010-01-19 20:22:31 +00002806 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002807 TheCondState.CondMet = ExprValue;
2808 TheCondState.Ignore = !TheCondState.CondMet;
2809 }
2810
2811 return false;
2812}
2813
2814/// ParseDirectiveElse
2815/// ::= .else
2816bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002817 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002818 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002819
Sean Callanan79ed1a82010-01-19 20:22:31 +00002820 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002821
2822 if (TheCondState.TheCond != AsmCond::IfCond &&
2823 TheCondState.TheCond != AsmCond::ElseIfCond)
2824 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2825 ".elseif");
2826 TheCondState.TheCond = AsmCond::ElseCond;
2827 bool LastIgnoreState = false;
2828 if (!TheCondStack.empty())
2829 LastIgnoreState = TheCondStack.back().Ignore;
2830 if (LastIgnoreState || TheCondState.CondMet)
2831 TheCondState.Ignore = true;
2832 else
2833 TheCondState.Ignore = false;
2834
2835 return false;
2836}
2837
2838/// ParseDirectiveEndIf
2839/// ::= .endif
2840bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002841 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002842 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002843
Sean Callanan79ed1a82010-01-19 20:22:31 +00002844 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002845
2846 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2847 TheCondStack.empty())
2848 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2849 ".else");
2850 if (!TheCondStack.empty()) {
2851 TheCondState = TheCondStack.back();
2852 TheCondStack.pop_back();
2853 }
2854
2855 return false;
2856}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002857
2858/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002859/// ::= .file [number] filename
2860/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002861bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002862 // FIXME: I'm not sure what this is.
2863 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002864 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002865 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002866 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002867 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002868
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002869 if (FileNumber < 1)
2870 return TokError("file number less than one");
2871 }
2872
Daniel Dunbareceec052010-07-12 17:45:27 +00002873 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002874 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002875
Nick Lewycky44d798d2011-10-17 23:05:28 +00002876 // Usually the directory and filename together, otherwise just the directory.
2877 StringRef Path = getTok().getString();
2878 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002879 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002880
Nick Lewycky44d798d2011-10-17 23:05:28 +00002881 StringRef Directory;
2882 StringRef Filename;
2883 if (getLexer().is(AsmToken::String)) {
2884 if (FileNumber == -1)
2885 return TokError("explicit path specified, but no file number");
2886 Filename = getTok().getString();
2887 Filename = Filename.substr(1, Filename.size()-2);
2888 Directory = Path;
2889 Lex();
2890 } else {
2891 Filename = Path;
2892 }
2893
Daniel Dunbareceec052010-07-12 17:45:27 +00002894 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002895 return TokError("unexpected token in '.file' directive");
2896
Chris Lattnerd32e8032010-01-25 19:02:58 +00002897 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002898 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002899 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002900 if (getContext().getGenDwarfForAssembly() == true)
2901 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2902 "used to generate dwarf debug info for assembly code");
2903
Nick Lewycky44d798d2011-10-17 23:05:28 +00002904 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002905 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002906 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002907
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002908 return false;
2909}
2910
2911/// ParseDirectiveLine
2912/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002913bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002914 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2915 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002916 return TokError("unexpected token in '.line' directive");
2917
Sean Callanan18b83232010-01-19 21:44:56 +00002918 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002919 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002920 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002921
2922 // FIXME: Do something with the .line.
2923 }
2924
Daniel Dunbareceec052010-07-12 17:45:27 +00002925 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002926 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002927
2928 return false;
2929}
2930
2931
2932/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002933/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002934/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2935/// The first number is a file number, must have been previously assigned with
2936/// a .file directive, the second number is the line number and optionally the
2937/// third number is a column position (zero if not specified). The remaining
2938/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002939bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002940
Daniel Dunbareceec052010-07-12 17:45:27 +00002941 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002942 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002943 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002944 if (FileNumber < 1)
2945 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002946 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002947 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002948 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002949
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002950 int64_t LineNumber = 0;
2951 if (getLexer().is(AsmToken::Integer)) {
2952 LineNumber = getTok().getIntVal();
2953 if (LineNumber < 1)
2954 return TokError("line number less than one in '.loc' directive");
2955 Lex();
2956 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002957
2958 int64_t ColumnPos = 0;
2959 if (getLexer().is(AsmToken::Integer)) {
2960 ColumnPos = getTok().getIntVal();
2961 if (ColumnPos < 0)
2962 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002963 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002964 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002965
Kevin Enderbyc0957932010-09-30 16:52:03 +00002966 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002967 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002968 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002969 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2970 for (;;) {
2971 if (getLexer().is(AsmToken::EndOfStatement))
2972 break;
2973
2974 StringRef Name;
2975 SMLoc Loc = getTok().getLoc();
2976 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002977 return TokError("unexpected token in '.loc' directive");
2978
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002979 if (Name == "basic_block")
2980 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2981 else if (Name == "prologue_end")
2982 Flags |= DWARF2_FLAG_PROLOGUE_END;
2983 else if (Name == "epilogue_begin")
2984 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2985 else if (Name == "is_stmt") {
Jordan Rose3ebe59c2013-01-07 19:00:49 +00002986 Loc = getTok().getLoc();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002987 const MCExpr *Value;
2988 if (getParser().ParseExpression(Value))
2989 return true;
2990 // The expression must be the constant 0 or 1.
2991 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2992 int Value = MCE->getValue();
2993 if (Value == 0)
2994 Flags &= ~DWARF2_FLAG_IS_STMT;
2995 else if (Value == 1)
2996 Flags |= DWARF2_FLAG_IS_STMT;
2997 else
2998 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002999 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003000 else {
3001 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3002 }
3003 }
3004 else if (Name == "isa") {
Jordan Rose3ebe59c2013-01-07 19:00:49 +00003005 Loc = getTok().getLoc();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003006 const MCExpr *Value;
3007 if (getParser().ParseExpression(Value))
3008 return true;
3009 // The expression must be a constant greater or equal to 0.
3010 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3011 int Value = MCE->getValue();
3012 if (Value < 0)
3013 return Error(Loc, "isa number less than zero");
3014 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003015 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003016 else {
3017 return Error(Loc, "isa number not a constant value");
3018 }
3019 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00003020 else if (Name == "discriminator") {
3021 if (getParser().ParseAbsoluteExpression(Discriminator))
3022 return true;
3023 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003024 else {
3025 return Error(Loc, "unknown sub-directive in '.loc' directive");
3026 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003027
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003028 if (getLexer().is(AsmToken::EndOfStatement))
3029 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003030 }
3031 }
3032
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00003033 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00003034 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003035
3036 return false;
3037}
3038
Daniel Dunbar138abae2010-10-16 04:56:42 +00003039/// ParseDirectiveStabs
3040/// ::= .stabs string, number, number, number
3041bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3042 SMLoc DirectiveLoc) {
3043 return TokError("unsupported directive '" + Directive + "'");
3044}
3045
Rafael Espindolaf9efd832011-05-10 01:10:18 +00003046/// ParseDirectiveCFISections
3047/// ::= .cfi_sections section [, section]
3048bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3049 SMLoc DirectiveLoc) {
3050 StringRef Name;
3051 bool EH = false;
3052 bool Debug = false;
3053
3054 if (getParser().ParseIdentifier(Name))
3055 return TokError("Expected an identifier");
3056
3057 if (Name == ".eh_frame")
3058 EH = true;
3059 else if (Name == ".debug_frame")
3060 Debug = true;
3061
3062 if (getLexer().is(AsmToken::Comma)) {
3063 Lex();
3064
3065 if (getParser().ParseIdentifier(Name))
3066 return TokError("Expected an identifier");
3067
3068 if (Name == ".eh_frame")
3069 EH = true;
3070 else if (Name == ".debug_frame")
3071 Debug = true;
3072 }
3073
3074 getStreamer().EmitCFISections(EH, Debug);
3075
3076 return false;
3077}
3078
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003079/// ParseDirectiveCFIStartProc
3080/// ::= .cfi_startproc
3081bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3082 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003083 getStreamer().EmitCFIStartProc();
3084 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003085}
3086
3087/// ParseDirectiveCFIEndProc
3088/// ::= .cfi_endproc
3089bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003090 getStreamer().EmitCFIEndProc();
3091 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003092}
3093
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003094/// ParseRegisterOrRegisterNumber - parse register name or number.
3095bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3096 SMLoc DirectiveLoc) {
3097 unsigned RegNo;
3098
Jim Grosbach6f888a82011-06-02 17:14:04 +00003099 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003100 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3101 DirectiveLoc))
3102 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00003103 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003104 } else
3105 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00003106
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003107 return false;
3108}
3109
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003110/// ParseDirectiveCFIDefCfa
3111/// ::= .cfi_def_cfa register, offset
3112bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3113 SMLoc DirectiveLoc) {
3114 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003115 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003116 return true;
3117
3118 if (getLexer().isNot(AsmToken::Comma))
3119 return TokError("unexpected token in directive");
3120 Lex();
3121
3122 int64_t Offset = 0;
3123 if (getParser().ParseAbsoluteExpression(Offset))
3124 return true;
3125
Rafael Espindola066c2f42011-04-12 23:59:07 +00003126 getStreamer().EmitCFIDefCfa(Register, Offset);
3127 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003128}
3129
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003130/// ParseDirectiveCFIDefCfaOffset
3131/// ::= .cfi_def_cfa_offset offset
3132bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3133 SMLoc DirectiveLoc) {
3134 int64_t Offset = 0;
3135 if (getParser().ParseAbsoluteExpression(Offset))
3136 return true;
3137
Rafael Espindola066c2f42011-04-12 23:59:07 +00003138 getStreamer().EmitCFIDefCfaOffset(Offset);
3139 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003140}
3141
3142/// ParseDirectiveCFIAdjustCfaOffset
3143/// ::= .cfi_adjust_cfa_offset adjustment
3144bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3145 SMLoc DirectiveLoc) {
3146 int64_t Adjustment = 0;
3147 if (getParser().ParseAbsoluteExpression(Adjustment))
3148 return true;
3149
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003150 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3151 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003152}
3153
3154/// ParseDirectiveCFIDefCfaRegister
3155/// ::= .cfi_def_cfa_register register
3156bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3157 SMLoc DirectiveLoc) {
3158 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003159 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003160 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003161
Rafael Espindola066c2f42011-04-12 23:59:07 +00003162 getStreamer().EmitCFIDefCfaRegister(Register);
3163 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003164}
3165
3166/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003167/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003168bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3169 int64_t Register = 0;
3170 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003171
3172 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003173 return true;
3174
3175 if (getLexer().isNot(AsmToken::Comma))
3176 return TokError("unexpected token in directive");
3177 Lex();
3178
3179 if (getParser().ParseAbsoluteExpression(Offset))
3180 return true;
3181
Rafael Espindola066c2f42011-04-12 23:59:07 +00003182 getStreamer().EmitCFIOffset(Register, Offset);
3183 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003184}
3185
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003186/// ParseDirectiveCFIRelOffset
3187/// ::= .cfi_rel_offset register, offset
3188bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3189 SMLoc DirectiveLoc) {
3190 int64_t Register = 0;
3191
3192 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3193 return true;
3194
3195 if (getLexer().isNot(AsmToken::Comma))
3196 return TokError("unexpected token in directive");
3197 Lex();
3198
3199 int64_t Offset = 0;
3200 if (getParser().ParseAbsoluteExpression(Offset))
3201 return true;
3202
Rafael Espindola25f492e2011-04-12 16:12:03 +00003203 getStreamer().EmitCFIRelOffset(Register, Offset);
3204 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003205}
3206
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003207static bool isValidEncoding(int64_t Encoding) {
3208 if (Encoding & ~0xff)
3209 return false;
3210
3211 if (Encoding == dwarf::DW_EH_PE_omit)
3212 return true;
3213
3214 const unsigned Format = Encoding & 0xf;
3215 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3216 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3217 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3218 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3219 return false;
3220
Rafael Espindolacaf11582010-12-29 04:31:26 +00003221 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003222 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003223 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003224 return false;
3225
3226 return true;
3227}
3228
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003229/// ParseDirectiveCFIPersonalityOrLsda
3230/// ::= .cfi_personality encoding, [symbol_name]
3231/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003232bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003233 SMLoc DirectiveLoc) {
3234 int64_t Encoding = 0;
3235 if (getParser().ParseAbsoluteExpression(Encoding))
3236 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003237 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003238 return false;
3239
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003240 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003241 return TokError("unsupported encoding.");
3242
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003243 if (getLexer().isNot(AsmToken::Comma))
3244 return TokError("unexpected token in directive");
3245 Lex();
3246
3247 StringRef Name;
3248 if (getParser().ParseIdentifier(Name))
3249 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003250
3251 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3252
3253 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003254 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003255 else {
3256 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003257 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003258 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003259 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003260}
3261
Rafael Espindolafe024d02010-12-28 18:36:23 +00003262/// ParseDirectiveCFIRememberState
3263/// ::= .cfi_remember_state
3264bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3265 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003266 getStreamer().EmitCFIRememberState();
3267 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003268}
3269
3270/// ParseDirectiveCFIRestoreState
3271/// ::= .cfi_remember_state
3272bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3273 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003274 getStreamer().EmitCFIRestoreState();
3275 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003276}
3277
Rafael Espindolac5754392011-04-12 15:31:05 +00003278/// ParseDirectiveCFISameValue
3279/// ::= .cfi_same_value register
3280bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3281 SMLoc DirectiveLoc) {
3282 int64_t Register = 0;
3283
3284 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3285 return true;
3286
3287 getStreamer().EmitCFISameValue(Register);
3288
3289 return false;
3290}
3291
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003292/// ParseDirectiveCFIRestore
3293/// ::= .cfi_restore register
3294bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003295 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003296 int64_t Register = 0;
3297 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3298 return true;
3299
3300 getStreamer().EmitCFIRestore(Register);
3301
3302 return false;
3303}
3304
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003305/// ParseDirectiveCFIEscape
3306/// ::= .cfi_escape expression[,...]
3307bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003308 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003309 std::string Values;
3310 int64_t CurrValue;
3311 if (getParser().ParseAbsoluteExpression(CurrValue))
3312 return true;
3313
3314 Values.push_back((uint8_t)CurrValue);
3315
3316 while (getLexer().is(AsmToken::Comma)) {
3317 Lex();
3318
3319 if (getParser().ParseAbsoluteExpression(CurrValue))
3320 return true;
3321
3322 Values.push_back((uint8_t)CurrValue);
3323 }
3324
3325 getStreamer().EmitCFIEscape(Values);
3326 return false;
3327}
3328
Rafael Espindola16d7d432012-01-23 21:51:52 +00003329/// ParseDirectiveCFISignalFrame
3330/// ::= .cfi_signal_frame
3331bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3332 SMLoc DirectiveLoc) {
3333 if (getLexer().isNot(AsmToken::EndOfStatement))
3334 return Error(getLexer().getLoc(),
3335 "unexpected token in '" + Directive + "' directive");
3336
3337 getStreamer().EmitCFISignalFrame();
3338
3339 return false;
3340}
3341
Rafael Espindolac8fec7e2012-11-23 16:59:41 +00003342/// ParseDirectiveCFIUndefined
3343/// ::= .cfi_undefined register
3344bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3345 SMLoc DirectiveLoc) {
3346 int64_t Register = 0;
3347
3348 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3349 return true;
3350
3351 getStreamer().EmitCFIUndefined(Register);
3352
3353 return false;
3354}
3355
Rafael Espindolaf4f14f62012-11-25 15:14:49 +00003356/// ParseDirectiveCFIRegister
3357/// ::= .cfi_register register, register
3358bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3359 SMLoc DirectiveLoc) {
3360 int64_t Register1 = 0;
3361
3362 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3363 return true;
3364
3365 if (getLexer().isNot(AsmToken::Comma))
3366 return TokError("unexpected token in directive");
3367 Lex();
3368
3369 int64_t Register2 = 0;
3370
3371 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3372 return true;
3373
3374 getStreamer().EmitCFIRegister(Register1, Register2);
3375
3376 return false;
3377}
3378
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003379/// ParseDirectiveMacrosOnOff
3380/// ::= .macros_on
3381/// ::= .macros_off
3382bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3383 SMLoc DirectiveLoc) {
3384 if (getLexer().isNot(AsmToken::EndOfStatement))
3385 return Error(getLexer().getLoc(),
3386 "unexpected token in '" + Directive + "' directive");
3387
3388 getParser().MacrosEnabled = Directive == ".macros_on";
3389
3390 return false;
3391}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003392
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003393/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003394/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003395bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3396 SMLoc DirectiveLoc) {
3397 StringRef Name;
3398 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003399 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003400
Rafael Espindola8a403d32012-08-08 14:51:03 +00003401 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003402 // Argument delimiter is initially unknown. It will be set by
3403 // ParseMacroArgument()
3404 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003405 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003406 for (;;) {
3407 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003408 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003409 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003410
3411 if (getLexer().is(AsmToken::Equal)) {
3412 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003413 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003414 return true;
3415 }
3416
Rafael Espindola65366442011-06-05 02:43:45 +00003417 Parameters.push_back(Parameter);
3418
Preston Gurd7b6f2032012-09-19 20:36:12 +00003419 if (getLexer().is(AsmToken::Comma))
3420 Lex();
3421 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003422 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003423 }
3424 }
3425
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003426 // Eat the end of statement.
3427 Lex();
3428
3429 AsmToken EndToken, StartToken = getTok();
3430
3431 // Lex the macro definition.
3432 for (;;) {
3433 // Check whether we have reached the end of the file.
3434 if (getLexer().is(AsmToken::Eof))
3435 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3436
3437 // Otherwise, check whether we have reach the .endmacro.
3438 if (getLexer().is(AsmToken::Identifier) &&
3439 (getTok().getIdentifier() == ".endm" ||
3440 getTok().getIdentifier() == ".endmacro")) {
3441 EndToken = getTok();
3442 Lex();
3443 if (getLexer().isNot(AsmToken::EndOfStatement))
3444 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3445 "' directive");
3446 break;
3447 }
3448
3449 // Otherwise, scan til the end of the statement.
3450 getParser().EatToEndOfStatement();
3451 }
3452
3453 if (getParser().MacroMap.lookup(Name)) {
3454 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3455 }
3456
3457 const char *BodyStart = StartToken.getLoc().getPointer();
3458 const char *BodyEnd = EndToken.getLoc().getPointer();
3459 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003460 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003461 return false;
3462}
3463
3464/// ParseDirectiveEndMacro
3465/// ::= .endm
3466/// ::= .endmacro
3467bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003468 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003469 if (getLexer().isNot(AsmToken::EndOfStatement))
3470 return TokError("unexpected token in '" + Directive + "' directive");
3471
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003472 // If we are inside a macro instantiation, terminate the current
3473 // instantiation.
3474 if (!getParser().ActiveMacros.empty()) {
3475 getParser().HandleMacroExit();
3476 return false;
3477 }
3478
3479 // Otherwise, this .endmacro is a stray entry in the file; well formed
3480 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003481 return TokError("unexpected '" + Directive + "' in file, "
3482 "no current macro definition");
3483}
3484
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003485/// ParseDirectivePurgeMacro
3486/// ::= .purgem
3487bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3488 SMLoc DirectiveLoc) {
3489 StringRef Name;
3490 if (getParser().ParseIdentifier(Name))
3491 return TokError("expected identifier in '.purgem' directive");
3492
3493 if (getLexer().isNot(AsmToken::EndOfStatement))
3494 return TokError("unexpected token in '.purgem' directive");
3495
3496 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3497 if (I == getParser().MacroMap.end())
3498 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3499
3500 // Undefine the macro.
3501 delete I->getValue();
3502 getParser().MacroMap.erase(I);
3503 return false;
3504}
3505
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003506bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003507 getParser().CheckForValidSection();
3508
3509 const MCExpr *Value;
3510
3511 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003512 return true;
3513
3514 if (getLexer().isNot(AsmToken::EndOfStatement))
3515 return TokError("unexpected token in directive");
3516
3517 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003518 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003519 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003520 getStreamer().EmitULEB128Value(Value);
3521
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003522 return false;
3523}
3524
Rafael Espindola761cb062012-06-03 23:57:14 +00003525Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003526 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003527
Rafael Espindola761cb062012-06-03 23:57:14 +00003528 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003529 for (;;) {
3530 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003531 if (getLexer().is(AsmToken::Eof)) {
3532 Error(DirectiveLoc, "no matching '.endr' in definition");
3533 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003534 }
3535
Rafael Espindola761cb062012-06-03 23:57:14 +00003536 if (Lexer.is(AsmToken::Identifier) &&
3537 (getTok().getIdentifier() == ".rept")) {
3538 ++NestLevel;
3539 }
3540
3541 // Otherwise, check whether we have reached the .endr.
3542 if (Lexer.is(AsmToken::Identifier) &&
3543 getTok().getIdentifier() == ".endr") {
3544 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003545 EndToken = getTok();
3546 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003547 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3548 TokError("unexpected token in '.endr' directive");
3549 return 0;
3550 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003551 break;
3552 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003553 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003554 }
3555
Rafael Espindola761cb062012-06-03 23:57:14 +00003556 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003557 EatToEndOfStatement();
3558 }
3559
3560 const char *BodyStart = StartToken.getLoc().getPointer();
3561 const char *BodyEnd = EndToken.getLoc().getPointer();
3562 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3563
Rafael Espindola761cb062012-06-03 23:57:14 +00003564 // We Are Anonymous.
3565 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003566 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003567 return new Macro(Name, Body, Parameters);
3568}
3569
3570void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3571 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003572 OS << ".endr\n";
3573
3574 MemoryBuffer *Instantiation =
3575 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3576
Rafael Espindola761cb062012-06-03 23:57:14 +00003577 // Create the macro instantiation object and add to the current macro
3578 // instantiation stack.
3579 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003580 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003581 getTok().getLoc(),
3582 Instantiation);
3583 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003584
Rafael Espindola761cb062012-06-03 23:57:14 +00003585 // Jump to the macro instantiation and prime the lexer.
3586 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3587 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3588 Lex();
3589}
3590
3591bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3592 int64_t Count;
3593 if (ParseAbsoluteExpression(Count))
3594 return TokError("unexpected token in '.rept' directive");
3595
3596 if (Count < 0)
3597 return TokError("Count is negative");
3598
3599 if (Lexer.isNot(AsmToken::EndOfStatement))
3600 return TokError("unexpected token in '.rept' directive");
3601
3602 // Eat the end of statement.
3603 Lex();
3604
3605 // Lex the rept definition.
3606 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3607 if (!M)
3608 return true;
3609
3610 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3611 // to hold the macro body with substitutions.
3612 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003613 MacroParameters Parameters;
3614 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003615 raw_svector_ostream OS(Buf);
3616 while (Count--) {
3617 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3618 return true;
3619 }
3620 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003621
3622 return false;
3623}
3624
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003625/// ParseDirectiveIrp
3626/// ::= .irp symbol,values
3627bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003628 MacroParameters Parameters;
3629 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003630
Preston Gurd6c9176a2012-09-19 20:29:04 +00003631 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003632 return TokError("expected identifier in '.irp' directive");
3633
3634 Parameters.push_back(Parameter);
3635
3636 if (Lexer.isNot(AsmToken::Comma))
3637 return TokError("expected comma in '.irp' directive");
3638
3639 Lex();
3640
Rafael Espindola8a403d32012-08-08 14:51:03 +00003641 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003642 if (ParseMacroArguments(0, A))
3643 return true;
3644
3645 // Eat the end of statement.
3646 Lex();
3647
3648 // Lex the irp definition.
3649 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3650 if (!M)
3651 return true;
3652
3653 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3654 // to hold the macro body with substitutions.
3655 SmallString<256> Buf;
3656 raw_svector_ostream OS(Buf);
3657
Rafael Espindola7996d042012-08-21 16:06:48 +00003658 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3659 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003660 Args.push_back(*i);
3661
3662 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3663 return true;
3664 }
3665
3666 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3667
3668 return false;
3669}
3670
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003671/// ParseDirectiveIrpc
3672/// ::= .irpc symbol,values
3673bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003674 MacroParameters Parameters;
3675 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003676
Preston Gurd6c9176a2012-09-19 20:29:04 +00003677 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003678 return TokError("expected identifier in '.irpc' directive");
3679
3680 Parameters.push_back(Parameter);
3681
3682 if (Lexer.isNot(AsmToken::Comma))
3683 return TokError("expected comma in '.irpc' directive");
3684
3685 Lex();
3686
Rafael Espindola8a403d32012-08-08 14:51:03 +00003687 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003688 if (ParseMacroArguments(0, A))
3689 return true;
3690
3691 if (A.size() != 1 || A.front().size() != 1)
3692 return TokError("unexpected token in '.irpc' directive");
3693
3694 // Eat the end of statement.
3695 Lex();
3696
3697 // Lex the irpc definition.
3698 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3699 if (!M)
3700 return true;
3701
3702 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3703 // to hold the macro body with substitutions.
3704 SmallString<256> Buf;
3705 raw_svector_ostream OS(Buf);
3706
3707 StringRef Values = A.front().front().getString();
3708 std::size_t I, End = Values.size();
3709 for (I = 0; I < End; ++I) {
3710 MacroArgument Arg;
3711 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3712
Rafael Espindola8a403d32012-08-08 14:51:03 +00003713 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003714 Args.push_back(Arg);
3715
3716 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3717 return true;
3718 }
3719
3720 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3721
3722 return false;
3723}
3724
Rafael Espindola761cb062012-06-03 23:57:14 +00003725bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3726 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003727 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003728
3729 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003730 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003731 assert(getLexer().is(AsmToken::EndOfStatement));
3732
Rafael Espindola761cb062012-06-03 23:57:14 +00003733 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003734 return false;
3735}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003736
Eli Friedman2128aae2012-10-22 23:58:19 +00003737bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3738 const MCExpr *Value;
3739 SMLoc ExprLoc = getLexer().getLoc();
3740 if (ParseExpression(Value))
3741 return true;
3742 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3743 if (!MCE)
3744 return Error(ExprLoc, "unexpected expression in _emit");
3745 uint64_t IntValue = MCE->getValue();
3746 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3747 return Error(ExprLoc, "literal value out of range for directive");
3748
3749 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3750 return false;
3751}
3752
Chad Rosierb1f8c132012-10-18 15:49:34 +00003753bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3754 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003755 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003756 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003757 SmallVectorImpl<std::string> &Clobbers,
3758 const MCInstrInfo *MII,
3759 const MCInstPrinter *IP,
3760 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003761 SmallVector<void *, 4> InputDecls;
3762 SmallVector<void *, 4> OutputDecls;
3763 SmallVector<bool, 4> InputDeclsOffsetOf;
3764 SmallVector<bool, 4> OutputDeclsOffsetOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003765 SmallVector<std::string, 4> InputConstraints;
3766 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003767 std::set<std::string> ClobberRegs;
3768
Chad Rosier4e472d22012-10-20 01:02:45 +00003769 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003770
3771 // Prime the lexer.
3772 Lex();
3773
3774 // While we have input, parse each statement.
3775 unsigned InputIdx = 0;
3776 unsigned OutputIdx = 0;
3777 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003778 ParseStatementInfo Info(&AsmStrRewrites);
3779 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003780 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003781
Chad Rosier57498012012-12-12 22:45:52 +00003782 if (Info.ParseError)
3783 return true;
3784
Eli Friedman2128aae2012-10-22 23:58:19 +00003785 if (Info.Opcode != ~0U) {
3786 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003787
3788 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003789 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3790 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003791
3792 // Immediate.
3793 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003794 if (Operand->needAsmRewrite())
3795 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3796 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003797 continue;
3798 }
3799
3800 // Register operand.
Chad Rosierc0a14b82012-10-24 17:22:29 +00003801 if (Operand->isReg() && !Operand->isOffsetOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003802 unsigned NumDefs = Desc.getNumDefs();
3803 // Clobber.
3804 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3805 std::string Reg;
3806 raw_string_ostream OS(Reg);
3807 IP->printRegName(OS, Operand->getReg());
3808 ClobberRegs.insert(StringRef(OS.str()));
3809 }
3810 continue;
3811 }
3812
3813 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003814 unsigned Size;
3815 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3816 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003817 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003818 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc0a14b82012-10-24 17:22:29 +00003819 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003820 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003821 Operand->getStartLoc(),
3822 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003823 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003824 if (isOutput) {
3825 std::string Constraint = "=";
3826 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003827 OutputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003828 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003829 Constraint += Operand->getConstraint().str();
3830 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003831 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003832 Operand->getStartLoc(),
3833 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003834 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003835 InputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003836 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003837 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003838 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003839 Operand->getStartLoc(),
3840 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003841 }
3842 }
3843 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003844 }
3845 }
3846
3847 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003848 NumOutputs = OutputDecls.size();
3849 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003850
3851 // Set the unique clobbers.
3852 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3853 E = ClobberRegs.end(); I != E; ++I)
3854 Clobbers.push_back(*I);
3855
3856 // Merge the various outputs and inputs. Output are expected first.
3857 if (NumOutputs || NumInputs) {
3858 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003859 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003860 Constraints.resize(NumExprs);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003861 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3862 // constraint for offsetof. This needs to be cleaned up!
Chad Rosierb1f8c132012-10-18 15:49:34 +00003863 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003864 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3865 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003866 }
3867 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003868 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3869 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003870 }
3871 }
3872
3873 // Build the IR assembly string.
3874 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003875 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003876 raw_string_ostream OS(AsmStringIR);
3877 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003878 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003879 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3880 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003881
Chad Rosier4e472d22012-10-20 01:02:45 +00003882 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003883
3884 // Emit everything up to the immediate/expression. If the previous rewrite
3885 // was a size directive, then this has already been done.
3886 if (PrevKind != AOK_SizeDirective)
3887 OS << StringRef(Start, Loc - Start);
3888 PrevKind = Kind;
3889
Chad Rosier5a719fc2012-10-23 17:43:43 +00003890 // Skip the original expression.
3891 if (Kind == AOK_Skip) {
3892 Start = Loc + (*I).Len;
3893 continue;
3894 }
3895
Chad Rosierb1f8c132012-10-18 15:49:34 +00003896 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00003897 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003898 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003899 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00003900 OS << Twine("$$");
3901 OS << (*I).Val;
3902 break;
3903 case AOK_ImmPrefix:
3904 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00003905 break;
3906 case AOK_Input:
3907 OS << '$';
3908 OS << InputIdx++;
3909 break;
3910 case AOK_Output:
3911 OS << '$';
3912 OS << OutputIdx++;
3913 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00003914 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00003915 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00003916 default: break;
3917 case 8: OS << "byte ptr "; break;
3918 case 16: OS << "word ptr "; break;
3919 case 32: OS << "dword ptr "; break;
3920 case 64: OS << "qword ptr "; break;
3921 case 80: OS << "xword ptr "; break;
3922 case 128: OS << "xmmword ptr "; break;
3923 case 256: OS << "ymmword ptr "; break;
3924 }
Eli Friedman2128aae2012-10-22 23:58:19 +00003925 break;
3926 case AOK_Emit:
3927 OS << ".byte";
3928 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00003929 case AOK_DotOperator:
3930 OS << (*I).Val;
3931 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003932 }
Chad Rosier96d58e62012-10-19 20:57:14 +00003933
Chad Rosierb1f8c132012-10-18 15:49:34 +00003934 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00003935 if (Kind != AOK_SizeDirective)
3936 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003937 }
3938
3939 // Emit the remainder of the asm string.
3940 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3941 if (Start != AsmEnd)
3942 OS << StringRef(Start, AsmEnd - Start);
3943
3944 AsmString = OS.str();
3945 return false;
3946}
3947
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003948/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003949MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003950 MCContext &C, MCStreamer &Out,
3951 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003952 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003953}