blob: 34ebe3b859b470ade68167e2daa717cc1883aaea [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
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000049MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
50
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
81 /// The location where parsing should resume upon instantiation completion.
82 SMLoc ExitLoc;
83
84public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000085 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000086 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000087};
88
Chad Rosier6a020a72012-10-25 20:41:34 +000089//struct AsmRewrite;
Eli Friedman2128aae2012-10-22 23:58:19 +000090struct ParseStatementInfo {
91 /// ParsedOperands - The parsed operands from the last parsed statement.
92 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
93
94 /// Opcode - The opcode from the last parsed instruction.
95 unsigned Opcode;
96
97 SmallVectorImpl<AsmRewrite> *AsmRewrites;
98
99 ParseStatementInfo() : Opcode(~0U), AsmRewrites(0) {}
100 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
101 : Opcode(~0), AsmRewrites(rewrites) {}
102
103 ~ParseStatementInfo() {
104 // Free any parsed operands.
105 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
106 delete ParsedOperands[i];
107 ParsedOperands.clear();
108 }
109};
110
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000111/// \brief The concrete assembly parser instance.
112class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000113 friend class GenericAsmParser;
114
Craig Topper85aadc02012-09-15 16:23:52 +0000115 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
116 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000117private:
118 AsmLexer Lexer;
119 MCContext &Ctx;
120 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000121 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000122 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000123 SourceMgr::DiagHandlerTy SavedDiagHandler;
124 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000125 MCAsmParserExtension *GenericParser;
126 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000127
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000128 /// This is the current buffer index we're lexing from as managed by the
129 /// SourceMgr object.
130 int CurBuffer;
131
132 AsmCond TheCondState;
133 std::vector<AsmCond> TheCondStack;
134
135 /// DirectiveMap - This is a table handlers for directives. Each handler is
136 /// invoked after the directive identifier is read and is responsible for
137 /// parsing and validating the rest of the directive. The handler is passed
138 /// in the directive name and the location of the directive keyword.
139 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000140
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000141 /// MacroMap - Map of currently defined macros.
142 StringMap<Macro*> MacroMap;
143
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000144 /// ActiveMacros - Stack of active macro instantiations.
145 std::vector<MacroInstantiation*> ActiveMacros;
146
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000147 /// Boolean tracking whether macro substitution is enabled.
148 unsigned MacrosEnabled : 1;
149
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000150 /// Flag tracking whether any errors have been encountered.
151 unsigned HadError : 1;
152
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000153 /// The values from the last parsed cpp hash file line comment if any.
154 StringRef CppHashFilename;
155 int64_t CppHashLineNumber;
156 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000157 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000158
Devang Patel0db58bf2012-01-31 18:14:05 +0000159 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
160 unsigned AssemblerDialect;
161
Preston Gurd7b6f2032012-09-19 20:36:12 +0000162 /// IsDarwin - is Darwin compatibility enabled?
163 bool IsDarwin;
164
Chad Rosier8f138d12012-10-15 17:19:13 +0000165 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000166 bool ParsingInlineAsm;
167
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000168public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000169 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000170 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000171 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000172
173 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
174
Craig Topper345d16d2012-08-29 05:48:09 +0000175 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
176 StringRef Directive,
177 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000178 DirectiveMap[Directive] = std::make_pair(Object, Handler);
179 }
180
181public:
182 /// @name MCAsmParser Interface
183 /// {
184
185 virtual SourceMgr &getSourceManager() { return SrcMgr; }
186 virtual MCAsmLexer &getLexer() { return Lexer; }
187 virtual MCContext &getContext() { return Ctx; }
188 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000189 virtual unsigned getAssemblerDialect() {
190 if (AssemblerDialect == ~0U)
191 return MAI.getAssemblerDialect();
192 else
193 return AssemblerDialect;
194 }
195 virtual void setAssemblerDialect(unsigned i) {
196 AssemblerDialect = i;
197 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000198
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000199 virtual bool Warning(SMLoc L, const Twine &Msg,
200 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
201 virtual bool Error(SMLoc L, const Twine &Msg,
202 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000203
Craig Topper345d16d2012-08-29 05:48:09 +0000204 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000205
Chad Rosier84125ca2012-10-13 00:26:04 +0000206 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000207 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000208
209 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
210 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000211 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000212 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000213 SmallVectorImpl<std::string> &Clobbers,
214 const MCInstrInfo *MII,
215 const MCInstPrinter *IP,
216 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000217
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000218 bool ParseExpression(const MCExpr *&Res);
219 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
220 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
221 virtual bool ParseAbsoluteExpression(int64_t &Res);
222
223 /// }
224
225private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000226 void CheckForValidSection();
227
Eli Friedman2128aae2012-10-22 23:58:19 +0000228 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000229 void EatToEndOfLine();
230 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000231
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000232 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000233 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000234 const MacroParameters &Parameters,
235 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000236 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000237 void HandleMacroExit();
238
239 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000240 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000241 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
242 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000243 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000244 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000245
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000246 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
247 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000248 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
249 /// This returns true on failure.
250 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000251
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000252 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000253 /// current token is not set; clients should ensure Lex() is called
254 /// subsequently.
255 void JumpToLoc(SMLoc Loc);
256
Craig Topper345d16d2012-08-29 05:48:09 +0000257 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000258
Preston Gurd7b6f2032012-09-19 20:36:12 +0000259 bool ParseMacroArgument(MacroArgument &MA,
260 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000261 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000262
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000263 /// \brief Parse up to the end of statement and a return the contents from the
264 /// current token until the end of the statement; the current token on exit
265 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000266 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000267
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000268 /// \brief Parse until the end of a statement or a comma is encountered,
269 /// return the contents from the current token up to the end or comma.
270 StringRef ParseStringToComma();
271
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000272 bool ParseAssignment(StringRef Name, bool allow_redef,
273 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000274
275 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
276 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
277 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000278 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000279
280 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000281 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000282 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000283
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000284 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000285
286 // ".ascii", ".asciiz", ".string"
287 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000288 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000289 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000290 bool ParseDirectiveFill(); // ".fill"
291 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000292 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000293 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000294 bool ParseDirectiveOrg(); // ".org"
295 // ".align{,32}", ".p2align{,w,l}"
296 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
297
298 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
299 /// accepts a single symbol (which should be a label or an external).
300 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000301
302 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
303
304 bool ParseDirectiveAbort(); // ".abort"
305 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000306 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000307
308 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000309 // ".ifb" or ".ifnb", depending on ExpectBlank.
310 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000311 // ".ifc" or ".ifnc", depending on ExpectEqual.
312 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000313 // ".ifdef" or ".ifndef", depending on expect_defined
314 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000315 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
316 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
317 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
318
319 /// ParseEscapedString - Parse the current token as a string which may include
320 /// escaped characters and return the string contents.
321 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000322
323 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
324 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000325
Rafael Espindola761cb062012-06-03 23:57:14 +0000326 // Macro-like directives
327 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
328 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
329 raw_svector_ostream &OS);
330 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000331 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000332 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000333 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000334
Eli Friedman2128aae2012-10-22 23:58:19 +0000335 // "_emit"
336 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000337};
338
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000339/// \brief Generic implementations of directive handling, etc. which is shared
340/// (or the default, at least) for all assembler parser.
341class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000342 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
343 void AddDirectiveHandler(StringRef Directive) {
344 getParser().AddDirectiveHandler(this, Directive,
345 HandleDirective<GenericAsmParser, Handler>);
346 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000347public:
348 GenericAsmParser() {}
349
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000350 AsmParser &getParser() {
351 return (AsmParser&) this->MCAsmParserExtension::getParser();
352 }
353
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000354 virtual void Initialize(MCAsmParser &Parser) {
355 // Call the base implementation.
356 this->MCAsmParserExtension::Initialize(Parser);
357
358 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000359 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
360 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
361 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000362 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000363
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000364 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000365 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
366 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000367 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
368 ".cfi_startproc");
369 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
370 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000371 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
372 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000373 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
374 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000375 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
376 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000377 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
378 ".cfi_def_cfa_register");
379 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
380 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000381 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
382 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000383 AddDirectiveHandler<
384 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
385 AddDirectiveHandler<
386 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000387 AddDirectiveHandler<
388 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
389 AddDirectiveHandler<
390 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000391 AddDirectiveHandler<
392 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000393 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000394 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
395 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000396 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000397 AddDirectiveHandler<
398 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000399 AddDirectiveHandler<
400 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000401
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000402 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000403 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
404 ".macros_on");
405 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
406 ".macros_off");
407 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
408 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
409 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000410 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000411
412 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
413 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000414 }
415
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000416 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
417
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000418 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
419 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
420 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000421 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000422 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000423 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
424 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000425 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000426 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000427 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000428 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
429 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000430 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000431 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000432 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
433 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000434 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000435 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000436 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000437 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000438 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000439
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000440 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000441 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
442 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000443 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000444
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000445 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000446};
447
448}
449
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000450namespace llvm {
451
452extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000453extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000454extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000455
456}
457
Chris Lattneraaec2052010-01-19 19:46:13 +0000458enum { DEFAULT_ADDRSPACE = 0 };
459
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000460AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000461 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000462 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000463 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000464 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000465 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000466 // Save the old handler.
467 SavedDiagHandler = SrcMgr.getDiagHandler();
468 SavedDiagContext = SrcMgr.getDiagContext();
469 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000470 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000471 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000472
473 // Initialize the generic parser.
474 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000475
476 // Initialize the platform / file format parser.
477 //
478 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
479 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000480 if (_MAI.hasMicrosoftFastStdCallMangling()) {
481 PlatformParser = createCOFFAsmParser();
482 PlatformParser->Initialize(*this);
483 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000484 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000485 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000486 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000487 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000488 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000489 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000490 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000491}
492
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000493AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000494 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
495
496 // Destroy any macros.
497 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
498 ie = MacroMap.end(); it != ie; ++it)
499 delete it->getValue();
500
Daniel Dunbare4749702010-07-12 18:12:02 +0000501 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000502 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000503}
504
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000505void AsmParser::PrintMacroInstantiations() {
506 // Print the active macro instantiation stack.
507 for (std::vector<MacroInstantiation*>::const_reverse_iterator
508 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000509 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
510 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000511}
512
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000513bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000514 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000515 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000516 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000517 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000518 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000519}
520
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000521bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000522 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000523 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000524 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000525 return true;
526}
527
Sean Callananfd0b0282010-01-21 00:19:58 +0000528bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000529 std::string IncludedFile;
530 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000531 if (NewBuf == -1)
532 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000533
Sean Callananfd0b0282010-01-21 00:19:58 +0000534 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000535
Sean Callananfd0b0282010-01-21 00:19:58 +0000536 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000537
Sean Callananfd0b0282010-01-21 00:19:58 +0000538 return false;
539}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000540
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000541/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000542/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000543/// returns true on failure.
544bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
545 std::string IncludedFile;
546 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
547 if (NewBuf == -1)
548 return true;
549
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000550 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000551 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
552 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000553 return false;
554}
555
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000556void AsmParser::JumpToLoc(SMLoc Loc) {
557 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
558 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
559}
560
Sean Callananfd0b0282010-01-21 00:19:58 +0000561const AsmToken &AsmParser::Lex() {
562 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000563
Sean Callananfd0b0282010-01-21 00:19:58 +0000564 if (tok->is(AsmToken::Eof)) {
565 // If this is the end of an included file, pop the parent file off the
566 // include stack.
567 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
568 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000569 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000570 tok = &Lexer.Lex();
571 }
572 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000573
Sean Callananfd0b0282010-01-21 00:19:58 +0000574 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000575 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000576
Sean Callananfd0b0282010-01-21 00:19:58 +0000577 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000578}
579
Chris Lattner79180e22010-04-05 23:15:42 +0000580bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000581 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000582 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000583 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000584
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000585 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000586 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000587
588 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000589 AsmCond StartingCondState = TheCondState;
590
Kevin Enderby613b7572011-11-01 22:27:22 +0000591 // If we are generating dwarf for assembly source files save the initial text
592 // section and generate a .file directive.
593 if (getContext().getGenDwarfForAssembly()) {
594 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000595 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
596 getStreamer().EmitLabel(SectionStartSym);
597 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000598 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
599 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
600 }
601
Chris Lattnerb717fb02009-07-02 21:53:43 +0000602 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000603 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000604 ParseStatementInfo Info;
605 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000606
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000607 // We had an error, validate that one was emitted and recover by skipping to
608 // the next line.
609 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000610 EatToEndOfStatement();
611 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000612
613 if (TheCondState.TheCond != StartingCondState.TheCond ||
614 TheCondState.Ignore != StartingCondState.Ignore)
615 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000616
617 // Check to see there are no empty DwarfFile slots.
618 const std::vector<MCDwarfFile *> &MCDwarfFiles =
619 getContext().getMCDwarfFiles();
620 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000621 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000622 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000623 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000624
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000625 // Check to see that all assembler local symbols were actually defined.
626 // Targets that don't do subsections via symbols may not want this, though,
627 // so conservatively exclude them. Only do this if we're finalizing, though,
628 // as otherwise we won't necessarilly have seen everything yet.
629 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
630 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
631 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
632 e = Symbols.end();
633 i != e; ++i) {
634 MCSymbol *Sym = i->getValue();
635 // Variable symbols may not be marked as defined, so check those
636 // explicitly. If we know it's a variable, we have a definition for
637 // the purposes of this check.
638 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
639 // FIXME: We would really like to refer back to where the symbol was
640 // first referenced for a source location. We need to add something
641 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000642 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
643 "assembler local symbol '" + Sym->getName() +
644 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000645 }
646 }
647
648
Chris Lattner79180e22010-04-05 23:15:42 +0000649 // Finalize the output stream if there are no errors and if the client wants
650 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000651 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000652 Out.Finish();
653
Chris Lattnerb717fb02009-07-02 21:53:43 +0000654 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000655}
656
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000657void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000658 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000659 TokError("expected section directive before assembly directive");
660 Out.SwitchSection(Ctx.getMachOSection(
661 "__TEXT", "__text",
662 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
663 0, SectionKind::getText()));
664 }
665}
666
Chris Lattner2cf5f142009-06-22 01:29:09 +0000667/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
668void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000669 while (Lexer.isNot(AsmToken::EndOfStatement) &&
670 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000671 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000672
Chris Lattner2cf5f142009-06-22 01:29:09 +0000673 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000674 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000675 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000676}
677
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000678StringRef AsmParser::ParseStringToEndOfStatement() {
679 const char *Start = getTok().getLoc().getPointer();
680
681 while (Lexer.isNot(AsmToken::EndOfStatement) &&
682 Lexer.isNot(AsmToken::Eof))
683 Lex();
684
685 const char *End = getTok().getLoc().getPointer();
686 return StringRef(Start, End - Start);
687}
Chris Lattnerc4193832009-06-22 05:51:26 +0000688
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000689StringRef AsmParser::ParseStringToComma() {
690 const char *Start = getTok().getLoc().getPointer();
691
692 while (Lexer.isNot(AsmToken::EndOfStatement) &&
693 Lexer.isNot(AsmToken::Comma) &&
694 Lexer.isNot(AsmToken::Eof))
695 Lex();
696
697 const char *End = getTok().getLoc().getPointer();
698 return StringRef(Start, End - Start);
699}
700
Chris Lattner74ec1a32009-06-22 06:32:03 +0000701/// ParseParenExpr - Parse a paren expression and return it.
702/// NOTE: This assumes the leading '(' has already been consumed.
703///
704/// parenexpr ::= expr)
705///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000706bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000707 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000708 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000709 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000710 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000711 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000712 return false;
713}
Chris Lattnerc4193832009-06-22 05:51:26 +0000714
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000715/// ParseBracketExpr - Parse a bracket expression and return it.
716/// NOTE: This assumes the leading '[' has already been consumed.
717///
718/// bracketexpr ::= expr]
719///
720bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
721 if (ParseExpression(Res)) return true;
722 if (Lexer.isNot(AsmToken::RBrac))
723 return TokError("expected ']' in brackets expression");
724 EndLoc = Lexer.getLoc();
725 Lex();
726 return false;
727}
728
Chris Lattner74ec1a32009-06-22 06:32:03 +0000729/// ParsePrimaryExpr - Parse a primary expression and return it.
730/// primaryexpr ::= (parenexpr
731/// primaryexpr ::= symbol
732/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000733/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000734/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000735bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000736 switch (Lexer.getKind()) {
737 default:
738 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000739 // If we have an error assume that we've already handled it.
740 case AsmToken::Error:
741 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000742 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000743 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000744 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000745 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000746 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000747 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000748 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000749 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000750 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000751 EndLoc = Lexer.getLoc();
752
753 StringRef Identifier;
754 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000755 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000756
Daniel Dunbarfffff912009-10-16 01:34:54 +0000757 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000758 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000759 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000760
761 // Lookup the symbol variant if used.
762 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000763 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000764 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000765 if (Variant == MCSymbolRefExpr::VK_Invalid) {
766 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000767 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000768 }
769 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000770
Daniel Dunbarfffff912009-10-16 01:34:54 +0000771 // If this is an absolute variable reference, substitute it now to preserve
772 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000773 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000774 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000775 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000776
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000777 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000778 return false;
779 }
780
781 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000782 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000783 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000784 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000785 case AsmToken::Integer: {
786 SMLoc Loc = getTok().getLoc();
787 int64_t IntVal = getTok().getIntVal();
788 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000789 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000790 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000791 // Look for 'b' or 'f' following an Integer as a directional label
792 if (Lexer.getKind() == AsmToken::Identifier) {
793 StringRef IDVal = getTok().getString();
794 if (IDVal == "f" || IDVal == "b"){
795 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
796 IDVal == "f" ? 1 : 0);
797 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
798 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000799 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000800 return Error(Loc, "invalid reference to undefined symbol");
801 EndLoc = Lexer.getLoc();
802 Lex(); // Eat identifier.
803 }
804 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000805 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000806 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000807 case AsmToken::Real: {
808 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000809 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000810 Res = MCConstantExpr::Create(IntVal, getContext());
811 Lex(); // Eat token.
812 return false;
813 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000814 case AsmToken::Dot: {
815 // This is a '.' reference, which references the current PC. Emit a
816 // temporary label to the streamer and refer to it.
817 MCSymbol *Sym = Ctx.CreateTempSymbol();
818 Out.EmitLabel(Sym);
819 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
820 EndLoc = Lexer.getLoc();
821 Lex(); // Eat identifier.
822 return false;
823 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000824 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000825 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000826 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000827 case AsmToken::LBrac:
828 if (!PlatformParser->HasBracketExpressions())
829 return TokError("brackets expression not supported on this target");
830 Lex(); // Eat the '['.
831 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000832 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000833 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000834 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000835 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000836 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000837 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000838 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000839 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000840 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000841 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000842 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000843 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000844 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000845 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000846 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000847 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000848 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000849 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000850 }
851}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000852
Chris Lattnerb4307b32010-01-15 19:28:38 +0000853bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000854 SMLoc EndLoc;
855 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000856}
857
Daniel Dunbarcceba832010-09-17 02:47:07 +0000858const MCExpr *
859AsmParser::ApplyModifierToExpr(const MCExpr *E,
860 MCSymbolRefExpr::VariantKind Variant) {
861 // Recurse over the given expression, rebuilding it to apply the given variant
862 // if there is exactly one symbol.
863 switch (E->getKind()) {
864 case MCExpr::Target:
865 case MCExpr::Constant:
866 return 0;
867
868 case MCExpr::SymbolRef: {
869 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
870
871 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
872 TokError("invalid variant on expression '" +
873 getTok().getIdentifier() + "' (already modified)");
874 return E;
875 }
876
877 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
878 }
879
880 case MCExpr::Unary: {
881 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
882 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
883 if (!Sub)
884 return 0;
885 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
886 }
887
888 case MCExpr::Binary: {
889 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
890 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
891 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
892
893 if (!LHS && !RHS)
894 return 0;
895
896 if (!LHS) LHS = BE->getLHS();
897 if (!RHS) RHS = BE->getRHS();
898
899 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
900 }
901 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000902
Craig Topper85814382012-02-07 05:05:23 +0000903 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000904}
905
Chris Lattner74ec1a32009-06-22 06:32:03 +0000906/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000907///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000908/// expr ::= expr &&,|| expr -> lowest.
909/// expr ::= expr |,^,&,! expr
910/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
911/// expr ::= expr <<,>> expr
912/// expr ::= expr +,- expr
913/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000914/// expr ::= primaryexpr
915///
Chris Lattner54482b42010-01-15 19:39:23 +0000916bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000917 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000918 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000919 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
920 return true;
921
Daniel Dunbarcceba832010-09-17 02:47:07 +0000922 // As a special case, we support 'a op b @ modifier' by rewriting the
923 // expression to include the modifier. This is inefficient, but in general we
924 // expect users to use 'a@modifier op b'.
925 if (Lexer.getKind() == AsmToken::At) {
926 Lex();
927
928 if (Lexer.isNot(AsmToken::Identifier))
929 return TokError("unexpected symbol modifier following '@'");
930
931 MCSymbolRefExpr::VariantKind Variant =
932 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
933 if (Variant == MCSymbolRefExpr::VK_Invalid)
934 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
935
936 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
937 if (!ModifiedRes) {
938 return TokError("invalid modifier '" + getTok().getIdentifier() +
939 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000940 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000941
Daniel Dunbarcceba832010-09-17 02:47:07 +0000942 Res = ModifiedRes;
943 Lex();
944 }
945
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000946 // Try to constant fold it up front, if possible.
947 int64_t Value;
948 if (Res->EvaluateAsAbsolute(Value))
949 Res = MCConstantExpr::Create(Value, getContext());
950
951 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000952}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000953
Chris Lattnerb4307b32010-01-15 19:28:38 +0000954bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000955 Res = 0;
956 return ParseParenExpr(Res, EndLoc) ||
957 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000958}
959
Daniel Dunbar475839e2009-06-29 20:37:27 +0000960bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000961 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000962
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000963 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000964 if (ParseExpression(Expr))
965 return true;
966
Daniel Dunbare00b0112009-10-16 01:57:52 +0000967 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000968 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000969
970 return false;
971}
972
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000973static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000974 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000975 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000976 default:
977 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000978
Jim Grosbachfbe16812011-08-20 16:24:13 +0000979 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000980 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000981 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000982 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000983 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000984 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000985 return 1;
986
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000987
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000988 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000989 //
990 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000991 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000992 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000993 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000994 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000995 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000996 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000997 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000998 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000999 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001000
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001001 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001002 case AsmToken::EqualEqual:
1003 Kind = MCBinaryExpr::EQ;
1004 return 3;
1005 case AsmToken::ExclaimEqual:
1006 case AsmToken::LessGreater:
1007 Kind = MCBinaryExpr::NE;
1008 return 3;
1009 case AsmToken::Less:
1010 Kind = MCBinaryExpr::LT;
1011 return 3;
1012 case AsmToken::LessEqual:
1013 Kind = MCBinaryExpr::LTE;
1014 return 3;
1015 case AsmToken::Greater:
1016 Kind = MCBinaryExpr::GT;
1017 return 3;
1018 case AsmToken::GreaterEqual:
1019 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001020 return 3;
1021
Jim Grosbachfbe16812011-08-20 16:24:13 +00001022 // Intermediate Precedence: <<, >>
1023 case AsmToken::LessLess:
1024 Kind = MCBinaryExpr::Shl;
1025 return 4;
1026 case AsmToken::GreaterGreater:
1027 Kind = MCBinaryExpr::Shr;
1028 return 4;
1029
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001030 // High Intermediate Precedence: +, -
1031 case AsmToken::Plus:
1032 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001033 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001034 case AsmToken::Minus:
1035 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001036 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001037
Jim Grosbachfbe16812011-08-20 16:24:13 +00001038 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001039 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001040 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001041 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001042 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001043 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001044 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001045 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001046 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001047 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001048 }
1049}
1050
1051
1052/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1053/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001054bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1055 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001056 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001057 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001058 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001059
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001060 // If the next token is lower precedence than we are allowed to eat, return
1061 // successfully with what we ate already.
1062 if (TokPrec < Precedence)
1063 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001064
Sean Callanan79ed1a82010-01-19 20:22:31 +00001065 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001066
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001067 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001068 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001069 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001070
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001071 // If BinOp binds less tightly with RHS than the operator after RHS, let
1072 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001073 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001074 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001075 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001076 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001077 }
1078
Daniel Dunbar475839e2009-06-29 20:37:27 +00001079 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001080 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001081 }
1082}
1083
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001084/// ParseStatement:
1085/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001086/// ::= Label* Directive ...Operands... EndOfStatement
1087/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001088bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001089 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001090 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001091 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001092 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001093 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001094
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001095 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001096 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001097 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001098 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001099 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001100 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001101 if (Lexer.is(AsmToken::Hash))
1102 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001103
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001104 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001105 if (Lexer.is(AsmToken::Integer)) {
1106 LocalLabelVal = getTok().getIntVal();
1107 if (LocalLabelVal < 0) {
1108 if (!TheCondState.Ignore)
1109 return TokError("unexpected token at start of statement");
1110 IDVal = "";
1111 }
1112 else {
1113 IDVal = getTok().getString();
1114 Lex(); // Consume the integer token to be used as an identifier token.
1115 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001116 if (!TheCondState.Ignore)
1117 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001118 }
1119 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001120
1121 } else if (Lexer.is(AsmToken::Dot)) {
1122 // Treat '.' as a valid identifier in this context.
1123 Lex();
1124 IDVal = ".";
1125
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001126 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001127 if (!TheCondState.Ignore)
1128 return TokError("unexpected token at start of statement");
1129 IDVal = "";
1130 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001131
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001132
Chris Lattner7834fac2010-04-17 18:14:27 +00001133 // Handle conditional assembly here before checking for skipping. We
1134 // have to do this so that .endif isn't skipped in a ".if 0" block for
1135 // example.
1136 if (IDVal == ".if")
1137 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001138 if (IDVal == ".ifb")
1139 return ParseDirectiveIfb(IDLoc, true);
1140 if (IDVal == ".ifnb")
1141 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001142 if (IDVal == ".ifc")
1143 return ParseDirectiveIfc(IDLoc, true);
1144 if (IDVal == ".ifnc")
1145 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001146 if (IDVal == ".ifdef")
1147 return ParseDirectiveIfdef(IDLoc, true);
1148 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1149 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001150 if (IDVal == ".elseif")
1151 return ParseDirectiveElseIf(IDLoc);
1152 if (IDVal == ".else")
1153 return ParseDirectiveElse(IDLoc);
1154 if (IDVal == ".endif")
1155 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001156
Chris Lattner7834fac2010-04-17 18:14:27 +00001157 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001158 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001159 EatToEndOfStatement();
1160 return false;
1161 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001162
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001163 // FIXME: Recurse on local labels?
1164
1165 // See what kind of statement we have.
1166 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001167 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001168 CheckForValidSection();
1169
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001170 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001171 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001172
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001173 // Diagnose attempt to use '.' as a label.
1174 if (IDVal == ".")
1175 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1176
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001177 // Diagnose attempt to use a variable as a label.
1178 //
1179 // FIXME: Diagnostics. Note the location of the definition as a label.
1180 // FIXME: This doesn't diagnose assignment to a symbol which has been
1181 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001182 MCSymbol *Sym;
1183 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001184 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001185 else
1186 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001187 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001188 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001189
Daniel Dunbar959fd882009-08-26 22:13:22 +00001190 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001191 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001192
Kevin Enderby94c2e852011-12-09 18:09:40 +00001193 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001194 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001195 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001196 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1197 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001198
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001199 // Consume any end of statement token, if present, to avoid spurious
1200 // AddBlankLine calls().
1201 if (Lexer.is(AsmToken::EndOfStatement)) {
1202 Lex();
1203 if (Lexer.is(AsmToken::Eof))
1204 return false;
1205 }
1206
Eli Friedman2128aae2012-10-22 23:58:19 +00001207 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001208 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001209
Daniel Dunbar3f872332009-07-28 16:08:33 +00001210 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001211 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001212 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001213
Nico Weber4c4c7322011-01-28 03:04:41 +00001214 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001215
1216 default: // Normal instruction or directive.
1217 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001218 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001219
1220 // If macros are enabled, check to see if this is a macro instantiation.
1221 if (MacrosEnabled)
1222 if (const Macro *M = MacroMap.lookup(IDVal))
1223 return HandleMacroEntry(IDVal, IDLoc, M);
1224
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001225 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001226 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001227
1228 // Target hook for parsing target specific directives.
1229 if (!getTargetParser().ParseDirective(ID))
1230 return false;
1231
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001232 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001233 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001234 return ParseDirectiveSet(IDVal, true);
1235 if (IDVal == ".equiv")
1236 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001237
Daniel Dunbara0d14262009-06-24 23:30:00 +00001238 // Data directives
1239
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001240 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001241 return ParseDirectiveAscii(IDVal, false);
1242 if (IDVal == ".asciz" || IDVal == ".string")
1243 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001244
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001245 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001246 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001247 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001248 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001249 if (IDVal == ".value")
1250 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001251 if (IDVal == ".2byte")
1252 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001253 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001254 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001255 if (IDVal == ".int")
1256 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001257 if (IDVal == ".4byte")
1258 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001259 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001260 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001261 if (IDVal == ".8byte")
1262 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001263 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001264 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1265 if (IDVal == ".double")
1266 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001267
Eli Friedman5d68ec22010-07-19 04:17:25 +00001268 if (IDVal == ".align") {
1269 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1270 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1271 }
1272 if (IDVal == ".align32") {
1273 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1274 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1275 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001276 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001277 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001278 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001279 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001280 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001281 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001282 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001283 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001284 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001285 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001286 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001287 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1288
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001289 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001290 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001291
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001292 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001293 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001294 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001295 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001296 if (IDVal == ".zero")
1297 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001298
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001299 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001300
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001301 if (IDVal == ".extern") {
1302 EatToEndOfStatement(); // .extern is the default, ignore it.
1303 return false;
1304 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001305 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001306 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001307 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001308 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001309 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001310 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001311 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001312 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001313 if (IDVal == ".symbol_resolver")
1314 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001315 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001316 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001317 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001318 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001319 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001320 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001321 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001322 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001323 if (IDVal == ".weak_def_can_be_hidden")
1324 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001325
Hans Wennborg5cc64912011-06-18 13:51:54 +00001326 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001327 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001328 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001329 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001330
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001331 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001332 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001333 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001334 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001335 if (IDVal == ".incbin")
1336 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001337
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001338 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001339 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001340
Rafael Espindola761cb062012-06-03 23:57:14 +00001341 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001342 if (IDVal == ".rept")
1343 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001344 if (IDVal == ".irp")
1345 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001346 if (IDVal == ".irpc")
1347 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001348 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001349 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001350
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001351 // Look up the handler in the handler table.
1352 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1353 DirectiveMap.lookup(IDVal);
1354 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001355 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001356
Kevin Enderby9c656452009-09-10 20:51:44 +00001357
Jim Grosbach686c0182012-05-01 18:38:27 +00001358 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001359 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001360
Eli Friedman2128aae2012-10-22 23:58:19 +00001361 // _emit
1362 if (ParsingInlineAsm && IDVal == "_emit")
1363 return ParseDirectiveEmit(IDLoc, Info);
1364
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001365 CheckForValidSection();
1366
Chris Lattnera7f13542010-05-19 23:34:33 +00001367 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001368 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001369 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001370 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001371
Chad Rosier6a020a72012-10-25 20:41:34 +00001372 ParseInstructionInfo IInfo(Info.AsmRewrites);
1373 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1374 IDLoc,Info.ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001375
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001376 // Dump the parsed representation, if requested.
1377 if (getShowParsedOperands()) {
1378 SmallString<256> Str;
1379 raw_svector_ostream OS(Str);
1380 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001381 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001382 if (i != 0)
1383 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001384 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001385 }
1386 OS << "]";
1387
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001388 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001389 }
1390
Kevin Enderby613b7572011-11-01 22:27:22 +00001391 // If we are generating dwarf for assembly source files and the current
1392 // section is the initial text section then generate a .loc directive for
1393 // the instruction.
1394 if (!HadError && getContext().getGenDwarfForAssembly() &&
1395 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001396
1397 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1398
1399 // If we previously parsed a cpp hash file line comment then make sure the
1400 // current Dwarf File is for the CppHashFilename if not then emit the
1401 // Dwarf File table for it and adjust the line number for the .loc.
1402 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1403 getContext().getMCDwarfFiles();
1404 if (CppHashFilename.size() != 0) {
1405 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1406 CppHashFilename)
1407 getStreamer().EmitDwarfFileDirective(
1408 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1409
Kevin Enderby32c1a822012-11-05 21:55:41 +00001410 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001411 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1412 }
1413
Kevin Enderby613b7572011-11-01 22:27:22 +00001414 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001415 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001416 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001417 StringRef());
1418 }
1419
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001420 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001421 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001422 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001423 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1424 Info.ParsedOperands,
1425 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001426 ParsingInlineAsm);
1427 }
Chris Lattner98986712010-01-14 22:21:20 +00001428
Chris Lattnercbf8a982010-09-11 16:18:25 +00001429 // Don't skip the rest of the line, the instruction parser is responsible for
1430 // that.
1431 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001432}
Chris Lattner9a023f72009-06-24 04:43:34 +00001433
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001434/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1435/// since they may not be able to be tokenized to get to the end of line token.
1436void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001437 if (!Lexer.is(AsmToken::EndOfStatement))
1438 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001439 // Eat EOL.
1440 Lex();
1441}
1442
1443/// ParseCppHashLineFilenameComment as this:
1444/// ::= # number "filename"
1445/// or just as a full line comment if it doesn't have a number and a string.
1446bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1447 Lex(); // Eat the hash token.
1448
1449 if (getLexer().isNot(AsmToken::Integer)) {
1450 // Consume the line since in cases it is not a well-formed line directive,
1451 // as if were simply a full line comment.
1452 EatToEndOfLine();
1453 return false;
1454 }
1455
1456 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001457 Lex();
1458
1459 if (getLexer().isNot(AsmToken::String)) {
1460 EatToEndOfLine();
1461 return false;
1462 }
1463
1464 StringRef Filename = getTok().getString();
1465 // Get rid of the enclosing quotes.
1466 Filename = Filename.substr(1, Filename.size()-2);
1467
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001468 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1469 CppHashLoc = L;
1470 CppHashFilename = Filename;
1471 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001472 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001473
1474 // Ignore any trailing characters, they're just comment.
1475 EatToEndOfLine();
1476 return false;
1477}
1478
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001479/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001480/// for the Filename and LineNo if any in the diagnostic.
1481void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1482 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1483 raw_ostream &OS = errs();
1484
1485 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1486 const SMLoc &DiagLoc = Diag.getLoc();
1487 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1488 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1489
1490 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1491 // before printing the message.
1492 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001493 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001494 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1495 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1496 }
1497
1498 // If we have not parsed a cpp hash line filename comment or the source
1499 // manager changed or buffer changed (like in a nested include) then just
1500 // print the normal diagnostic using its Filename and LineNo.
1501 if (!Parser->CppHashLineNumber ||
1502 &DiagSrcMgr != &Parser->SrcMgr ||
1503 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001504 if (Parser->SavedDiagHandler)
1505 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1506 else
1507 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001508 return;
1509 }
1510
1511 // Use the CppHashFilename and calculate a line number based on the
1512 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1513 // the diagnostic.
1514 const std::string Filename = Parser->CppHashFilename;
1515
1516 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1517 int CppHashLocLineNo =
1518 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1519 int LineNo = Parser->CppHashLineNumber - 1 +
1520 (DiagLocLineNo - CppHashLocLineNo);
1521
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001522 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1523 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001524 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001525 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001526
Benjamin Kramer04a04262011-10-16 10:48:29 +00001527 if (Parser->SavedDiagHandler)
1528 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1529 else
1530 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001531}
1532
Rafael Espindola799aacf2012-08-21 18:29:30 +00001533// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1534// difference being that that function accepts '@' as part of identifiers and
1535// we can't do that. AsmLexer.cpp should probably be changed to handle
1536// '@' as a special case when needed.
1537static bool isIdentifierChar(char c) {
1538 return isalnum(c) || c == '_' || c == '$' || c == '.';
1539}
1540
Rafael Espindola761cb062012-06-03 23:57:14 +00001541bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001542 const MacroParameters &Parameters,
1543 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001544 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001545 unsigned NParameters = Parameters.size();
1546 if (NParameters != 0 && NParameters != A.size())
1547 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001548
Preston Gurd7b6f2032012-09-19 20:36:12 +00001549 // A macro without parameters is handled differently on Darwin:
1550 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001551 while (!Body.empty()) {
1552 // Scan for the next substitution.
1553 std::size_t End = Body.size(), Pos = 0;
1554 for (; Pos != End; ++Pos) {
1555 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001556 if (!NParameters) {
1557 // This macro has no parameters, look for $0, $1, etc.
1558 if (Body[Pos] != '$' || Pos + 1 == End)
1559 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001560
Rafael Espindola65366442011-06-05 02:43:45 +00001561 char Next = Body[Pos + 1];
1562 if (Next == '$' || Next == 'n' || isdigit(Next))
1563 break;
1564 } else {
1565 // This macro has parameters, look for \foo, \bar, etc.
1566 if (Body[Pos] == '\\' && Pos + 1 != End)
1567 break;
1568 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001569 }
1570
1571 // Add the prefix.
1572 OS << Body.slice(0, Pos);
1573
1574 // Check if we reached the end.
1575 if (Pos == End)
1576 break;
1577
Rafael Espindola65366442011-06-05 02:43:45 +00001578 if (!NParameters) {
1579 switch (Body[Pos+1]) {
1580 // $$ => $
1581 case '$':
1582 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001583 break;
1584
Rafael Espindola65366442011-06-05 02:43:45 +00001585 // $n => number of arguments
1586 case 'n':
1587 OS << A.size();
1588 break;
1589
1590 // $[0-9] => argument
1591 default: {
1592 // Missing arguments are ignored.
1593 unsigned Index = Body[Pos+1] - '0';
1594 if (Index >= A.size())
1595 break;
1596
1597 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001598 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001599 ie = A[Index].end(); it != ie; ++it)
1600 OS << it->getString();
1601 break;
1602 }
1603 }
1604 Pos += 2;
1605 } else {
1606 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001607 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001608 ++I;
1609
1610 const char *Begin = Body.data() + Pos +1;
1611 StringRef Argument(Begin, I - (Pos +1));
1612 unsigned Index = 0;
1613 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001614 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001615 break;
1616
Preston Gurd7b6f2032012-09-19 20:36:12 +00001617 if (Index == NParameters) {
1618 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1619 Pos += 3;
1620 else {
1621 OS << '\\' << Argument;
1622 Pos = I;
1623 }
1624 } else {
1625 for (MacroArgument::const_iterator it = A[Index].begin(),
1626 ie = A[Index].end(); it != ie; ++it)
1627 if (it->getKind() == AsmToken::String)
1628 OS << it->getStringContents();
1629 else
1630 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001631
Preston Gurd7b6f2032012-09-19 20:36:12 +00001632 Pos += 1 + Argument.size();
1633 }
Rafael Espindola65366442011-06-05 02:43:45 +00001634 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001635 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001636 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001637 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001638
Rafael Espindola65366442011-06-05 02:43:45 +00001639 return false;
1640}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001641
Rafael Espindola65366442011-06-05 02:43:45 +00001642MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1643 MemoryBuffer *I)
1644 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1645{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001646}
1647
Preston Gurd7b6f2032012-09-19 20:36:12 +00001648static bool IsOperator(AsmToken::TokenKind kind)
1649{
1650 switch (kind)
1651 {
1652 default:
1653 return false;
1654 case AsmToken::Plus:
1655 case AsmToken::Minus:
1656 case AsmToken::Tilde:
1657 case AsmToken::Slash:
1658 case AsmToken::Star:
1659 case AsmToken::Dot:
1660 case AsmToken::Equal:
1661 case AsmToken::EqualEqual:
1662 case AsmToken::Pipe:
1663 case AsmToken::PipePipe:
1664 case AsmToken::Caret:
1665 case AsmToken::Amp:
1666 case AsmToken::AmpAmp:
1667 case AsmToken::Exclaim:
1668 case AsmToken::ExclaimEqual:
1669 case AsmToken::Percent:
1670 case AsmToken::Less:
1671 case AsmToken::LessEqual:
1672 case AsmToken::LessLess:
1673 case AsmToken::LessGreater:
1674 case AsmToken::Greater:
1675 case AsmToken::GreaterEqual:
1676 case AsmToken::GreaterGreater:
1677 return true;
1678 }
1679}
1680
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001681/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1682/// This is used for both default macro parameter values and the
1683/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001684bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1685 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001686 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001687 unsigned AddTokens = 0;
1688
1689 // gas accepts arguments separated by whitespace, except on Darwin
1690 if (!IsDarwin)
1691 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001692
1693 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001694 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1695 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001696 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001697 }
1698
1699 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1700 // Spaces and commas cannot be mixed to delimit parameters
1701 if (ArgumentDelimiter == AsmToken::Eof)
1702 ArgumentDelimiter = AsmToken::Comma;
1703 else if (ArgumentDelimiter != AsmToken::Comma) {
1704 Lexer.setSkipSpace(true);
1705 return TokError("expected ' ' for macro argument separator");
1706 }
1707 break;
1708 }
1709
1710 if (Lexer.is(AsmToken::Space)) {
1711 Lex(); // Eat spaces
1712
1713 // Spaces can delimit parameters, but could also be part an expression.
1714 // If the token after a space is an operator, add the token and the next
1715 // one into this argument
1716 if (ArgumentDelimiter == AsmToken::Space ||
1717 ArgumentDelimiter == AsmToken::Eof) {
1718 if (IsOperator(Lexer.getKind())) {
1719 // Check to see whether the token is used as an operator,
1720 // or part of an identifier
1721 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1722 if (*NextChar == ' ')
1723 AddTokens = 2;
1724 }
1725
1726 if (!AddTokens && ParenLevel == 0) {
1727 if (ArgumentDelimiter == AsmToken::Eof &&
1728 !IsOperator(Lexer.getKind()))
1729 ArgumentDelimiter = AsmToken::Space;
1730 break;
1731 }
1732 }
1733 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001734
1735 // HandleMacroEntry relies on not advancing the lexer here
1736 // to be able to fill in the remaining default parameter values
1737 if (Lexer.is(AsmToken::EndOfStatement))
1738 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001739
1740 // Adjust the current parentheses level.
1741 if (Lexer.is(AsmToken::LParen))
1742 ++ParenLevel;
1743 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1744 --ParenLevel;
1745
1746 // Append the token to the current argument list.
1747 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001748 if (AddTokens)
1749 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001750 Lex();
1751 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001752
1753 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001754 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001755 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001756 return false;
1757}
1758
1759// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001760bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001761 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001762 // Argument delimiter is initially unknown. It will be set by
1763 // ParseMacroArgument()
1764 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001765
1766 // Parse two kinds of macro invocations:
1767 // - macros defined without any parameters accept an arbitrary number of them
1768 // - macros defined with parameters accept at most that many of them
1769 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1770 ++Parameter) {
1771 MacroArgument MA;
1772
Preston Gurd7b6f2032012-09-19 20:36:12 +00001773 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001774 return true;
1775
Preston Gurd6c9176a2012-09-19 20:29:04 +00001776 if (!MA.empty() || !NParameters)
1777 A.push_back(MA);
1778 else if (NParameters) {
1779 if (!M->Parameters[Parameter].second.empty())
1780 A.push_back(M->Parameters[Parameter].second);
1781 }
Jim Grosbach97146442012-07-30 22:44:17 +00001782
Preston Gurd6c9176a2012-09-19 20:29:04 +00001783 // At the end of the statement, fill in remaining arguments that have
1784 // default values. If there aren't any, then the next argument is
1785 // required but missing
1786 if (Lexer.is(AsmToken::EndOfStatement)) {
1787 if (NParameters && Parameter < NParameters - 1) {
1788 if (M->Parameters[Parameter + 1].second.empty())
1789 return TokError("macro argument '" +
1790 Twine(M->Parameters[Parameter + 1].first) +
1791 "' is missing");
1792 else
1793 continue;
1794 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001795 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001796 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001797
1798 if (Lexer.is(AsmToken::Comma))
1799 Lex();
1800 }
1801 return TokError("Too many arguments");
1802}
1803
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001804bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1805 const Macro *M) {
1806 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1807 // this, although we should protect against infinite loops.
1808 if (ActiveMacros.size() == 20)
1809 return TokError("macros cannot be nested more than 20 levels deep");
1810
Rafael Espindola8a403d32012-08-08 14:51:03 +00001811 MacroArguments A;
1812 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001813 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001814
Jim Grosbach97146442012-07-30 22:44:17 +00001815 // Remove any trailing empty arguments. Do this after-the-fact as we have
1816 // to keep empty arguments in the middle of the list or positionality
1817 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001818 while (!A.empty() && A.back().empty())
1819 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001820
Rafael Espindola65366442011-06-05 02:43:45 +00001821 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1822 // to hold the macro body with substitutions.
1823 SmallString<256> Buf;
1824 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001825 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001826
Rafael Espindola8a403d32012-08-08 14:51:03 +00001827 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001828 return true;
1829
Rafael Espindola761cb062012-06-03 23:57:14 +00001830 // We include the .endmacro in the buffer as our queue to exit the macro
1831 // instantiation.
1832 OS << ".endmacro\n";
1833
Rafael Espindola65366442011-06-05 02:43:45 +00001834 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001835 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001836
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001837 // Create the macro instantiation object and add to the current macro
1838 // instantiation stack.
1839 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001840 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001841 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001842 ActiveMacros.push_back(MI);
1843
1844 // Jump to the macro instantiation and prime the lexer.
1845 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1846 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1847 Lex();
1848
1849 return false;
1850}
1851
1852void AsmParser::HandleMacroExit() {
1853 // Jump to the EndOfStatement we should return to, and consume it.
1854 JumpToLoc(ActiveMacros.back()->ExitLoc);
1855 Lex();
1856
1857 // Pop the instantiation entry.
1858 delete ActiveMacros.back();
1859 ActiveMacros.pop_back();
1860}
1861
Rafael Espindolae71cc862012-01-28 05:57:00 +00001862static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001863 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001864 case MCExpr::Binary: {
1865 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1866 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001867 break;
1868 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001869 case MCExpr::Target:
1870 case MCExpr::Constant:
1871 return false;
1872 case MCExpr::SymbolRef: {
1873 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001874 if (S.isVariable())
1875 return IsUsedIn(Sym, S.getVariableValue());
1876 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001877 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001878 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001879 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001880 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001881
1882 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001883}
1884
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001885bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1886 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001887 // FIXME: Use better location, we should use proper tokens.
1888 SMLoc EqualLoc = Lexer.getLoc();
1889
Daniel Dunbar821e3332009-08-31 08:09:28 +00001890 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001891 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001892 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001893
Rafael Espindolae71cc862012-01-28 05:57:00 +00001894 // Note: we don't count b as used in "a = b". This is to allow
1895 // a = b
1896 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001897
Daniel Dunbar3f872332009-07-28 16:08:33 +00001898 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001899 return TokError("unexpected token in assignment");
1900
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001901 // Error on assignment to '.'.
1902 if (Name == ".") {
1903 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1904 "(use '.space' or '.org').)"));
1905 }
1906
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001907 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001908 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001909
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001910 // Validate that the LHS is allowed to be a variable (either it has not been
1911 // used as a symbol, or it is an absolute symbol).
1912 MCSymbol *Sym = getContext().LookupSymbol(Name);
1913 if (Sym) {
1914 // Diagnose assignment to a label.
1915 //
1916 // FIXME: Diagnostics. Note the location of the definition as a label.
1917 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001918 if (IsUsedIn(Sym, Value))
1919 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1920 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001921 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001922 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1923 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001924 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001925 return Error(EqualLoc, "redefinition of '" + Name + "'");
1926 else if (!Sym->isVariable())
1927 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001928 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001929 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1930 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001931
1932 // Don't count these checks as uses.
1933 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001934 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001935 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001936
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001937 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001938
1939 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001940 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001941 if (NoDeadStrip)
1942 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1943
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001944
1945 return false;
1946}
1947
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001948/// ParseIdentifier:
1949/// ::= identifier
1950/// ::= string
1951bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001952 // The assembler has relaxed rules for accepting identifiers, in particular we
1953 // allow things like '.globl $foo', which would normally be separate
1954 // tokens. At this level, we have already lexed so we cannot (currently)
1955 // handle this as a context dependent token, instead we detect adjacent tokens
1956 // and return the combined identifier.
1957 if (Lexer.is(AsmToken::Dollar)) {
1958 SMLoc DollarLoc = getLexer().getLoc();
1959
1960 // Consume the dollar sign, and check for a following identifier.
1961 Lex();
1962 if (Lexer.isNot(AsmToken::Identifier))
1963 return true;
1964
1965 // We have a '$' followed by an identifier, make sure they are adjacent.
1966 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1967 return true;
1968
1969 // Construct the joined identifier and consume the token.
1970 Res = StringRef(DollarLoc.getPointer(),
1971 getTok().getIdentifier().size() + 1);
1972 Lex();
1973 return false;
1974 }
1975
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001976 if (Lexer.isNot(AsmToken::Identifier) &&
1977 Lexer.isNot(AsmToken::String))
1978 return true;
1979
Sean Callanan18b83232010-01-19 21:44:56 +00001980 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001981
Sean Callanan79ed1a82010-01-19 20:22:31 +00001982 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001983
1984 return false;
1985}
1986
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001987/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001988/// ::= .equ identifier ',' expression
1989/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001990/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001991bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001992 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001993
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001994 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001995 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001996
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001997 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001998 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001999 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002000
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002001 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002002}
2003
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002004bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002005 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002006
2007 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002008 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002009 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2010 if (Str[i] != '\\') {
2011 Data += Str[i];
2012 continue;
2013 }
2014
2015 // Recognize escaped characters. Note that this escape semantics currently
2016 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2017 ++i;
2018 if (i == e)
2019 return TokError("unexpected backslash at end of string");
2020
2021 // Recognize octal sequences.
2022 if ((unsigned) (Str[i] - '0') <= 7) {
2023 // Consume up to three octal characters.
2024 unsigned Value = Str[i] - '0';
2025
2026 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2027 ++i;
2028 Value = Value * 8 + (Str[i] - '0');
2029
2030 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2031 ++i;
2032 Value = Value * 8 + (Str[i] - '0');
2033 }
2034 }
2035
2036 if (Value > 255)
2037 return TokError("invalid octal escape sequence (out of range)");
2038
2039 Data += (unsigned char) Value;
2040 continue;
2041 }
2042
2043 // Otherwise recognize individual escapes.
2044 switch (Str[i]) {
2045 default:
2046 // Just reject invalid escape sequences for now.
2047 return TokError("invalid escape sequence (unrecognized character)");
2048
2049 case 'b': Data += '\b'; break;
2050 case 'f': Data += '\f'; break;
2051 case 'n': Data += '\n'; break;
2052 case 'r': Data += '\r'; break;
2053 case 't': Data += '\t'; break;
2054 case '"': Data += '"'; break;
2055 case '\\': Data += '\\'; break;
2056 }
2057 }
2058
2059 return false;
2060}
2061
Daniel Dunbara0d14262009-06-24 23:30:00 +00002062/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002063/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2064bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002065 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002066 CheckForValidSection();
2067
Daniel Dunbara0d14262009-06-24 23:30:00 +00002068 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002069 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002070 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002071
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002072 std::string Data;
2073 if (ParseEscapedString(Data))
2074 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002075
2076 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002077 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002078 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2079
Sean Callanan79ed1a82010-01-19 20:22:31 +00002080 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002081
2082 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002083 break;
2084
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002085 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002086 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002087 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002088 }
2089 }
2090
Sean Callanan79ed1a82010-01-19 20:22:31 +00002091 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002092 return false;
2093}
2094
2095/// ParseDirectiveValue
2096/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2097bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002098 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002099 CheckForValidSection();
2100
Daniel Dunbara0d14262009-06-24 23:30:00 +00002101 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002102 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002103 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002104 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002105 return true;
2106
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002107 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002108 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2109 assert(Size <= 8 && "Invalid size");
2110 uint64_t IntValue = MCE->getValue();
2111 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2112 return Error(ExprLoc, "literal value out of range for directive");
2113 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2114 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002115 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002116
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002117 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002118 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002119
Daniel Dunbara0d14262009-06-24 23:30:00 +00002120 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002121 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002122 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002123 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002124 }
2125 }
2126
Sean Callanan79ed1a82010-01-19 20:22:31 +00002127 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002128 return false;
2129}
2130
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002131/// ParseDirectiveRealValue
2132/// ::= (.single | .double) [ expression (, expression)* ]
2133bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2134 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2135 CheckForValidSection();
2136
2137 for (;;) {
2138 // We don't truly support arithmetic on floating point expressions, so we
2139 // have to manually parse unary prefixes.
2140 bool IsNeg = false;
2141 if (getLexer().is(AsmToken::Minus)) {
2142 Lex();
2143 IsNeg = true;
2144 } else if (getLexer().is(AsmToken::Plus))
2145 Lex();
2146
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002147 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002148 getLexer().isNot(AsmToken::Real) &&
2149 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002150 return TokError("unexpected token in directive");
2151
2152 // Convert to an APFloat.
2153 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002154 StringRef IDVal = getTok().getString();
2155 if (getLexer().is(AsmToken::Identifier)) {
2156 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2157 Value = APFloat::getInf(Semantics);
2158 else if (!IDVal.compare_lower("nan"))
2159 Value = APFloat::getNaN(Semantics, false, ~0);
2160 else
2161 return TokError("invalid floating point literal");
2162 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002163 APFloat::opInvalidOp)
2164 return TokError("invalid floating point literal");
2165 if (IsNeg)
2166 Value.changeSign();
2167
2168 // Consume the numeric token.
2169 Lex();
2170
2171 // Emit the value as an integer.
2172 APInt AsInt = Value.bitcastToAPInt();
2173 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2174 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2175
2176 if (getLexer().is(AsmToken::EndOfStatement))
2177 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002178
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002179 if (getLexer().isNot(AsmToken::Comma))
2180 return TokError("unexpected token in directive");
2181 Lex();
2182 }
2183 }
2184
2185 Lex();
2186 return false;
2187}
2188
Daniel Dunbara0d14262009-06-24 23:30:00 +00002189/// ParseDirectiveSpace
2190/// ::= .space expression [ , expression ]
2191bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002192 CheckForValidSection();
2193
Daniel Dunbara0d14262009-06-24 23:30:00 +00002194 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002195 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002196 return true;
2197
2198 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002199 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2200 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002201 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002202 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002203
Daniel Dunbar475839e2009-06-29 20:37:27 +00002204 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002205 return true;
2206
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002207 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002208 return TokError("unexpected token in '.space' directive");
2209 }
2210
Sean Callanan79ed1a82010-01-19 20:22:31 +00002211 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002212
2213 if (NumBytes <= 0)
2214 return TokError("invalid number of bytes in '.space' directive");
2215
2216 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002217 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002218
2219 return false;
2220}
2221
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002222/// ParseDirectiveZero
2223/// ::= .zero expression
2224bool AsmParser::ParseDirectiveZero() {
2225 CheckForValidSection();
2226
2227 int64_t NumBytes;
2228 if (ParseAbsoluteExpression(NumBytes))
2229 return true;
2230
Rafael Espindolae452b172010-10-05 19:42:57 +00002231 int64_t Val = 0;
2232 if (getLexer().is(AsmToken::Comma)) {
2233 Lex();
2234 if (ParseAbsoluteExpression(Val))
2235 return true;
2236 }
2237
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002238 if (getLexer().isNot(AsmToken::EndOfStatement))
2239 return TokError("unexpected token in '.zero' directive");
2240
2241 Lex();
2242
Rafael Espindolae452b172010-10-05 19:42:57 +00002243 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002244
2245 return false;
2246}
2247
Daniel Dunbara0d14262009-06-24 23:30:00 +00002248/// ParseDirectiveFill
2249/// ::= .fill expression , expression , expression
2250bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002251 CheckForValidSection();
2252
Daniel Dunbara0d14262009-06-24 23:30:00 +00002253 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002254 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002255 return true;
2256
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002257 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002258 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002259 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002260
Daniel Dunbara0d14262009-06-24 23:30:00 +00002261 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002262 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002263 return true;
2264
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002265 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002266 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002267 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002268
Daniel Dunbara0d14262009-06-24 23:30:00 +00002269 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002270 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002271 return true;
2272
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002273 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002274 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002275
Sean Callanan79ed1a82010-01-19 20:22:31 +00002276 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002277
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002278 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2279 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002280
2281 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002282 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002283
2284 return false;
2285}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002286
2287/// ParseDirectiveOrg
2288/// ::= .org expression [ , expression ]
2289bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002290 CheckForValidSection();
2291
Daniel Dunbar821e3332009-08-31 08:09:28 +00002292 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002293 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002294 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002295 return true;
2296
2297 // Parse optional fill expression.
2298 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002299 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2300 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002301 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002302 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002303
Daniel Dunbar475839e2009-06-29 20:37:27 +00002304 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002305 return true;
2306
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002307 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002308 return TokError("unexpected token in '.org' directive");
2309 }
2310
Sean Callanan79ed1a82010-01-19 20:22:31 +00002311 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002312
Jim Grosbachebd4c052012-01-27 00:37:08 +00002313 // Only limited forms of relocatable expressions are accepted here, it
2314 // has to be relative to the current section. The streamer will return
2315 // 'true' if the expression wasn't evaluatable.
2316 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2317 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002318
2319 return false;
2320}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002321
2322/// ParseDirectiveAlign
2323/// ::= {.align, ...} expression [ , expression [ , expression ]]
2324bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002325 CheckForValidSection();
2326
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002327 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002328 int64_t Alignment;
2329 if (ParseAbsoluteExpression(Alignment))
2330 return true;
2331
2332 SMLoc MaxBytesLoc;
2333 bool HasFillExpr = false;
2334 int64_t FillExpr = 0;
2335 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002336 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2337 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002338 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002339 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002340
2341 // The fill expression can be omitted while specifying a maximum number of
2342 // alignment bytes, e.g:
2343 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002344 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002345 HasFillExpr = true;
2346 if (ParseAbsoluteExpression(FillExpr))
2347 return true;
2348 }
2349
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002350 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2351 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002352 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002353 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002354
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002355 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002356 if (ParseAbsoluteExpression(MaxBytesToFill))
2357 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002358
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002359 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002360 return TokError("unexpected token in directive");
2361 }
2362 }
2363
Sean Callanan79ed1a82010-01-19 20:22:31 +00002364 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002365
Daniel Dunbar648ac512010-05-17 21:54:30 +00002366 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002367 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002368
2369 // Compute alignment in bytes.
2370 if (IsPow2) {
2371 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002372 if (Alignment >= 32) {
2373 Error(AlignmentLoc, "invalid alignment value");
2374 Alignment = 31;
2375 }
2376
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002377 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002378 }
2379
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002380 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002381 if (MaxBytesLoc.isValid()) {
2382 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002383 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2384 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002385 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002386 }
2387
2388 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002389 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2390 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002391 MaxBytesToFill = 0;
2392 }
2393 }
2394
Daniel Dunbar648ac512010-05-17 21:54:30 +00002395 // Check whether we should use optimal code alignment for this .align
2396 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002397 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002398 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2399 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002400 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002401 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002402 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002403 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2404 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002405 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002406
2407 return false;
2408}
2409
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002410/// ParseDirectiveSymbolAttribute
2411/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002412bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002413 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002414 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002415 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002416 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002417
2418 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002419 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002420
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002421 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002422
Jim Grosbach10ec6502011-09-15 17:56:49 +00002423 // Assembler local symbols don't make any sense here. Complain loudly.
2424 if (Sym->isTemporary())
2425 return Error(Loc, "non-local symbol required in directive");
2426
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002427 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002428
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002429 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002430 break;
2431
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002432 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002433 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002434 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002435 }
2436 }
2437
Sean Callanan79ed1a82010-01-19 20:22:31 +00002438 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002439 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002440}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002441
2442/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002443/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2444bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002445 CheckForValidSection();
2446
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002447 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002448 StringRef Name;
2449 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002450 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002451
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002452 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002453 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002454
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002455 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002456 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002457 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002458
2459 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002460 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002461 if (ParseAbsoluteExpression(Size))
2462 return true;
2463
2464 int64_t Pow2Alignment = 0;
2465 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002466 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002467 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002468 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002469 if (ParseAbsoluteExpression(Pow2Alignment))
2470 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002471
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002472 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2473 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002474 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2475
Chris Lattner258281d2010-01-19 06:22:22 +00002476 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002477 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2478 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002479 if (!isPowerOf2_64(Pow2Alignment))
2480 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2481 Pow2Alignment = Log2_64(Pow2Alignment);
2482 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002483 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002484
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002485 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002486 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002487
Sean Callanan79ed1a82010-01-19 20:22:31 +00002488 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002489
Chris Lattner1fc3d752009-07-09 17:25:12 +00002490 // NOTE: a size of zero for a .comm should create a undefined symbol
2491 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002492 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002493 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2494 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002495
Eric Christopherc260a3e2010-05-14 01:38:54 +00002496 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002497 // may internally end up wanting an alignment in bytes.
2498 // FIXME: Diagnose overflow.
2499 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002500 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2501 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002502
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002503 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002504 return Error(IDLoc, "invalid symbol redefinition");
2505
Chris Lattner1fc3d752009-07-09 17:25:12 +00002506 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002507 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002508 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002509 return false;
2510 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002511
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002512 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002513 return false;
2514}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002515
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002516/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002517/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002518bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002519 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002520 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002521
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002522 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002523 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002524 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002525
Sean Callanan79ed1a82010-01-19 20:22:31 +00002526 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002527
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002528 if (Str.empty())
2529 Error(Loc, ".abort detected. Assembly stopping.");
2530 else
2531 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002532 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002533
2534 return false;
2535}
Kevin Enderby71148242009-07-14 21:35:03 +00002536
Kevin Enderby1f049b22009-07-14 23:21:55 +00002537/// ParseDirectiveInclude
2538/// ::= .include "filename"
2539bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002540 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002541 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002542
Sean Callanan18b83232010-01-19 21:44:56 +00002543 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002544 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002545 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002546
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002547 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002548 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002549
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002550 // Strip the quotes.
2551 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002552
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002553 // Attempt to switch the lexer to the included file before consuming the end
2554 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002555 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002556 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002557 return true;
2558 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002559
2560 return false;
2561}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002562
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002563/// ParseDirectiveIncbin
2564/// ::= .incbin "filename"
2565bool AsmParser::ParseDirectiveIncbin() {
2566 if (getLexer().isNot(AsmToken::String))
2567 return TokError("expected string in '.incbin' directive");
2568
2569 std::string Filename = getTok().getString();
2570 SMLoc IncbinLoc = getLexer().getLoc();
2571 Lex();
2572
2573 if (getLexer().isNot(AsmToken::EndOfStatement))
2574 return TokError("unexpected token in '.incbin' directive");
2575
2576 // Strip the quotes.
2577 Filename = Filename.substr(1, Filename.size()-2);
2578
2579 // Attempt to process the included file.
2580 if (ProcessIncbinFile(Filename)) {
2581 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2582 return true;
2583 }
2584
2585 return false;
2586}
2587
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002588/// ParseDirectiveIf
2589/// ::= .if expression
2590bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002591 TheCondStack.push_back(TheCondState);
2592 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002593 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002594 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002595 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002596 int64_t ExprValue;
2597 if (ParseAbsoluteExpression(ExprValue))
2598 return true;
2599
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002600 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002601 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002602
Sean Callanan79ed1a82010-01-19 20:22:31 +00002603 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002604
2605 TheCondState.CondMet = ExprValue;
2606 TheCondState.Ignore = !TheCondState.CondMet;
2607 }
2608
2609 return false;
2610}
2611
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002612/// ParseDirectiveIfb
2613/// ::= .ifb string
2614bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2615 TheCondStack.push_back(TheCondState);
2616 TheCondState.TheCond = AsmCond::IfCond;
2617
Benjamin Kramer29739e72012-05-12 16:52:21 +00002618 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002619 EatToEndOfStatement();
2620 } else {
2621 StringRef Str = ParseStringToEndOfStatement();
2622
2623 if (getLexer().isNot(AsmToken::EndOfStatement))
2624 return TokError("unexpected token in '.ifb' directive");
2625
2626 Lex();
2627
2628 TheCondState.CondMet = ExpectBlank == Str.empty();
2629 TheCondState.Ignore = !TheCondState.CondMet;
2630 }
2631
2632 return false;
2633}
2634
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002635/// ParseDirectiveIfc
2636/// ::= .ifc string1, string2
2637bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2638 TheCondStack.push_back(TheCondState);
2639 TheCondState.TheCond = AsmCond::IfCond;
2640
Benjamin Kramer29739e72012-05-12 16:52:21 +00002641 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002642 EatToEndOfStatement();
2643 } else {
2644 StringRef Str1 = ParseStringToComma();
2645
2646 if (getLexer().isNot(AsmToken::Comma))
2647 return TokError("unexpected token in '.ifc' directive");
2648
2649 Lex();
2650
2651 StringRef Str2 = ParseStringToEndOfStatement();
2652
2653 if (getLexer().isNot(AsmToken::EndOfStatement))
2654 return TokError("unexpected token in '.ifc' directive");
2655
2656 Lex();
2657
2658 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2659 TheCondState.Ignore = !TheCondState.CondMet;
2660 }
2661
2662 return false;
2663}
2664
2665/// ParseDirectiveIfdef
2666/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002667bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2668 StringRef Name;
2669 TheCondStack.push_back(TheCondState);
2670 TheCondState.TheCond = AsmCond::IfCond;
2671
2672 if (TheCondState.Ignore) {
2673 EatToEndOfStatement();
2674 } else {
2675 if (ParseIdentifier(Name))
2676 return TokError("expected identifier after '.ifdef'");
2677
2678 Lex();
2679
2680 MCSymbol *Sym = getContext().LookupSymbol(Name);
2681
2682 if (expect_defined)
2683 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2684 else
2685 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2686 TheCondState.Ignore = !TheCondState.CondMet;
2687 }
2688
2689 return false;
2690}
2691
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002692/// ParseDirectiveElseIf
2693/// ::= .elseif expression
2694bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2695 if (TheCondState.TheCond != AsmCond::IfCond &&
2696 TheCondState.TheCond != AsmCond::ElseIfCond)
2697 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2698 " an .elseif");
2699 TheCondState.TheCond = AsmCond::ElseIfCond;
2700
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002701 bool LastIgnoreState = false;
2702 if (!TheCondStack.empty())
2703 LastIgnoreState = TheCondStack.back().Ignore;
2704 if (LastIgnoreState || TheCondState.CondMet) {
2705 TheCondState.Ignore = true;
2706 EatToEndOfStatement();
2707 }
2708 else {
2709 int64_t ExprValue;
2710 if (ParseAbsoluteExpression(ExprValue))
2711 return true;
2712
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002713 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002714 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002715
Sean Callanan79ed1a82010-01-19 20:22:31 +00002716 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002717 TheCondState.CondMet = ExprValue;
2718 TheCondState.Ignore = !TheCondState.CondMet;
2719 }
2720
2721 return false;
2722}
2723
2724/// ParseDirectiveElse
2725/// ::= .else
2726bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002727 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002728 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002729
Sean Callanan79ed1a82010-01-19 20:22:31 +00002730 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002731
2732 if (TheCondState.TheCond != AsmCond::IfCond &&
2733 TheCondState.TheCond != AsmCond::ElseIfCond)
2734 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2735 ".elseif");
2736 TheCondState.TheCond = AsmCond::ElseCond;
2737 bool LastIgnoreState = false;
2738 if (!TheCondStack.empty())
2739 LastIgnoreState = TheCondStack.back().Ignore;
2740 if (LastIgnoreState || TheCondState.CondMet)
2741 TheCondState.Ignore = true;
2742 else
2743 TheCondState.Ignore = false;
2744
2745 return false;
2746}
2747
2748/// ParseDirectiveEndIf
2749/// ::= .endif
2750bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002751 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002752 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002753
Sean Callanan79ed1a82010-01-19 20:22:31 +00002754 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002755
2756 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2757 TheCondStack.empty())
2758 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2759 ".else");
2760 if (!TheCondStack.empty()) {
2761 TheCondState = TheCondStack.back();
2762 TheCondStack.pop_back();
2763 }
2764
2765 return false;
2766}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002767
2768/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002769/// ::= .file [number] filename
2770/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002771bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002772 // FIXME: I'm not sure what this is.
2773 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002774 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002775 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002776 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002777 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002778
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002779 if (FileNumber < 1)
2780 return TokError("file number less than one");
2781 }
2782
Daniel Dunbareceec052010-07-12 17:45:27 +00002783 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002784 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002785
Nick Lewycky44d798d2011-10-17 23:05:28 +00002786 // Usually the directory and filename together, otherwise just the directory.
2787 StringRef Path = getTok().getString();
2788 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002789 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002790
Nick Lewycky44d798d2011-10-17 23:05:28 +00002791 StringRef Directory;
2792 StringRef Filename;
2793 if (getLexer().is(AsmToken::String)) {
2794 if (FileNumber == -1)
2795 return TokError("explicit path specified, but no file number");
2796 Filename = getTok().getString();
2797 Filename = Filename.substr(1, Filename.size()-2);
2798 Directory = Path;
2799 Lex();
2800 } else {
2801 Filename = Path;
2802 }
2803
Daniel Dunbareceec052010-07-12 17:45:27 +00002804 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002805 return TokError("unexpected token in '.file' directive");
2806
Chris Lattnerd32e8032010-01-25 19:02:58 +00002807 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002808 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002809 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002810 if (getContext().getGenDwarfForAssembly() == true)
2811 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2812 "used to generate dwarf debug info for assembly code");
2813
Nick Lewycky44d798d2011-10-17 23:05:28 +00002814 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002815 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002816 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002817
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002818 return false;
2819}
2820
2821/// ParseDirectiveLine
2822/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002823bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002824 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2825 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002826 return TokError("unexpected token in '.line' directive");
2827
Sean Callanan18b83232010-01-19 21:44:56 +00002828 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002829 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002830 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002831
2832 // FIXME: Do something with the .line.
2833 }
2834
Daniel Dunbareceec052010-07-12 17:45:27 +00002835 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002836 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002837
2838 return false;
2839}
2840
2841
2842/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002843/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002844/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2845/// The first number is a file number, must have been previously assigned with
2846/// a .file directive, the second number is the line number and optionally the
2847/// third number is a column position (zero if not specified). The remaining
2848/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002849bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002850
Daniel Dunbareceec052010-07-12 17:45:27 +00002851 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002852 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002853 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002854 if (FileNumber < 1)
2855 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002856 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002857 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002858 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002859
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002860 int64_t LineNumber = 0;
2861 if (getLexer().is(AsmToken::Integer)) {
2862 LineNumber = getTok().getIntVal();
2863 if (LineNumber < 1)
2864 return TokError("line number less than one in '.loc' directive");
2865 Lex();
2866 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002867
2868 int64_t ColumnPos = 0;
2869 if (getLexer().is(AsmToken::Integer)) {
2870 ColumnPos = getTok().getIntVal();
2871 if (ColumnPos < 0)
2872 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002873 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002874 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002875
Kevin Enderbyc0957932010-09-30 16:52:03 +00002876 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002877 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002878 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002879 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2880 for (;;) {
2881 if (getLexer().is(AsmToken::EndOfStatement))
2882 break;
2883
2884 StringRef Name;
2885 SMLoc Loc = getTok().getLoc();
2886 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002887 return TokError("unexpected token in '.loc' directive");
2888
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002889 if (Name == "basic_block")
2890 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2891 else if (Name == "prologue_end")
2892 Flags |= DWARF2_FLAG_PROLOGUE_END;
2893 else if (Name == "epilogue_begin")
2894 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2895 else if (Name == "is_stmt") {
2896 SMLoc Loc = getTok().getLoc();
2897 const MCExpr *Value;
2898 if (getParser().ParseExpression(Value))
2899 return true;
2900 // The expression must be the constant 0 or 1.
2901 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2902 int Value = MCE->getValue();
2903 if (Value == 0)
2904 Flags &= ~DWARF2_FLAG_IS_STMT;
2905 else if (Value == 1)
2906 Flags |= DWARF2_FLAG_IS_STMT;
2907 else
2908 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002909 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002910 else {
2911 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2912 }
2913 }
2914 else if (Name == "isa") {
2915 SMLoc Loc = getTok().getLoc();
2916 const MCExpr *Value;
2917 if (getParser().ParseExpression(Value))
2918 return true;
2919 // The expression must be a constant greater or equal to 0.
2920 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2921 int Value = MCE->getValue();
2922 if (Value < 0)
2923 return Error(Loc, "isa number less than zero");
2924 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002925 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002926 else {
2927 return Error(Loc, "isa number not a constant value");
2928 }
2929 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002930 else if (Name == "discriminator") {
2931 if (getParser().ParseAbsoluteExpression(Discriminator))
2932 return true;
2933 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002934 else {
2935 return Error(Loc, "unknown sub-directive in '.loc' directive");
2936 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002937
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002938 if (getLexer().is(AsmToken::EndOfStatement))
2939 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002940 }
2941 }
2942
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002943 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002944 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002945
2946 return false;
2947}
2948
Daniel Dunbar138abae2010-10-16 04:56:42 +00002949/// ParseDirectiveStabs
2950/// ::= .stabs string, number, number, number
2951bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2952 SMLoc DirectiveLoc) {
2953 return TokError("unsupported directive '" + Directive + "'");
2954}
2955
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002956/// ParseDirectiveCFISections
2957/// ::= .cfi_sections section [, section]
2958bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2959 SMLoc DirectiveLoc) {
2960 StringRef Name;
2961 bool EH = false;
2962 bool Debug = false;
2963
2964 if (getParser().ParseIdentifier(Name))
2965 return TokError("Expected an identifier");
2966
2967 if (Name == ".eh_frame")
2968 EH = true;
2969 else if (Name == ".debug_frame")
2970 Debug = true;
2971
2972 if (getLexer().is(AsmToken::Comma)) {
2973 Lex();
2974
2975 if (getParser().ParseIdentifier(Name))
2976 return TokError("Expected an identifier");
2977
2978 if (Name == ".eh_frame")
2979 EH = true;
2980 else if (Name == ".debug_frame")
2981 Debug = true;
2982 }
2983
2984 getStreamer().EmitCFISections(EH, Debug);
2985
2986 return false;
2987}
2988
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002989/// ParseDirectiveCFIStartProc
2990/// ::= .cfi_startproc
2991bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2992 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002993 getStreamer().EmitCFIStartProc();
2994 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002995}
2996
2997/// ParseDirectiveCFIEndProc
2998/// ::= .cfi_endproc
2999bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003000 getStreamer().EmitCFIEndProc();
3001 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003002}
3003
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003004/// ParseRegisterOrRegisterNumber - parse register name or number.
3005bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3006 SMLoc DirectiveLoc) {
3007 unsigned RegNo;
3008
Jim Grosbach6f888a82011-06-02 17:14:04 +00003009 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003010 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3011 DirectiveLoc))
3012 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00003013 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003014 } else
3015 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00003016
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003017 return false;
3018}
3019
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003020/// ParseDirectiveCFIDefCfa
3021/// ::= .cfi_def_cfa register, offset
3022bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3023 SMLoc DirectiveLoc) {
3024 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003025 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003026 return true;
3027
3028 if (getLexer().isNot(AsmToken::Comma))
3029 return TokError("unexpected token in directive");
3030 Lex();
3031
3032 int64_t Offset = 0;
3033 if (getParser().ParseAbsoluteExpression(Offset))
3034 return true;
3035
Rafael Espindola066c2f42011-04-12 23:59:07 +00003036 getStreamer().EmitCFIDefCfa(Register, Offset);
3037 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003038}
3039
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003040/// ParseDirectiveCFIDefCfaOffset
3041/// ::= .cfi_def_cfa_offset offset
3042bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3043 SMLoc DirectiveLoc) {
3044 int64_t Offset = 0;
3045 if (getParser().ParseAbsoluteExpression(Offset))
3046 return true;
3047
Rafael Espindola066c2f42011-04-12 23:59:07 +00003048 getStreamer().EmitCFIDefCfaOffset(Offset);
3049 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003050}
3051
3052/// ParseDirectiveCFIAdjustCfaOffset
3053/// ::= .cfi_adjust_cfa_offset adjustment
3054bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3055 SMLoc DirectiveLoc) {
3056 int64_t Adjustment = 0;
3057 if (getParser().ParseAbsoluteExpression(Adjustment))
3058 return true;
3059
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003060 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3061 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003062}
3063
3064/// ParseDirectiveCFIDefCfaRegister
3065/// ::= .cfi_def_cfa_register register
3066bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3067 SMLoc DirectiveLoc) {
3068 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003069 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003070 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003071
Rafael Espindola066c2f42011-04-12 23:59:07 +00003072 getStreamer().EmitCFIDefCfaRegister(Register);
3073 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003074}
3075
3076/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003077/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003078bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3079 int64_t Register = 0;
3080 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003081
3082 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003083 return true;
3084
3085 if (getLexer().isNot(AsmToken::Comma))
3086 return TokError("unexpected token in directive");
3087 Lex();
3088
3089 if (getParser().ParseAbsoluteExpression(Offset))
3090 return true;
3091
Rafael Espindola066c2f42011-04-12 23:59:07 +00003092 getStreamer().EmitCFIOffset(Register, Offset);
3093 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003094}
3095
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003096/// ParseDirectiveCFIRelOffset
3097/// ::= .cfi_rel_offset register, offset
3098bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3099 SMLoc DirectiveLoc) {
3100 int64_t Register = 0;
3101
3102 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3103 return true;
3104
3105 if (getLexer().isNot(AsmToken::Comma))
3106 return TokError("unexpected token in directive");
3107 Lex();
3108
3109 int64_t Offset = 0;
3110 if (getParser().ParseAbsoluteExpression(Offset))
3111 return true;
3112
Rafael Espindola25f492e2011-04-12 16:12:03 +00003113 getStreamer().EmitCFIRelOffset(Register, Offset);
3114 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003115}
3116
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003117static bool isValidEncoding(int64_t Encoding) {
3118 if (Encoding & ~0xff)
3119 return false;
3120
3121 if (Encoding == dwarf::DW_EH_PE_omit)
3122 return true;
3123
3124 const unsigned Format = Encoding & 0xf;
3125 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3126 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3127 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3128 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3129 return false;
3130
Rafael Espindolacaf11582010-12-29 04:31:26 +00003131 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003132 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003133 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003134 return false;
3135
3136 return true;
3137}
3138
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003139/// ParseDirectiveCFIPersonalityOrLsda
3140/// ::= .cfi_personality encoding, [symbol_name]
3141/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003142bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003143 SMLoc DirectiveLoc) {
3144 int64_t Encoding = 0;
3145 if (getParser().ParseAbsoluteExpression(Encoding))
3146 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003147 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003148 return false;
3149
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003150 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003151 return TokError("unsupported encoding.");
3152
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003153 if (getLexer().isNot(AsmToken::Comma))
3154 return TokError("unexpected token in directive");
3155 Lex();
3156
3157 StringRef Name;
3158 if (getParser().ParseIdentifier(Name))
3159 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003160
3161 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3162
3163 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003164 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003165 else {
3166 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003167 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003168 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003169 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003170}
3171
Rafael Espindolafe024d02010-12-28 18:36:23 +00003172/// ParseDirectiveCFIRememberState
3173/// ::= .cfi_remember_state
3174bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3175 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003176 getStreamer().EmitCFIRememberState();
3177 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003178}
3179
3180/// ParseDirectiveCFIRestoreState
3181/// ::= .cfi_remember_state
3182bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3183 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003184 getStreamer().EmitCFIRestoreState();
3185 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003186}
3187
Rafael Espindolac5754392011-04-12 15:31:05 +00003188/// ParseDirectiveCFISameValue
3189/// ::= .cfi_same_value register
3190bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3191 SMLoc DirectiveLoc) {
3192 int64_t Register = 0;
3193
3194 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3195 return true;
3196
3197 getStreamer().EmitCFISameValue(Register);
3198
3199 return false;
3200}
3201
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003202/// ParseDirectiveCFIRestore
3203/// ::= .cfi_restore register
3204bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003205 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003206 int64_t Register = 0;
3207 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3208 return true;
3209
3210 getStreamer().EmitCFIRestore(Register);
3211
3212 return false;
3213}
3214
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003215/// ParseDirectiveCFIEscape
3216/// ::= .cfi_escape expression[,...]
3217bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003218 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003219 std::string Values;
3220 int64_t CurrValue;
3221 if (getParser().ParseAbsoluteExpression(CurrValue))
3222 return true;
3223
3224 Values.push_back((uint8_t)CurrValue);
3225
3226 while (getLexer().is(AsmToken::Comma)) {
3227 Lex();
3228
3229 if (getParser().ParseAbsoluteExpression(CurrValue))
3230 return true;
3231
3232 Values.push_back((uint8_t)CurrValue);
3233 }
3234
3235 getStreamer().EmitCFIEscape(Values);
3236 return false;
3237}
3238
Rafael Espindola16d7d432012-01-23 21:51:52 +00003239/// ParseDirectiveCFISignalFrame
3240/// ::= .cfi_signal_frame
3241bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3242 SMLoc DirectiveLoc) {
3243 if (getLexer().isNot(AsmToken::EndOfStatement))
3244 return Error(getLexer().getLoc(),
3245 "unexpected token in '" + Directive + "' directive");
3246
3247 getStreamer().EmitCFISignalFrame();
3248
3249 return false;
3250}
3251
Rafael Espindolac8fec7e2012-11-23 16:59:41 +00003252/// ParseDirectiveCFIUndefined
3253/// ::= .cfi_undefined register
3254bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3255 SMLoc DirectiveLoc) {
3256 int64_t Register = 0;
3257
3258 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3259 return true;
3260
3261 getStreamer().EmitCFIUndefined(Register);
3262
3263 return false;
3264}
3265
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003266/// ParseDirectiveMacrosOnOff
3267/// ::= .macros_on
3268/// ::= .macros_off
3269bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3270 SMLoc DirectiveLoc) {
3271 if (getLexer().isNot(AsmToken::EndOfStatement))
3272 return Error(getLexer().getLoc(),
3273 "unexpected token in '" + Directive + "' directive");
3274
3275 getParser().MacrosEnabled = Directive == ".macros_on";
3276
3277 return false;
3278}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003279
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003280/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003281/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003282bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3283 SMLoc DirectiveLoc) {
3284 StringRef Name;
3285 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003286 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003287
Rafael Espindola8a403d32012-08-08 14:51:03 +00003288 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003289 // Argument delimiter is initially unknown. It will be set by
3290 // ParseMacroArgument()
3291 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003292 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003293 for (;;) {
3294 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003295 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003296 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003297
3298 if (getLexer().is(AsmToken::Equal)) {
3299 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003300 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003301 return true;
3302 }
3303
Rafael Espindola65366442011-06-05 02:43:45 +00003304 Parameters.push_back(Parameter);
3305
Preston Gurd7b6f2032012-09-19 20:36:12 +00003306 if (getLexer().is(AsmToken::Comma))
3307 Lex();
3308 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003309 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003310 }
3311 }
3312
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003313 // Eat the end of statement.
3314 Lex();
3315
3316 AsmToken EndToken, StartToken = getTok();
3317
3318 // Lex the macro definition.
3319 for (;;) {
3320 // Check whether we have reached the end of the file.
3321 if (getLexer().is(AsmToken::Eof))
3322 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3323
3324 // Otherwise, check whether we have reach the .endmacro.
3325 if (getLexer().is(AsmToken::Identifier) &&
3326 (getTok().getIdentifier() == ".endm" ||
3327 getTok().getIdentifier() == ".endmacro")) {
3328 EndToken = getTok();
3329 Lex();
3330 if (getLexer().isNot(AsmToken::EndOfStatement))
3331 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3332 "' directive");
3333 break;
3334 }
3335
3336 // Otherwise, scan til the end of the statement.
3337 getParser().EatToEndOfStatement();
3338 }
3339
3340 if (getParser().MacroMap.lookup(Name)) {
3341 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3342 }
3343
3344 const char *BodyStart = StartToken.getLoc().getPointer();
3345 const char *BodyEnd = EndToken.getLoc().getPointer();
3346 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003347 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003348 return false;
3349}
3350
3351/// ParseDirectiveEndMacro
3352/// ::= .endm
3353/// ::= .endmacro
3354bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003355 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003356 if (getLexer().isNot(AsmToken::EndOfStatement))
3357 return TokError("unexpected token in '" + Directive + "' directive");
3358
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003359 // If we are inside a macro instantiation, terminate the current
3360 // instantiation.
3361 if (!getParser().ActiveMacros.empty()) {
3362 getParser().HandleMacroExit();
3363 return false;
3364 }
3365
3366 // Otherwise, this .endmacro is a stray entry in the file; well formed
3367 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003368 return TokError("unexpected '" + Directive + "' in file, "
3369 "no current macro definition");
3370}
3371
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003372/// ParseDirectivePurgeMacro
3373/// ::= .purgem
3374bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3375 SMLoc DirectiveLoc) {
3376 StringRef Name;
3377 if (getParser().ParseIdentifier(Name))
3378 return TokError("expected identifier in '.purgem' directive");
3379
3380 if (getLexer().isNot(AsmToken::EndOfStatement))
3381 return TokError("unexpected token in '.purgem' directive");
3382
3383 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3384 if (I == getParser().MacroMap.end())
3385 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3386
3387 // Undefine the macro.
3388 delete I->getValue();
3389 getParser().MacroMap.erase(I);
3390 return false;
3391}
3392
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003393bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003394 getParser().CheckForValidSection();
3395
3396 const MCExpr *Value;
3397
3398 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003399 return true;
3400
3401 if (getLexer().isNot(AsmToken::EndOfStatement))
3402 return TokError("unexpected token in directive");
3403
3404 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003405 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003406 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003407 getStreamer().EmitULEB128Value(Value);
3408
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003409 return false;
3410}
3411
Rafael Espindola761cb062012-06-03 23:57:14 +00003412Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003413 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003414
Rafael Espindola761cb062012-06-03 23:57:14 +00003415 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003416 for (;;) {
3417 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003418 if (getLexer().is(AsmToken::Eof)) {
3419 Error(DirectiveLoc, "no matching '.endr' in definition");
3420 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003421 }
3422
Rafael Espindola761cb062012-06-03 23:57:14 +00003423 if (Lexer.is(AsmToken::Identifier) &&
3424 (getTok().getIdentifier() == ".rept")) {
3425 ++NestLevel;
3426 }
3427
3428 // Otherwise, check whether we have reached the .endr.
3429 if (Lexer.is(AsmToken::Identifier) &&
3430 getTok().getIdentifier() == ".endr") {
3431 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003432 EndToken = getTok();
3433 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003434 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3435 TokError("unexpected token in '.endr' directive");
3436 return 0;
3437 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003438 break;
3439 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003440 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003441 }
3442
Rafael Espindola761cb062012-06-03 23:57:14 +00003443 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003444 EatToEndOfStatement();
3445 }
3446
3447 const char *BodyStart = StartToken.getLoc().getPointer();
3448 const char *BodyEnd = EndToken.getLoc().getPointer();
3449 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3450
Rafael Espindola761cb062012-06-03 23:57:14 +00003451 // We Are Anonymous.
3452 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003453 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003454 return new Macro(Name, Body, Parameters);
3455}
3456
3457void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3458 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003459 OS << ".endr\n";
3460
3461 MemoryBuffer *Instantiation =
3462 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3463
Rafael Espindola761cb062012-06-03 23:57:14 +00003464 // Create the macro instantiation object and add to the current macro
3465 // instantiation stack.
3466 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3467 getTok().getLoc(),
3468 Instantiation);
3469 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003470
Rafael Espindola761cb062012-06-03 23:57:14 +00003471 // Jump to the macro instantiation and prime the lexer.
3472 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3473 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3474 Lex();
3475}
3476
3477bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3478 int64_t Count;
3479 if (ParseAbsoluteExpression(Count))
3480 return TokError("unexpected token in '.rept' directive");
3481
3482 if (Count < 0)
3483 return TokError("Count is negative");
3484
3485 if (Lexer.isNot(AsmToken::EndOfStatement))
3486 return TokError("unexpected token in '.rept' directive");
3487
3488 // Eat the end of statement.
3489 Lex();
3490
3491 // Lex the rept definition.
3492 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3493 if (!M)
3494 return true;
3495
3496 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3497 // to hold the macro body with substitutions.
3498 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003499 MacroParameters Parameters;
3500 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003501 raw_svector_ostream OS(Buf);
3502 while (Count--) {
3503 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3504 return true;
3505 }
3506 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003507
3508 return false;
3509}
3510
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003511/// ParseDirectiveIrp
3512/// ::= .irp symbol,values
3513bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003514 MacroParameters Parameters;
3515 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003516
Preston Gurd6c9176a2012-09-19 20:29:04 +00003517 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003518 return TokError("expected identifier in '.irp' directive");
3519
3520 Parameters.push_back(Parameter);
3521
3522 if (Lexer.isNot(AsmToken::Comma))
3523 return TokError("expected comma in '.irp' directive");
3524
3525 Lex();
3526
Rafael Espindola8a403d32012-08-08 14:51:03 +00003527 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003528 if (ParseMacroArguments(0, A))
3529 return true;
3530
3531 // Eat the end of statement.
3532 Lex();
3533
3534 // Lex the irp definition.
3535 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3536 if (!M)
3537 return true;
3538
3539 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3540 // to hold the macro body with substitutions.
3541 SmallString<256> Buf;
3542 raw_svector_ostream OS(Buf);
3543
Rafael Espindola7996d042012-08-21 16:06:48 +00003544 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3545 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003546 Args.push_back(*i);
3547
3548 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3549 return true;
3550 }
3551
3552 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3553
3554 return false;
3555}
3556
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003557/// ParseDirectiveIrpc
3558/// ::= .irpc symbol,values
3559bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003560 MacroParameters Parameters;
3561 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003562
Preston Gurd6c9176a2012-09-19 20:29:04 +00003563 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003564 return TokError("expected identifier in '.irpc' directive");
3565
3566 Parameters.push_back(Parameter);
3567
3568 if (Lexer.isNot(AsmToken::Comma))
3569 return TokError("expected comma in '.irpc' directive");
3570
3571 Lex();
3572
Rafael Espindola8a403d32012-08-08 14:51:03 +00003573 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003574 if (ParseMacroArguments(0, A))
3575 return true;
3576
3577 if (A.size() != 1 || A.front().size() != 1)
3578 return TokError("unexpected token in '.irpc' directive");
3579
3580 // Eat the end of statement.
3581 Lex();
3582
3583 // Lex the irpc definition.
3584 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3585 if (!M)
3586 return true;
3587
3588 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3589 // to hold the macro body with substitutions.
3590 SmallString<256> Buf;
3591 raw_svector_ostream OS(Buf);
3592
3593 StringRef Values = A.front().front().getString();
3594 std::size_t I, End = Values.size();
3595 for (I = 0; I < End; ++I) {
3596 MacroArgument Arg;
3597 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3598
Rafael Espindola8a403d32012-08-08 14:51:03 +00003599 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003600 Args.push_back(Arg);
3601
3602 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3603 return true;
3604 }
3605
3606 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3607
3608 return false;
3609}
3610
Rafael Espindola761cb062012-06-03 23:57:14 +00003611bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3612 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003613 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003614
3615 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003616 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003617 assert(getLexer().is(AsmToken::EndOfStatement));
3618
Rafael Espindola761cb062012-06-03 23:57:14 +00003619 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003620 return false;
3621}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003622
Eli Friedman2128aae2012-10-22 23:58:19 +00003623bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3624 const MCExpr *Value;
3625 SMLoc ExprLoc = getLexer().getLoc();
3626 if (ParseExpression(Value))
3627 return true;
3628 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3629 if (!MCE)
3630 return Error(ExprLoc, "unexpected expression in _emit");
3631 uint64_t IntValue = MCE->getValue();
3632 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3633 return Error(ExprLoc, "literal value out of range for directive");
3634
3635 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3636 return false;
3637}
3638
Chad Rosierb1f8c132012-10-18 15:49:34 +00003639bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3640 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003641 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003642 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003643 SmallVectorImpl<std::string> &Clobbers,
3644 const MCInstrInfo *MII,
3645 const MCInstPrinter *IP,
3646 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003647 SmallVector<void *, 4> InputDecls;
3648 SmallVector<void *, 4> OutputDecls;
3649 SmallVector<bool, 4> InputDeclsOffsetOf;
3650 SmallVector<bool, 4> OutputDeclsOffsetOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003651 SmallVector<std::string, 4> InputConstraints;
3652 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003653 std::set<std::string> ClobberRegs;
3654
Chad Rosier4e472d22012-10-20 01:02:45 +00003655 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003656
3657 // Prime the lexer.
3658 Lex();
3659
3660 // While we have input, parse each statement.
3661 unsigned InputIdx = 0;
3662 unsigned OutputIdx = 0;
3663 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003664 ParseStatementInfo Info(&AsmStrRewrites);
3665 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003666 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003667
Eli Friedman2128aae2012-10-22 23:58:19 +00003668 if (Info.Opcode != ~0U) {
3669 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003670
3671 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003672 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3673 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003674
3675 // Immediate.
3676 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003677 if (Operand->needAsmRewrite())
3678 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3679 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003680 continue;
3681 }
3682
3683 // Register operand.
Chad Rosierc0a14b82012-10-24 17:22:29 +00003684 if (Operand->isReg() && !Operand->isOffsetOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003685 unsigned NumDefs = Desc.getNumDefs();
3686 // Clobber.
3687 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3688 std::string Reg;
3689 raw_string_ostream OS(Reg);
3690 IP->printRegName(OS, Operand->getReg());
3691 ClobberRegs.insert(StringRef(OS.str()));
3692 }
3693 continue;
3694 }
3695
3696 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003697 unsigned Size;
3698 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3699 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003700 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003701 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc0a14b82012-10-24 17:22:29 +00003702 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003703 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003704 Operand->getStartLoc(),
3705 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003706 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003707 if (isOutput) {
3708 std::string Constraint = "=";
3709 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003710 OutputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003711 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003712 Constraint += Operand->getConstraint().str();
3713 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003714 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003715 Operand->getStartLoc(),
3716 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003717 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003718 InputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003719 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003720 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003721 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003722 Operand->getStartLoc(),
3723 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003724 }
3725 }
3726 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003727 }
3728 }
3729
3730 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003731 NumOutputs = OutputDecls.size();
3732 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003733
3734 // Set the unique clobbers.
3735 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3736 E = ClobberRegs.end(); I != E; ++I)
3737 Clobbers.push_back(*I);
3738
3739 // Merge the various outputs and inputs. Output are expected first.
3740 if (NumOutputs || NumInputs) {
3741 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003742 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003743 Constraints.resize(NumExprs);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003744 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3745 // constraint for offsetof. This needs to be cleaned up!
Chad Rosierb1f8c132012-10-18 15:49:34 +00003746 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003747 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3748 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003749 }
3750 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003751 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3752 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003753 }
3754 }
3755
3756 // Build the IR assembly string.
3757 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003758 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003759 raw_string_ostream OS(AsmStringIR);
3760 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003761 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003762 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3763 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003764
Chad Rosier4e472d22012-10-20 01:02:45 +00003765 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003766
3767 // Emit everything up to the immediate/expression. If the previous rewrite
3768 // was a size directive, then this has already been done.
3769 if (PrevKind != AOK_SizeDirective)
3770 OS << StringRef(Start, Loc - Start);
3771 PrevKind = Kind;
3772
Chad Rosier5a719fc2012-10-23 17:43:43 +00003773 // Skip the original expression.
3774 if (Kind == AOK_Skip) {
3775 Start = Loc + (*I).Len;
3776 continue;
3777 }
3778
Chad Rosierb1f8c132012-10-18 15:49:34 +00003779 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00003780 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003781 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003782 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00003783 OS << Twine("$$");
3784 OS << (*I).Val;
3785 break;
3786 case AOK_ImmPrefix:
3787 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00003788 break;
3789 case AOK_Input:
3790 OS << '$';
3791 OS << InputIdx++;
3792 break;
3793 case AOK_Output:
3794 OS << '$';
3795 OS << OutputIdx++;
3796 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00003797 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00003798 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00003799 default: break;
3800 case 8: OS << "byte ptr "; break;
3801 case 16: OS << "word ptr "; break;
3802 case 32: OS << "dword ptr "; break;
3803 case 64: OS << "qword ptr "; break;
3804 case 80: OS << "xword ptr "; break;
3805 case 128: OS << "xmmword ptr "; break;
3806 case 256: OS << "ymmword ptr "; break;
3807 }
Eli Friedman2128aae2012-10-22 23:58:19 +00003808 break;
3809 case AOK_Emit:
3810 OS << ".byte";
3811 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00003812 case AOK_DotOperator:
3813 OS << (*I).Val;
3814 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003815 }
Chad Rosier96d58e62012-10-19 20:57:14 +00003816
Chad Rosierb1f8c132012-10-18 15:49:34 +00003817 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00003818 if (Kind != AOK_SizeDirective)
3819 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003820 }
3821
3822 // Emit the remainder of the asm string.
3823 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3824 if (Start != AsmEnd)
3825 OS << StringRef(Start, AsmEnd - Start);
3826
3827 AsmString = OS.str();
3828 return false;
3829}
3830
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003831/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003832MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003833 MCContext &C, MCStreamer &Out,
3834 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003835 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003836}