blob: 2c06604be2b72d2a7ea82be78f536a09f1b9387a [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
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000081 /// The buffer where parsing should resume upon instantiation completion.
82 int ExitBuffer;
83
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000084 /// The location where parsing should resume upon instantiation completion.
85 SMLoc ExitLoc;
86
87public:
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000088 MacroInstantiation(const Macro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000089 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000090};
91
Chad Rosier6a020a72012-10-25 20:41:34 +000092//struct AsmRewrite;
Eli Friedman2128aae2012-10-22 23:58:19 +000093struct ParseStatementInfo {
94 /// ParsedOperands - The parsed operands from the last parsed statement.
95 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
96
97 /// Opcode - The opcode from the last parsed instruction.
98 unsigned Opcode;
99
100 SmallVectorImpl<AsmRewrite> *AsmRewrites;
101
102 ParseStatementInfo() : Opcode(~0U), AsmRewrites(0) {}
103 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
104 : Opcode(~0), AsmRewrites(rewrites) {}
105
106 ~ParseStatementInfo() {
107 // Free any parsed operands.
108 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
109 delete ParsedOperands[i];
110 ParsedOperands.clear();
111 }
112};
113
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000114/// \brief The concrete assembly parser instance.
115class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000116 friend class GenericAsmParser;
117
Craig Topper85aadc02012-09-15 16:23:52 +0000118 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
119 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000120private:
121 AsmLexer Lexer;
122 MCContext &Ctx;
123 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000124 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000125 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000126 SourceMgr::DiagHandlerTy SavedDiagHandler;
127 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000128 MCAsmParserExtension *GenericParser;
129 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000130
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000131 /// This is the current buffer index we're lexing from as managed by the
132 /// SourceMgr object.
133 int CurBuffer;
134
135 AsmCond TheCondState;
136 std::vector<AsmCond> TheCondStack;
137
138 /// DirectiveMap - This is a table handlers for directives. Each handler is
139 /// invoked after the directive identifier is read and is responsible for
140 /// parsing and validating the rest of the directive. The handler is passed
141 /// in the directive name and the location of the directive keyword.
142 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000143
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000144 /// MacroMap - Map of currently defined macros.
145 StringMap<Macro*> MacroMap;
146
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000147 /// ActiveMacros - Stack of active macro instantiations.
148 std::vector<MacroInstantiation*> ActiveMacros;
149
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000150 /// Boolean tracking whether macro substitution is enabled.
151 unsigned MacrosEnabled : 1;
152
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000153 /// Flag tracking whether any errors have been encountered.
154 unsigned HadError : 1;
155
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000156 /// The values from the last parsed cpp hash file line comment if any.
157 StringRef CppHashFilename;
158 int64_t CppHashLineNumber;
159 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000160 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000161
Devang Patel0db58bf2012-01-31 18:14:05 +0000162 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
163 unsigned AssemblerDialect;
164
Preston Gurd7b6f2032012-09-19 20:36:12 +0000165 /// IsDarwin - is Darwin compatibility enabled?
166 bool IsDarwin;
167
Chad Rosier8f138d12012-10-15 17:19:13 +0000168 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000169 bool ParsingInlineAsm;
170
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000171public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000172 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000173 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000174 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000175
176 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
177
Craig Topper345d16d2012-08-29 05:48:09 +0000178 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
179 StringRef Directive,
180 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000181 DirectiveMap[Directive] = std::make_pair(Object, Handler);
182 }
183
184public:
185 /// @name MCAsmParser Interface
186 /// {
187
188 virtual SourceMgr &getSourceManager() { return SrcMgr; }
189 virtual MCAsmLexer &getLexer() { return Lexer; }
190 virtual MCContext &getContext() { return Ctx; }
191 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000192 virtual unsigned getAssemblerDialect() {
193 if (AssemblerDialect == ~0U)
194 return MAI.getAssemblerDialect();
195 else
196 return AssemblerDialect;
197 }
198 virtual void setAssemblerDialect(unsigned i) {
199 AssemblerDialect = i;
200 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000201
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000202 virtual bool Warning(SMLoc L, const Twine &Msg,
203 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
204 virtual bool Error(SMLoc L, const Twine &Msg,
205 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000206
Craig Topper345d16d2012-08-29 05:48:09 +0000207 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000208
Chad Rosier84125ca2012-10-13 00:26:04 +0000209 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000210 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000211
212 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
213 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000214 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000215 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000216 SmallVectorImpl<std::string> &Clobbers,
217 const MCInstrInfo *MII,
218 const MCInstPrinter *IP,
219 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000220
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000221 bool ParseExpression(const MCExpr *&Res);
222 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
223 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
224 virtual bool ParseAbsoluteExpression(int64_t &Res);
225
226 /// }
227
228private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000229 void CheckForValidSection();
230
Eli Friedman2128aae2012-10-22 23:58:19 +0000231 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000232 void EatToEndOfLine();
233 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000234
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000235 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000236 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000237 const MacroParameters &Parameters,
238 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000239 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000240 void HandleMacroExit();
241
242 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000243 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000244 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
245 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000246 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000247 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000248
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000249 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
250 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000251 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
252 /// This returns true on failure.
253 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000254
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000255 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000256 /// current token is not set; clients should ensure Lex() is called
257 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000258 ///
259 /// \param InBuffer If not -1, should be the known buffer id that contains the
260 /// location.
261 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000262
Craig Topper345d16d2012-08-29 05:48:09 +0000263 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000264
Preston Gurd7b6f2032012-09-19 20:36:12 +0000265 bool ParseMacroArgument(MacroArgument &MA,
266 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000267 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000268
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000269 /// \brief Parse up to the end of statement and a return the contents from the
270 /// current token until the end of the statement; the current token on exit
271 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000272 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000273
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000274 /// \brief Parse until the end of a statement or a comma is encountered,
275 /// return the contents from the current token up to the end or comma.
276 StringRef ParseStringToComma();
277
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000278 bool ParseAssignment(StringRef Name, bool allow_redef,
279 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000280
281 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
282 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
283 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000284 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000285
286 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000287 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000288 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000289
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000290 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000291
292 // ".ascii", ".asciiz", ".string"
293 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000294 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000295 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000296 bool ParseDirectiveFill(); // ".fill"
297 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000298 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000299 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000300 bool ParseDirectiveOrg(); // ".org"
301 // ".align{,32}", ".p2align{,w,l}"
302 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
303
304 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
305 /// accepts a single symbol (which should be a label or an external).
306 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000307
308 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
309
310 bool ParseDirectiveAbort(); // ".abort"
311 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000312 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000313
314 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000315 // ".ifb" or ".ifnb", depending on ExpectBlank.
316 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000317 // ".ifc" or ".ifnc", depending on ExpectEqual.
318 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000319 // ".ifdef" or ".ifndef", depending on expect_defined
320 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000321 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
322 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
323 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
324
325 /// ParseEscapedString - Parse the current token as a string which may include
326 /// escaped characters and return the string contents.
327 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000328
329 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
330 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000331
Rafael Espindola761cb062012-06-03 23:57:14 +0000332 // Macro-like directives
333 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
334 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
335 raw_svector_ostream &OS);
336 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000337 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000338 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000339 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000340
Eli Friedman2128aae2012-10-22 23:58:19 +0000341 // "_emit"
342 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000343};
344
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000345/// \brief Generic implementations of directive handling, etc. which is shared
346/// (or the default, at least) for all assembler parser.
347class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000348 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
349 void AddDirectiveHandler(StringRef Directive) {
350 getParser().AddDirectiveHandler(this, Directive,
351 HandleDirective<GenericAsmParser, Handler>);
352 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000353public:
354 GenericAsmParser() {}
355
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000356 AsmParser &getParser() {
357 return (AsmParser&) this->MCAsmParserExtension::getParser();
358 }
359
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000360 virtual void Initialize(MCAsmParser &Parser) {
361 // Call the base implementation.
362 this->MCAsmParserExtension::Initialize(Parser);
363
364 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000365 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
366 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
367 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000368 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000369
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000370 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000371 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
372 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000373 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
374 ".cfi_startproc");
375 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
376 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000377 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
378 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000379 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
380 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000381 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
382 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000383 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
384 ".cfi_def_cfa_register");
385 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
386 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000387 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
388 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000389 AddDirectiveHandler<
390 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
391 AddDirectiveHandler<
392 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000393 AddDirectiveHandler<
394 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
395 AddDirectiveHandler<
396 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000397 AddDirectiveHandler<
398 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000399 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000400 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
401 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000402 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000403 AddDirectiveHandler<
404 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000405 AddDirectiveHandler<
406 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000407 AddDirectiveHandler<
408 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000409
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000410 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000411 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
412 ".macros_on");
413 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
414 ".macros_off");
415 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
416 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
417 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000418 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000419
420 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
421 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000422 }
423
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000424 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
425
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000426 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
427 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
428 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000429 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000430 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000431 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
432 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000433 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000434 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000435 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000436 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
437 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000438 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000439 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000440 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
441 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000442 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000443 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000444 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000445 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000446 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000447 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000448
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000449 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000450 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
451 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000452 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000453
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000454 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000455};
456
457}
458
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000459namespace llvm {
460
461extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000462extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000463extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000464
465}
466
Chris Lattneraaec2052010-01-19 19:46:13 +0000467enum { DEFAULT_ADDRSPACE = 0 };
468
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000469AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000470 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000471 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000472 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000473 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000474 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000475 // Save the old handler.
476 SavedDiagHandler = SrcMgr.getDiagHandler();
477 SavedDiagContext = SrcMgr.getDiagContext();
478 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000479 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000480 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000481
482 // Initialize the generic parser.
483 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000484
485 // Initialize the platform / file format parser.
486 //
487 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
488 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000489 if (_MAI.hasMicrosoftFastStdCallMangling()) {
490 PlatformParser = createCOFFAsmParser();
491 PlatformParser->Initialize(*this);
492 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000493 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000494 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000495 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000496 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000497 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000498 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000499 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000500}
501
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000502AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000503 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
504
505 // Destroy any macros.
506 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
507 ie = MacroMap.end(); it != ie; ++it)
508 delete it->getValue();
509
Daniel Dunbare4749702010-07-12 18:12:02 +0000510 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000511 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000512}
513
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000514void AsmParser::PrintMacroInstantiations() {
515 // Print the active macro instantiation stack.
516 for (std::vector<MacroInstantiation*>::const_reverse_iterator
517 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000518 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
519 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000520}
521
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000522bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000523 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000524 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000525 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000526 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000527 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000528}
529
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000530bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000531 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000532 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000533 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000534 return true;
535}
536
Sean Callananfd0b0282010-01-21 00:19:58 +0000537bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000538 std::string IncludedFile;
539 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000540 if (NewBuf == -1)
541 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000542
Sean Callananfd0b0282010-01-21 00:19:58 +0000543 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000544
Sean Callananfd0b0282010-01-21 00:19:58 +0000545 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000546
Sean Callananfd0b0282010-01-21 00:19:58 +0000547 return false;
548}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000549
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000550/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000551/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000552/// returns true on failure.
553bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
554 std::string IncludedFile;
555 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
556 if (NewBuf == -1)
557 return true;
558
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000559 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000560 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
561 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000562 return false;
563}
564
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000565void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
566 if (InBuffer != -1) {
567 CurBuffer = InBuffer;
568 } else {
569 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
570 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000571 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
572}
573
Sean Callananfd0b0282010-01-21 00:19:58 +0000574const AsmToken &AsmParser::Lex() {
575 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000576
Sean Callananfd0b0282010-01-21 00:19:58 +0000577 if (tok->is(AsmToken::Eof)) {
578 // If this is the end of an included file, pop the parent file off the
579 // include stack.
580 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
581 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000582 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000583 tok = &Lexer.Lex();
584 }
585 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000586
Sean Callananfd0b0282010-01-21 00:19:58 +0000587 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000588 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000589
Sean Callananfd0b0282010-01-21 00:19:58 +0000590 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000591}
592
Chris Lattner79180e22010-04-05 23:15:42 +0000593bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000594 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000595 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000596 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000597
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000598 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000599 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000600
601 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000602 AsmCond StartingCondState = TheCondState;
603
Kevin Enderby613b7572011-11-01 22:27:22 +0000604 // If we are generating dwarf for assembly source files save the initial text
605 // section and generate a .file directive.
606 if (getContext().getGenDwarfForAssembly()) {
607 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000608 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
609 getStreamer().EmitLabel(SectionStartSym);
610 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000611 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
612 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
613 }
614
Chris Lattnerb717fb02009-07-02 21:53:43 +0000615 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000616 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000617 ParseStatementInfo Info;
618 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000619
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000620 // We had an error, validate that one was emitted and recover by skipping to
621 // the next line.
622 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000623 EatToEndOfStatement();
624 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000625
626 if (TheCondState.TheCond != StartingCondState.TheCond ||
627 TheCondState.Ignore != StartingCondState.Ignore)
628 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000629
630 // Check to see there are no empty DwarfFile slots.
631 const std::vector<MCDwarfFile *> &MCDwarfFiles =
632 getContext().getMCDwarfFiles();
633 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000634 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000635 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000636 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000637
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000638 // Check to see that all assembler local symbols were actually defined.
639 // Targets that don't do subsections via symbols may not want this, though,
640 // so conservatively exclude them. Only do this if we're finalizing, though,
641 // as otherwise we won't necessarilly have seen everything yet.
642 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
643 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
644 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
645 e = Symbols.end();
646 i != e; ++i) {
647 MCSymbol *Sym = i->getValue();
648 // Variable symbols may not be marked as defined, so check those
649 // explicitly. If we know it's a variable, we have a definition for
650 // the purposes of this check.
651 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
652 // FIXME: We would really like to refer back to where the symbol was
653 // first referenced for a source location. We need to add something
654 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000655 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
656 "assembler local symbol '" + Sym->getName() +
657 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000658 }
659 }
660
661
Chris Lattner79180e22010-04-05 23:15:42 +0000662 // Finalize the output stream if there are no errors and if the client wants
663 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000664 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000665 Out.Finish();
666
Chris Lattnerb717fb02009-07-02 21:53:43 +0000667 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000668}
669
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000670void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000671 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000672 TokError("expected section directive before assembly directive");
673 Out.SwitchSection(Ctx.getMachOSection(
674 "__TEXT", "__text",
675 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
676 0, SectionKind::getText()));
677 }
678}
679
Chris Lattner2cf5f142009-06-22 01:29:09 +0000680/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
681void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000682 while (Lexer.isNot(AsmToken::EndOfStatement) &&
683 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000684 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000685
Chris Lattner2cf5f142009-06-22 01:29:09 +0000686 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000687 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000688 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000689}
690
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000691StringRef AsmParser::ParseStringToEndOfStatement() {
692 const char *Start = getTok().getLoc().getPointer();
693
694 while (Lexer.isNot(AsmToken::EndOfStatement) &&
695 Lexer.isNot(AsmToken::Eof))
696 Lex();
697
698 const char *End = getTok().getLoc().getPointer();
699 return StringRef(Start, End - Start);
700}
Chris Lattnerc4193832009-06-22 05:51:26 +0000701
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000702StringRef AsmParser::ParseStringToComma() {
703 const char *Start = getTok().getLoc().getPointer();
704
705 while (Lexer.isNot(AsmToken::EndOfStatement) &&
706 Lexer.isNot(AsmToken::Comma) &&
707 Lexer.isNot(AsmToken::Eof))
708 Lex();
709
710 const char *End = getTok().getLoc().getPointer();
711 return StringRef(Start, End - Start);
712}
713
Chris Lattner74ec1a32009-06-22 06:32:03 +0000714/// ParseParenExpr - Parse a paren expression and return it.
715/// NOTE: This assumes the leading '(' has already been consumed.
716///
717/// parenexpr ::= expr)
718///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000719bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000720 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000721 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000722 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000723 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000724 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000725 return false;
726}
Chris Lattnerc4193832009-06-22 05:51:26 +0000727
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000728/// ParseBracketExpr - Parse a bracket expression and return it.
729/// NOTE: This assumes the leading '[' has already been consumed.
730///
731/// bracketexpr ::= expr]
732///
733bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
734 if (ParseExpression(Res)) return true;
735 if (Lexer.isNot(AsmToken::RBrac))
736 return TokError("expected ']' in brackets expression");
737 EndLoc = Lexer.getLoc();
738 Lex();
739 return false;
740}
741
Chris Lattner74ec1a32009-06-22 06:32:03 +0000742/// ParsePrimaryExpr - Parse a primary expression and return it.
743/// primaryexpr ::= (parenexpr
744/// primaryexpr ::= symbol
745/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000746/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000747/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000748bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000749 switch (Lexer.getKind()) {
750 default:
751 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000752 // If we have an error assume that we've already handled it.
753 case AsmToken::Error:
754 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000755 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000756 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000757 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000758 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000759 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000760 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000761 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000762 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000763 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000764 EndLoc = Lexer.getLoc();
765
766 StringRef Identifier;
767 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000768 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000769
Daniel Dunbarfffff912009-10-16 01:34:54 +0000770 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000771 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000772 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000773
774 // Lookup the symbol variant if used.
775 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000776 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000777 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000778 if (Variant == MCSymbolRefExpr::VK_Invalid) {
779 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000780 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000781 }
782 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000783
Daniel Dunbarfffff912009-10-16 01:34:54 +0000784 // If this is an absolute variable reference, substitute it now to preserve
785 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000786 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000787 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000788 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000789
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000790 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000791 return false;
792 }
793
794 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000795 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000796 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000797 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000798 case AsmToken::Integer: {
799 SMLoc Loc = getTok().getLoc();
800 int64_t IntVal = getTok().getIntVal();
801 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000802 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000803 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000804 // Look for 'b' or 'f' following an Integer as a directional label
805 if (Lexer.getKind() == AsmToken::Identifier) {
806 StringRef IDVal = getTok().getString();
807 if (IDVal == "f" || IDVal == "b"){
808 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
809 IDVal == "f" ? 1 : 0);
810 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
811 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000812 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000813 return Error(Loc, "invalid reference to undefined symbol");
814 EndLoc = Lexer.getLoc();
815 Lex(); // Eat identifier.
816 }
817 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000818 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000819 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000820 case AsmToken::Real: {
821 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000822 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000823 Res = MCConstantExpr::Create(IntVal, getContext());
824 Lex(); // Eat token.
825 return false;
826 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000827 case AsmToken::Dot: {
828 // This is a '.' reference, which references the current PC. Emit a
829 // temporary label to the streamer and refer to it.
830 MCSymbol *Sym = Ctx.CreateTempSymbol();
831 Out.EmitLabel(Sym);
832 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
833 EndLoc = Lexer.getLoc();
834 Lex(); // Eat identifier.
835 return false;
836 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000837 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000838 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000839 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000840 case AsmToken::LBrac:
841 if (!PlatformParser->HasBracketExpressions())
842 return TokError("brackets expression not supported on this target");
843 Lex(); // Eat the '['.
844 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000845 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000846 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000847 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000848 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000849 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000850 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000851 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000852 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000853 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000854 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000855 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000856 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000857 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000858 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000859 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000860 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000861 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000862 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000863 }
864}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000865
Chris Lattnerb4307b32010-01-15 19:28:38 +0000866bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000867 SMLoc EndLoc;
868 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000869}
870
Daniel Dunbarcceba832010-09-17 02:47:07 +0000871const MCExpr *
872AsmParser::ApplyModifierToExpr(const MCExpr *E,
873 MCSymbolRefExpr::VariantKind Variant) {
874 // Recurse over the given expression, rebuilding it to apply the given variant
875 // if there is exactly one symbol.
876 switch (E->getKind()) {
877 case MCExpr::Target:
878 case MCExpr::Constant:
879 return 0;
880
881 case MCExpr::SymbolRef: {
882 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
883
884 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
885 TokError("invalid variant on expression '" +
886 getTok().getIdentifier() + "' (already modified)");
887 return E;
888 }
889
890 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
891 }
892
893 case MCExpr::Unary: {
894 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
895 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
896 if (!Sub)
897 return 0;
898 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
899 }
900
901 case MCExpr::Binary: {
902 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
903 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
904 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
905
906 if (!LHS && !RHS)
907 return 0;
908
909 if (!LHS) LHS = BE->getLHS();
910 if (!RHS) RHS = BE->getRHS();
911
912 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
913 }
914 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000915
Craig Topper85814382012-02-07 05:05:23 +0000916 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000917}
918
Chris Lattner74ec1a32009-06-22 06:32:03 +0000919/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000920///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000921/// expr ::= expr &&,|| expr -> lowest.
922/// expr ::= expr |,^,&,! expr
923/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
924/// expr ::= expr <<,>> expr
925/// expr ::= expr +,- expr
926/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000927/// expr ::= primaryexpr
928///
Chris Lattner54482b42010-01-15 19:39:23 +0000929bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000930 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000931 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000932 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
933 return true;
934
Daniel Dunbarcceba832010-09-17 02:47:07 +0000935 // As a special case, we support 'a op b @ modifier' by rewriting the
936 // expression to include the modifier. This is inefficient, but in general we
937 // expect users to use 'a@modifier op b'.
938 if (Lexer.getKind() == AsmToken::At) {
939 Lex();
940
941 if (Lexer.isNot(AsmToken::Identifier))
942 return TokError("unexpected symbol modifier following '@'");
943
944 MCSymbolRefExpr::VariantKind Variant =
945 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
946 if (Variant == MCSymbolRefExpr::VK_Invalid)
947 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
948
949 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
950 if (!ModifiedRes) {
951 return TokError("invalid modifier '" + getTok().getIdentifier() +
952 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000953 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000954
Daniel Dunbarcceba832010-09-17 02:47:07 +0000955 Res = ModifiedRes;
956 Lex();
957 }
958
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000959 // Try to constant fold it up front, if possible.
960 int64_t Value;
961 if (Res->EvaluateAsAbsolute(Value))
962 Res = MCConstantExpr::Create(Value, getContext());
963
964 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000965}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000966
Chris Lattnerb4307b32010-01-15 19:28:38 +0000967bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000968 Res = 0;
969 return ParseParenExpr(Res, EndLoc) ||
970 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000971}
972
Daniel Dunbar475839e2009-06-29 20:37:27 +0000973bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000974 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000975
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000976 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000977 if (ParseExpression(Expr))
978 return true;
979
Daniel Dunbare00b0112009-10-16 01:57:52 +0000980 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000981 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000982
983 return false;
984}
985
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000986static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000987 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000988 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000989 default:
990 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000991
Jim Grosbachfbe16812011-08-20 16:24:13 +0000992 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000993 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000994 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000995 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000996 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000997 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000998 return 1;
999
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001000
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001001 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001002 //
1003 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001004 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001005 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001006 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001007 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001008 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001009 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001010 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001011 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001012 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001013
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001014 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001015 case AsmToken::EqualEqual:
1016 Kind = MCBinaryExpr::EQ;
1017 return 3;
1018 case AsmToken::ExclaimEqual:
1019 case AsmToken::LessGreater:
1020 Kind = MCBinaryExpr::NE;
1021 return 3;
1022 case AsmToken::Less:
1023 Kind = MCBinaryExpr::LT;
1024 return 3;
1025 case AsmToken::LessEqual:
1026 Kind = MCBinaryExpr::LTE;
1027 return 3;
1028 case AsmToken::Greater:
1029 Kind = MCBinaryExpr::GT;
1030 return 3;
1031 case AsmToken::GreaterEqual:
1032 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001033 return 3;
1034
Jim Grosbachfbe16812011-08-20 16:24:13 +00001035 // Intermediate Precedence: <<, >>
1036 case AsmToken::LessLess:
1037 Kind = MCBinaryExpr::Shl;
1038 return 4;
1039 case AsmToken::GreaterGreater:
1040 Kind = MCBinaryExpr::Shr;
1041 return 4;
1042
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001043 // High Intermediate Precedence: +, -
1044 case AsmToken::Plus:
1045 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001046 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001047 case AsmToken::Minus:
1048 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001049 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001050
Jim Grosbachfbe16812011-08-20 16:24:13 +00001051 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001052 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001053 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001054 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001055 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001056 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001057 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001058 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001059 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001060 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001061 }
1062}
1063
1064
1065/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1066/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001067bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1068 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001069 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001070 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001071 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001072
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001073 // If the next token is lower precedence than we are allowed to eat, return
1074 // successfully with what we ate already.
1075 if (TokPrec < Precedence)
1076 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001077
Sean Callanan79ed1a82010-01-19 20:22:31 +00001078 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001079
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001080 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001081 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001082 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001083
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001084 // If BinOp binds less tightly with RHS than the operator after RHS, let
1085 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001086 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001087 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001088 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001089 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001090 }
1091
Daniel Dunbar475839e2009-06-29 20:37:27 +00001092 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001093 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001094 }
1095}
1096
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001097/// ParseStatement:
1098/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001099/// ::= Label* Directive ...Operands... EndOfStatement
1100/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001101bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001102 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001103 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001104 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001105 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001106 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001107
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001108 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001109 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001110 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001111 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001112 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001113 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001114 if (Lexer.is(AsmToken::Hash))
1115 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001116
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001117 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001118 if (Lexer.is(AsmToken::Integer)) {
1119 LocalLabelVal = getTok().getIntVal();
1120 if (LocalLabelVal < 0) {
1121 if (!TheCondState.Ignore)
1122 return TokError("unexpected token at start of statement");
1123 IDVal = "";
1124 }
1125 else {
1126 IDVal = getTok().getString();
1127 Lex(); // Consume the integer token to be used as an identifier token.
1128 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001129 if (!TheCondState.Ignore)
1130 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001131 }
1132 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001133
1134 } else if (Lexer.is(AsmToken::Dot)) {
1135 // Treat '.' as a valid identifier in this context.
1136 Lex();
1137 IDVal = ".";
1138
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001139 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001140 if (!TheCondState.Ignore)
1141 return TokError("unexpected token at start of statement");
1142 IDVal = "";
1143 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001144
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001145
Chris Lattner7834fac2010-04-17 18:14:27 +00001146 // Handle conditional assembly here before checking for skipping. We
1147 // have to do this so that .endif isn't skipped in a ".if 0" block for
1148 // example.
1149 if (IDVal == ".if")
1150 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001151 if (IDVal == ".ifb")
1152 return ParseDirectiveIfb(IDLoc, true);
1153 if (IDVal == ".ifnb")
1154 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001155 if (IDVal == ".ifc")
1156 return ParseDirectiveIfc(IDLoc, true);
1157 if (IDVal == ".ifnc")
1158 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001159 if (IDVal == ".ifdef")
1160 return ParseDirectiveIfdef(IDLoc, true);
1161 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1162 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001163 if (IDVal == ".elseif")
1164 return ParseDirectiveElseIf(IDLoc);
1165 if (IDVal == ".else")
1166 return ParseDirectiveElse(IDLoc);
1167 if (IDVal == ".endif")
1168 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001169
Chris Lattner7834fac2010-04-17 18:14:27 +00001170 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001171 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001172 EatToEndOfStatement();
1173 return false;
1174 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001175
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001176 // FIXME: Recurse on local labels?
1177
1178 // See what kind of statement we have.
1179 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001180 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001181 CheckForValidSection();
1182
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001183 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001184 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001185
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001186 // Diagnose attempt to use '.' as a label.
1187 if (IDVal == ".")
1188 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1189
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001190 // Diagnose attempt to use a variable as a label.
1191 //
1192 // FIXME: Diagnostics. Note the location of the definition as a label.
1193 // FIXME: This doesn't diagnose assignment to a symbol which has been
1194 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001195 MCSymbol *Sym;
1196 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001197 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001198 else
1199 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001200 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001201 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001202
Daniel Dunbar959fd882009-08-26 22:13:22 +00001203 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001204 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001205
Kevin Enderby94c2e852011-12-09 18:09:40 +00001206 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001207 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001208 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001209 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1210 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001211
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001212 // Consume any end of statement token, if present, to avoid spurious
1213 // AddBlankLine calls().
1214 if (Lexer.is(AsmToken::EndOfStatement)) {
1215 Lex();
1216 if (Lexer.is(AsmToken::Eof))
1217 return false;
1218 }
1219
Eli Friedman2128aae2012-10-22 23:58:19 +00001220 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001221 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001222
Daniel Dunbar3f872332009-07-28 16:08:33 +00001223 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001224 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001225 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001226
Nico Weber4c4c7322011-01-28 03:04:41 +00001227 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001228
1229 default: // Normal instruction or directive.
1230 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001231 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001232
1233 // If macros are enabled, check to see if this is a macro instantiation.
1234 if (MacrosEnabled)
1235 if (const Macro *M = MacroMap.lookup(IDVal))
1236 return HandleMacroEntry(IDVal, IDLoc, M);
1237
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001238 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001239 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001240
1241 // Target hook for parsing target specific directives.
1242 if (!getTargetParser().ParseDirective(ID))
1243 return false;
1244
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001245 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001246 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001247 return ParseDirectiveSet(IDVal, true);
1248 if (IDVal == ".equiv")
1249 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001250
Daniel Dunbara0d14262009-06-24 23:30:00 +00001251 // Data directives
1252
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001253 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001254 return ParseDirectiveAscii(IDVal, false);
1255 if (IDVal == ".asciz" || IDVal == ".string")
1256 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001257
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001258 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001259 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001260 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001261 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001262 if (IDVal == ".value")
1263 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001264 if (IDVal == ".2byte")
1265 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001266 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001267 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001268 if (IDVal == ".int")
1269 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001270 if (IDVal == ".4byte")
1271 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001272 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001273 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001274 if (IDVal == ".8byte")
1275 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001276 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001277 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1278 if (IDVal == ".double")
1279 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001280
Eli Friedman5d68ec22010-07-19 04:17:25 +00001281 if (IDVal == ".align") {
1282 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1283 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1284 }
1285 if (IDVal == ".align32") {
1286 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1287 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1288 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001289 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001290 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001291 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001292 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001293 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001294 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001295 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001296 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001297 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001298 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001299 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001300 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1301
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001302 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001303 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001304
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001305 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001306 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001307 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001308 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001309 if (IDVal == ".zero")
1310 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001311
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001312 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001313
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001314 if (IDVal == ".extern") {
1315 EatToEndOfStatement(); // .extern is the default, ignore it.
1316 return false;
1317 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001318 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001319 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001320 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001321 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001322 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001323 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001324 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001325 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001326 if (IDVal == ".symbol_resolver")
1327 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001328 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001329 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001330 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001331 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001332 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001333 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001334 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001335 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001336 if (IDVal == ".weak_def_can_be_hidden")
1337 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001338
Hans Wennborg5cc64912011-06-18 13:51:54 +00001339 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001340 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001341 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001342 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001343
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001344 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001345 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001346 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001347 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001348 if (IDVal == ".incbin")
1349 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001350
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001351 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001352 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001353
Rafael Espindola761cb062012-06-03 23:57:14 +00001354 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001355 if (IDVal == ".rept")
1356 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001357 if (IDVal == ".irp")
1358 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001359 if (IDVal == ".irpc")
1360 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001361 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001362 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001363
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001364 // Look up the handler in the handler table.
1365 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1366 DirectiveMap.lookup(IDVal);
1367 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001368 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001369
Kevin Enderby9c656452009-09-10 20:51:44 +00001370
Jim Grosbach686c0182012-05-01 18:38:27 +00001371 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001372 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001373
Eli Friedman2128aae2012-10-22 23:58:19 +00001374 // _emit
1375 if (ParsingInlineAsm && IDVal == "_emit")
1376 return ParseDirectiveEmit(IDLoc, Info);
1377
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001378 CheckForValidSection();
1379
Chris Lattnera7f13542010-05-19 23:34:33 +00001380 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001381 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001382 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001383 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001384
Chad Rosier6a020a72012-10-25 20:41:34 +00001385 ParseInstructionInfo IInfo(Info.AsmRewrites);
1386 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1387 IDLoc,Info.ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001388
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001389 // Dump the parsed representation, if requested.
1390 if (getShowParsedOperands()) {
1391 SmallString<256> Str;
1392 raw_svector_ostream OS(Str);
1393 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001394 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001395 if (i != 0)
1396 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001397 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001398 }
1399 OS << "]";
1400
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001401 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001402 }
1403
Kevin Enderby613b7572011-11-01 22:27:22 +00001404 // If we are generating dwarf for assembly source files and the current
1405 // section is the initial text section then generate a .loc directive for
1406 // the instruction.
1407 if (!HadError && getContext().getGenDwarfForAssembly() &&
1408 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001409
1410 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1411
1412 // If we previously parsed a cpp hash file line comment then make sure the
1413 // current Dwarf File is for the CppHashFilename if not then emit the
1414 // Dwarf File table for it and adjust the line number for the .loc.
1415 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1416 getContext().getMCDwarfFiles();
1417 if (CppHashFilename.size() != 0) {
1418 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1419 CppHashFilename)
1420 getStreamer().EmitDwarfFileDirective(
1421 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1422
Kevin Enderby32c1a822012-11-05 21:55:41 +00001423 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001424 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1425 }
1426
Kevin Enderby613b7572011-11-01 22:27:22 +00001427 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001428 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001429 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001430 StringRef());
1431 }
1432
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001433 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001434 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001435 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001436 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1437 Info.ParsedOperands,
1438 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001439 ParsingInlineAsm);
1440 }
Chris Lattner98986712010-01-14 22:21:20 +00001441
Chris Lattnercbf8a982010-09-11 16:18:25 +00001442 // Don't skip the rest of the line, the instruction parser is responsible for
1443 // that.
1444 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001445}
Chris Lattner9a023f72009-06-24 04:43:34 +00001446
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001447/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1448/// since they may not be able to be tokenized to get to the end of line token.
1449void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001450 if (!Lexer.is(AsmToken::EndOfStatement))
1451 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001452 // Eat EOL.
1453 Lex();
1454}
1455
1456/// ParseCppHashLineFilenameComment as this:
1457/// ::= # number "filename"
1458/// or just as a full line comment if it doesn't have a number and a string.
1459bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1460 Lex(); // Eat the hash token.
1461
1462 if (getLexer().isNot(AsmToken::Integer)) {
1463 // Consume the line since in cases it is not a well-formed line directive,
1464 // as if were simply a full line comment.
1465 EatToEndOfLine();
1466 return false;
1467 }
1468
1469 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001470 Lex();
1471
1472 if (getLexer().isNot(AsmToken::String)) {
1473 EatToEndOfLine();
1474 return false;
1475 }
1476
1477 StringRef Filename = getTok().getString();
1478 // Get rid of the enclosing quotes.
1479 Filename = Filename.substr(1, Filename.size()-2);
1480
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001481 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1482 CppHashLoc = L;
1483 CppHashFilename = Filename;
1484 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001485 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001486
1487 // Ignore any trailing characters, they're just comment.
1488 EatToEndOfLine();
1489 return false;
1490}
1491
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001492/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001493/// for the Filename and LineNo if any in the diagnostic.
1494void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1495 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1496 raw_ostream &OS = errs();
1497
1498 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1499 const SMLoc &DiagLoc = Diag.getLoc();
1500 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1501 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1502
1503 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1504 // before printing the message.
1505 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001506 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001507 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1508 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1509 }
1510
1511 // If we have not parsed a cpp hash line filename comment or the source
1512 // manager changed or buffer changed (like in a nested include) then just
1513 // print the normal diagnostic using its Filename and LineNo.
1514 if (!Parser->CppHashLineNumber ||
1515 &DiagSrcMgr != &Parser->SrcMgr ||
1516 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001517 if (Parser->SavedDiagHandler)
1518 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1519 else
1520 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001521 return;
1522 }
1523
1524 // Use the CppHashFilename and calculate a line number based on the
1525 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1526 // the diagnostic.
1527 const std::string Filename = Parser->CppHashFilename;
1528
1529 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1530 int CppHashLocLineNo =
1531 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1532 int LineNo = Parser->CppHashLineNumber - 1 +
1533 (DiagLocLineNo - CppHashLocLineNo);
1534
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001535 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1536 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001537 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001538 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001539
Benjamin Kramer04a04262011-10-16 10:48:29 +00001540 if (Parser->SavedDiagHandler)
1541 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1542 else
1543 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001544}
1545
Rafael Espindola799aacf2012-08-21 18:29:30 +00001546// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1547// difference being that that function accepts '@' as part of identifiers and
1548// we can't do that. AsmLexer.cpp should probably be changed to handle
1549// '@' as a special case when needed.
1550static bool isIdentifierChar(char c) {
1551 return isalnum(c) || c == '_' || c == '$' || c == '.';
1552}
1553
Rafael Espindola761cb062012-06-03 23:57:14 +00001554bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001555 const MacroParameters &Parameters,
1556 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001557 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001558 unsigned NParameters = Parameters.size();
1559 if (NParameters != 0 && NParameters != A.size())
1560 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001561
Preston Gurd7b6f2032012-09-19 20:36:12 +00001562 // A macro without parameters is handled differently on Darwin:
1563 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001564 while (!Body.empty()) {
1565 // Scan for the next substitution.
1566 std::size_t End = Body.size(), Pos = 0;
1567 for (; Pos != End; ++Pos) {
1568 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001569 if (!NParameters) {
1570 // This macro has no parameters, look for $0, $1, etc.
1571 if (Body[Pos] != '$' || Pos + 1 == End)
1572 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001573
Rafael Espindola65366442011-06-05 02:43:45 +00001574 char Next = Body[Pos + 1];
1575 if (Next == '$' || Next == 'n' || isdigit(Next))
1576 break;
1577 } else {
1578 // This macro has parameters, look for \foo, \bar, etc.
1579 if (Body[Pos] == '\\' && Pos + 1 != End)
1580 break;
1581 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001582 }
1583
1584 // Add the prefix.
1585 OS << Body.slice(0, Pos);
1586
1587 // Check if we reached the end.
1588 if (Pos == End)
1589 break;
1590
Rafael Espindola65366442011-06-05 02:43:45 +00001591 if (!NParameters) {
1592 switch (Body[Pos+1]) {
1593 // $$ => $
1594 case '$':
1595 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001596 break;
1597
Rafael Espindola65366442011-06-05 02:43:45 +00001598 // $n => number of arguments
1599 case 'n':
1600 OS << A.size();
1601 break;
1602
1603 // $[0-9] => argument
1604 default: {
1605 // Missing arguments are ignored.
1606 unsigned Index = Body[Pos+1] - '0';
1607 if (Index >= A.size())
1608 break;
1609
1610 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001611 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001612 ie = A[Index].end(); it != ie; ++it)
1613 OS << it->getString();
1614 break;
1615 }
1616 }
1617 Pos += 2;
1618 } else {
1619 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001620 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001621 ++I;
1622
1623 const char *Begin = Body.data() + Pos +1;
1624 StringRef Argument(Begin, I - (Pos +1));
1625 unsigned Index = 0;
1626 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001627 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001628 break;
1629
Preston Gurd7b6f2032012-09-19 20:36:12 +00001630 if (Index == NParameters) {
1631 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1632 Pos += 3;
1633 else {
1634 OS << '\\' << Argument;
1635 Pos = I;
1636 }
1637 } else {
1638 for (MacroArgument::const_iterator it = A[Index].begin(),
1639 ie = A[Index].end(); it != ie; ++it)
1640 if (it->getKind() == AsmToken::String)
1641 OS << it->getStringContents();
1642 else
1643 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001644
Preston Gurd7b6f2032012-09-19 20:36:12 +00001645 Pos += 1 + Argument.size();
1646 }
Rafael Espindola65366442011-06-05 02:43:45 +00001647 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001648 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001649 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001650 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001651
Rafael Espindola65366442011-06-05 02:43:45 +00001652 return false;
1653}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001654
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001655MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1656 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001657 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001658 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1659 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001660{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001661}
1662
Preston Gurd7b6f2032012-09-19 20:36:12 +00001663static bool IsOperator(AsmToken::TokenKind kind)
1664{
1665 switch (kind)
1666 {
1667 default:
1668 return false;
1669 case AsmToken::Plus:
1670 case AsmToken::Minus:
1671 case AsmToken::Tilde:
1672 case AsmToken::Slash:
1673 case AsmToken::Star:
1674 case AsmToken::Dot:
1675 case AsmToken::Equal:
1676 case AsmToken::EqualEqual:
1677 case AsmToken::Pipe:
1678 case AsmToken::PipePipe:
1679 case AsmToken::Caret:
1680 case AsmToken::Amp:
1681 case AsmToken::AmpAmp:
1682 case AsmToken::Exclaim:
1683 case AsmToken::ExclaimEqual:
1684 case AsmToken::Percent:
1685 case AsmToken::Less:
1686 case AsmToken::LessEqual:
1687 case AsmToken::LessLess:
1688 case AsmToken::LessGreater:
1689 case AsmToken::Greater:
1690 case AsmToken::GreaterEqual:
1691 case AsmToken::GreaterGreater:
1692 return true;
1693 }
1694}
1695
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001696/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1697/// This is used for both default macro parameter values and the
1698/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001699bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1700 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001701 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001702 unsigned AddTokens = 0;
1703
1704 // gas accepts arguments separated by whitespace, except on Darwin
1705 if (!IsDarwin)
1706 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001707
1708 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001709 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1710 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001711 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001712 }
1713
1714 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1715 // Spaces and commas cannot be mixed to delimit parameters
1716 if (ArgumentDelimiter == AsmToken::Eof)
1717 ArgumentDelimiter = AsmToken::Comma;
1718 else if (ArgumentDelimiter != AsmToken::Comma) {
1719 Lexer.setSkipSpace(true);
1720 return TokError("expected ' ' for macro argument separator");
1721 }
1722 break;
1723 }
1724
1725 if (Lexer.is(AsmToken::Space)) {
1726 Lex(); // Eat spaces
1727
1728 // Spaces can delimit parameters, but could also be part an expression.
1729 // If the token after a space is an operator, add the token and the next
1730 // one into this argument
1731 if (ArgumentDelimiter == AsmToken::Space ||
1732 ArgumentDelimiter == AsmToken::Eof) {
1733 if (IsOperator(Lexer.getKind())) {
1734 // Check to see whether the token is used as an operator,
1735 // or part of an identifier
1736 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1737 if (*NextChar == ' ')
1738 AddTokens = 2;
1739 }
1740
1741 if (!AddTokens && ParenLevel == 0) {
1742 if (ArgumentDelimiter == AsmToken::Eof &&
1743 !IsOperator(Lexer.getKind()))
1744 ArgumentDelimiter = AsmToken::Space;
1745 break;
1746 }
1747 }
1748 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001749
1750 // HandleMacroEntry relies on not advancing the lexer here
1751 // to be able to fill in the remaining default parameter values
1752 if (Lexer.is(AsmToken::EndOfStatement))
1753 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001754
1755 // Adjust the current parentheses level.
1756 if (Lexer.is(AsmToken::LParen))
1757 ++ParenLevel;
1758 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1759 --ParenLevel;
1760
1761 // Append the token to the current argument list.
1762 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001763 if (AddTokens)
1764 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001765 Lex();
1766 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001767
1768 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001769 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001770 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001771 return false;
1772}
1773
1774// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001775bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001776 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001777 // Argument delimiter is initially unknown. It will be set by
1778 // ParseMacroArgument()
1779 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001780
1781 // Parse two kinds of macro invocations:
1782 // - macros defined without any parameters accept an arbitrary number of them
1783 // - macros defined with parameters accept at most that many of them
1784 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1785 ++Parameter) {
1786 MacroArgument MA;
1787
Preston Gurd7b6f2032012-09-19 20:36:12 +00001788 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001789 return true;
1790
Preston Gurd6c9176a2012-09-19 20:29:04 +00001791 if (!MA.empty() || !NParameters)
1792 A.push_back(MA);
1793 else if (NParameters) {
1794 if (!M->Parameters[Parameter].second.empty())
1795 A.push_back(M->Parameters[Parameter].second);
1796 }
Jim Grosbach97146442012-07-30 22:44:17 +00001797
Preston Gurd6c9176a2012-09-19 20:29:04 +00001798 // At the end of the statement, fill in remaining arguments that have
1799 // default values. If there aren't any, then the next argument is
1800 // required but missing
1801 if (Lexer.is(AsmToken::EndOfStatement)) {
1802 if (NParameters && Parameter < NParameters - 1) {
1803 if (M->Parameters[Parameter + 1].second.empty())
1804 return TokError("macro argument '" +
1805 Twine(M->Parameters[Parameter + 1].first) +
1806 "' is missing");
1807 else
1808 continue;
1809 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001810 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001811 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001812
1813 if (Lexer.is(AsmToken::Comma))
1814 Lex();
1815 }
1816 return TokError("Too many arguments");
1817}
1818
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001819bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1820 const Macro *M) {
1821 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1822 // this, although we should protect against infinite loops.
1823 if (ActiveMacros.size() == 20)
1824 return TokError("macros cannot be nested more than 20 levels deep");
1825
Rafael Espindola8a403d32012-08-08 14:51:03 +00001826 MacroArguments A;
1827 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001828 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001829
Jim Grosbach97146442012-07-30 22:44:17 +00001830 // Remove any trailing empty arguments. Do this after-the-fact as we have
1831 // to keep empty arguments in the middle of the list or positionality
1832 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001833 while (!A.empty() && A.back().empty())
1834 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001835
Rafael Espindola65366442011-06-05 02:43:45 +00001836 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1837 // to hold the macro body with substitutions.
1838 SmallString<256> Buf;
1839 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001840 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001841
Rafael Espindola8a403d32012-08-08 14:51:03 +00001842 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001843 return true;
1844
Rafael Espindola761cb062012-06-03 23:57:14 +00001845 // We include the .endmacro in the buffer as our queue to exit the macro
1846 // instantiation.
1847 OS << ".endmacro\n";
1848
Rafael Espindola65366442011-06-05 02:43:45 +00001849 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001850 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001851
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001852 // Create the macro instantiation object and add to the current macro
1853 // instantiation stack.
1854 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001855 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001856 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001857 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001858 ActiveMacros.push_back(MI);
1859
1860 // Jump to the macro instantiation and prime the lexer.
1861 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1862 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1863 Lex();
1864
1865 return false;
1866}
1867
1868void AsmParser::HandleMacroExit() {
1869 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001870 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001871 Lex();
1872
1873 // Pop the instantiation entry.
1874 delete ActiveMacros.back();
1875 ActiveMacros.pop_back();
1876}
1877
Rafael Espindolae71cc862012-01-28 05:57:00 +00001878static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001879 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001880 case MCExpr::Binary: {
1881 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1882 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001883 break;
1884 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001885 case MCExpr::Target:
1886 case MCExpr::Constant:
1887 return false;
1888 case MCExpr::SymbolRef: {
1889 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001890 if (S.isVariable())
1891 return IsUsedIn(Sym, S.getVariableValue());
1892 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001893 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001894 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001895 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001896 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001897
1898 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001899}
1900
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001901bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1902 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001903 // FIXME: Use better location, we should use proper tokens.
1904 SMLoc EqualLoc = Lexer.getLoc();
1905
Daniel Dunbar821e3332009-08-31 08:09:28 +00001906 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001907 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001908 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001909
Rafael Espindolae71cc862012-01-28 05:57:00 +00001910 // Note: we don't count b as used in "a = b". This is to allow
1911 // a = b
1912 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001913
Daniel Dunbar3f872332009-07-28 16:08:33 +00001914 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001915 return TokError("unexpected token in assignment");
1916
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001917 // Error on assignment to '.'.
1918 if (Name == ".") {
1919 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1920 "(use '.space' or '.org').)"));
1921 }
1922
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001923 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001924 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001925
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001926 // Validate that the LHS is allowed to be a variable (either it has not been
1927 // used as a symbol, or it is an absolute symbol).
1928 MCSymbol *Sym = getContext().LookupSymbol(Name);
1929 if (Sym) {
1930 // Diagnose assignment to a label.
1931 //
1932 // FIXME: Diagnostics. Note the location of the definition as a label.
1933 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001934 if (IsUsedIn(Sym, Value))
1935 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1936 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001937 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001938 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1939 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001940 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001941 return Error(EqualLoc, "redefinition of '" + Name + "'");
1942 else if (!Sym->isVariable())
1943 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001944 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001945 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1946 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001947
1948 // Don't count these checks as uses.
1949 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001950 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001951 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001952
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001953 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001954
1955 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001956 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001957 if (NoDeadStrip)
1958 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1959
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001960
1961 return false;
1962}
1963
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001964/// ParseIdentifier:
1965/// ::= identifier
1966/// ::= string
1967bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001968 // The assembler has relaxed rules for accepting identifiers, in particular we
1969 // allow things like '.globl $foo', which would normally be separate
1970 // tokens. At this level, we have already lexed so we cannot (currently)
1971 // handle this as a context dependent token, instead we detect adjacent tokens
1972 // and return the combined identifier.
1973 if (Lexer.is(AsmToken::Dollar)) {
1974 SMLoc DollarLoc = getLexer().getLoc();
1975
1976 // Consume the dollar sign, and check for a following identifier.
1977 Lex();
1978 if (Lexer.isNot(AsmToken::Identifier))
1979 return true;
1980
1981 // We have a '$' followed by an identifier, make sure they are adjacent.
1982 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1983 return true;
1984
1985 // Construct the joined identifier and consume the token.
1986 Res = StringRef(DollarLoc.getPointer(),
1987 getTok().getIdentifier().size() + 1);
1988 Lex();
1989 return false;
1990 }
1991
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001992 if (Lexer.isNot(AsmToken::Identifier) &&
1993 Lexer.isNot(AsmToken::String))
1994 return true;
1995
Sean Callanan18b83232010-01-19 21:44:56 +00001996 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001997
Sean Callanan79ed1a82010-01-19 20:22:31 +00001998 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001999
2000 return false;
2001}
2002
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002003/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002004/// ::= .equ identifier ',' expression
2005/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002006/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002007bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002008 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002009
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002010 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002011 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002012
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002013 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002014 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002015 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002016
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002017 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002018}
2019
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002020bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002021 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002022
2023 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002024 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002025 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2026 if (Str[i] != '\\') {
2027 Data += Str[i];
2028 continue;
2029 }
2030
2031 // Recognize escaped characters. Note that this escape semantics currently
2032 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2033 ++i;
2034 if (i == e)
2035 return TokError("unexpected backslash at end of string");
2036
2037 // Recognize octal sequences.
2038 if ((unsigned) (Str[i] - '0') <= 7) {
2039 // Consume up to three octal characters.
2040 unsigned Value = Str[i] - '0';
2041
2042 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2043 ++i;
2044 Value = Value * 8 + (Str[i] - '0');
2045
2046 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2047 ++i;
2048 Value = Value * 8 + (Str[i] - '0');
2049 }
2050 }
2051
2052 if (Value > 255)
2053 return TokError("invalid octal escape sequence (out of range)");
2054
2055 Data += (unsigned char) Value;
2056 continue;
2057 }
2058
2059 // Otherwise recognize individual escapes.
2060 switch (Str[i]) {
2061 default:
2062 // Just reject invalid escape sequences for now.
2063 return TokError("invalid escape sequence (unrecognized character)");
2064
2065 case 'b': Data += '\b'; break;
2066 case 'f': Data += '\f'; break;
2067 case 'n': Data += '\n'; break;
2068 case 'r': Data += '\r'; break;
2069 case 't': Data += '\t'; break;
2070 case '"': Data += '"'; break;
2071 case '\\': Data += '\\'; break;
2072 }
2073 }
2074
2075 return false;
2076}
2077
Daniel Dunbara0d14262009-06-24 23:30:00 +00002078/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002079/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2080bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002081 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002082 CheckForValidSection();
2083
Daniel Dunbara0d14262009-06-24 23:30:00 +00002084 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002085 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002086 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002087
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002088 std::string Data;
2089 if (ParseEscapedString(Data))
2090 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002091
2092 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002093 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002094 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2095
Sean Callanan79ed1a82010-01-19 20:22:31 +00002096 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002097
2098 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002099 break;
2100
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002101 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002102 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002103 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002104 }
2105 }
2106
Sean Callanan79ed1a82010-01-19 20:22:31 +00002107 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002108 return false;
2109}
2110
2111/// ParseDirectiveValue
2112/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2113bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002114 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002115 CheckForValidSection();
2116
Daniel Dunbara0d14262009-06-24 23:30:00 +00002117 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002118 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002119 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002120 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002121 return true;
2122
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002123 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002124 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2125 assert(Size <= 8 && "Invalid size");
2126 uint64_t IntValue = MCE->getValue();
2127 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2128 return Error(ExprLoc, "literal value out of range for directive");
2129 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2130 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002131 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002132
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002133 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002134 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002135
Daniel Dunbara0d14262009-06-24 23:30:00 +00002136 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002137 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002138 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002139 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002140 }
2141 }
2142
Sean Callanan79ed1a82010-01-19 20:22:31 +00002143 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002144 return false;
2145}
2146
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002147/// ParseDirectiveRealValue
2148/// ::= (.single | .double) [ expression (, expression)* ]
2149bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2150 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2151 CheckForValidSection();
2152
2153 for (;;) {
2154 // We don't truly support arithmetic on floating point expressions, so we
2155 // have to manually parse unary prefixes.
2156 bool IsNeg = false;
2157 if (getLexer().is(AsmToken::Minus)) {
2158 Lex();
2159 IsNeg = true;
2160 } else if (getLexer().is(AsmToken::Plus))
2161 Lex();
2162
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002163 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002164 getLexer().isNot(AsmToken::Real) &&
2165 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002166 return TokError("unexpected token in directive");
2167
2168 // Convert to an APFloat.
2169 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002170 StringRef IDVal = getTok().getString();
2171 if (getLexer().is(AsmToken::Identifier)) {
2172 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2173 Value = APFloat::getInf(Semantics);
2174 else if (!IDVal.compare_lower("nan"))
2175 Value = APFloat::getNaN(Semantics, false, ~0);
2176 else
2177 return TokError("invalid floating point literal");
2178 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002179 APFloat::opInvalidOp)
2180 return TokError("invalid floating point literal");
2181 if (IsNeg)
2182 Value.changeSign();
2183
2184 // Consume the numeric token.
2185 Lex();
2186
2187 // Emit the value as an integer.
2188 APInt AsInt = Value.bitcastToAPInt();
2189 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2190 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2191
2192 if (getLexer().is(AsmToken::EndOfStatement))
2193 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002194
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002195 if (getLexer().isNot(AsmToken::Comma))
2196 return TokError("unexpected token in directive");
2197 Lex();
2198 }
2199 }
2200
2201 Lex();
2202 return false;
2203}
2204
Daniel Dunbara0d14262009-06-24 23:30:00 +00002205/// ParseDirectiveSpace
2206/// ::= .space expression [ , expression ]
2207bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002208 CheckForValidSection();
2209
Daniel Dunbara0d14262009-06-24 23:30:00 +00002210 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002211 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002212 return true;
2213
2214 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002215 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2216 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002217 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002218 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002219
Daniel Dunbar475839e2009-06-29 20:37:27 +00002220 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002221 return true;
2222
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002223 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002224 return TokError("unexpected token in '.space' directive");
2225 }
2226
Sean Callanan79ed1a82010-01-19 20:22:31 +00002227 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002228
2229 if (NumBytes <= 0)
2230 return TokError("invalid number of bytes in '.space' directive");
2231
2232 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002233 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002234
2235 return false;
2236}
2237
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002238/// ParseDirectiveZero
2239/// ::= .zero expression
2240bool AsmParser::ParseDirectiveZero() {
2241 CheckForValidSection();
2242
2243 int64_t NumBytes;
2244 if (ParseAbsoluteExpression(NumBytes))
2245 return true;
2246
Rafael Espindolae452b172010-10-05 19:42:57 +00002247 int64_t Val = 0;
2248 if (getLexer().is(AsmToken::Comma)) {
2249 Lex();
2250 if (ParseAbsoluteExpression(Val))
2251 return true;
2252 }
2253
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002254 if (getLexer().isNot(AsmToken::EndOfStatement))
2255 return TokError("unexpected token in '.zero' directive");
2256
2257 Lex();
2258
Rafael Espindolae452b172010-10-05 19:42:57 +00002259 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002260
2261 return false;
2262}
2263
Daniel Dunbara0d14262009-06-24 23:30:00 +00002264/// ParseDirectiveFill
2265/// ::= .fill expression , expression , expression
2266bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002267 CheckForValidSection();
2268
Daniel Dunbara0d14262009-06-24 23:30:00 +00002269 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002270 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002271 return true;
2272
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002273 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002274 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002275 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002276
Daniel Dunbara0d14262009-06-24 23:30:00 +00002277 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002278 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002279 return true;
2280
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002281 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002282 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002283 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002284
Daniel Dunbara0d14262009-06-24 23:30:00 +00002285 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002286 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002287 return true;
2288
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002289 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002290 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002291
Sean Callanan79ed1a82010-01-19 20:22:31 +00002292 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002293
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002294 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2295 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002296
2297 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002298 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002299
2300 return false;
2301}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002302
2303/// ParseDirectiveOrg
2304/// ::= .org expression [ , expression ]
2305bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002306 CheckForValidSection();
2307
Daniel Dunbar821e3332009-08-31 08:09:28 +00002308 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002309 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002310 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002311 return true;
2312
2313 // Parse optional fill expression.
2314 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002315 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2316 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002317 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002318 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002319
Daniel Dunbar475839e2009-06-29 20:37:27 +00002320 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002321 return true;
2322
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002323 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002324 return TokError("unexpected token in '.org' directive");
2325 }
2326
Sean Callanan79ed1a82010-01-19 20:22:31 +00002327 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002328
Jim Grosbachebd4c052012-01-27 00:37:08 +00002329 // Only limited forms of relocatable expressions are accepted here, it
2330 // has to be relative to the current section. The streamer will return
2331 // 'true' if the expression wasn't evaluatable.
2332 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2333 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002334
2335 return false;
2336}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002337
2338/// ParseDirectiveAlign
2339/// ::= {.align, ...} expression [ , expression [ , expression ]]
2340bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002341 CheckForValidSection();
2342
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002343 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002344 int64_t Alignment;
2345 if (ParseAbsoluteExpression(Alignment))
2346 return true;
2347
2348 SMLoc MaxBytesLoc;
2349 bool HasFillExpr = false;
2350 int64_t FillExpr = 0;
2351 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002352 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2353 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002354 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002355 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002356
2357 // The fill expression can be omitted while specifying a maximum number of
2358 // alignment bytes, e.g:
2359 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002360 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002361 HasFillExpr = true;
2362 if (ParseAbsoluteExpression(FillExpr))
2363 return true;
2364 }
2365
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002366 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2367 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002368 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002369 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002370
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002371 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002372 if (ParseAbsoluteExpression(MaxBytesToFill))
2373 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002374
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002375 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002376 return TokError("unexpected token in directive");
2377 }
2378 }
2379
Sean Callanan79ed1a82010-01-19 20:22:31 +00002380 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002381
Daniel Dunbar648ac512010-05-17 21:54:30 +00002382 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002383 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002384
2385 // Compute alignment in bytes.
2386 if (IsPow2) {
2387 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002388 if (Alignment >= 32) {
2389 Error(AlignmentLoc, "invalid alignment value");
2390 Alignment = 31;
2391 }
2392
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002393 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002394 }
2395
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002396 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002397 if (MaxBytesLoc.isValid()) {
2398 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002399 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2400 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002401 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002402 }
2403
2404 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002405 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2406 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002407 MaxBytesToFill = 0;
2408 }
2409 }
2410
Daniel Dunbar648ac512010-05-17 21:54:30 +00002411 // Check whether we should use optimal code alignment for this .align
2412 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002413 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002414 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2415 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002416 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002417 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002418 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002419 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2420 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002421 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002422
2423 return false;
2424}
2425
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002426/// ParseDirectiveSymbolAttribute
2427/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002428bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002429 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002430 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002431 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002432 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002433
2434 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002435 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002436
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002437 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002438
Jim Grosbach10ec6502011-09-15 17:56:49 +00002439 // Assembler local symbols don't make any sense here. Complain loudly.
2440 if (Sym->isTemporary())
2441 return Error(Loc, "non-local symbol required in directive");
2442
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002443 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002444
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002445 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002446 break;
2447
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002448 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002449 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002450 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002451 }
2452 }
2453
Sean Callanan79ed1a82010-01-19 20:22:31 +00002454 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002455 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002456}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002457
2458/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002459/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2460bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002461 CheckForValidSection();
2462
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002463 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002464 StringRef Name;
2465 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002466 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002467
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002468 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002469 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002470
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002471 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002472 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002473 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002474
2475 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002476 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002477 if (ParseAbsoluteExpression(Size))
2478 return true;
2479
2480 int64_t Pow2Alignment = 0;
2481 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002482 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002483 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002484 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002485 if (ParseAbsoluteExpression(Pow2Alignment))
2486 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002487
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002488 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2489 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002490 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2491
Chris Lattner258281d2010-01-19 06:22:22 +00002492 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002493 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2494 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002495 if (!isPowerOf2_64(Pow2Alignment))
2496 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2497 Pow2Alignment = Log2_64(Pow2Alignment);
2498 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002499 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002500
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002501 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002502 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002503
Sean Callanan79ed1a82010-01-19 20:22:31 +00002504 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002505
Chris Lattner1fc3d752009-07-09 17:25:12 +00002506 // NOTE: a size of zero for a .comm should create a undefined symbol
2507 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002508 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002509 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2510 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002511
Eric Christopherc260a3e2010-05-14 01:38:54 +00002512 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002513 // may internally end up wanting an alignment in bytes.
2514 // FIXME: Diagnose overflow.
2515 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002516 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2517 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002518
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002519 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002520 return Error(IDLoc, "invalid symbol redefinition");
2521
Chris Lattner1fc3d752009-07-09 17:25:12 +00002522 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002523 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002524 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002525 return false;
2526 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002527
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002528 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002529 return false;
2530}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002531
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002532/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002533/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002534bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002535 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002536 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002537
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002538 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002539 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002540 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002541
Sean Callanan79ed1a82010-01-19 20:22:31 +00002542 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002543
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002544 if (Str.empty())
2545 Error(Loc, ".abort detected. Assembly stopping.");
2546 else
2547 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002548 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002549
2550 return false;
2551}
Kevin Enderby71148242009-07-14 21:35:03 +00002552
Kevin Enderby1f049b22009-07-14 23:21:55 +00002553/// ParseDirectiveInclude
2554/// ::= .include "filename"
2555bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002556 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002557 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002558
Sean Callanan18b83232010-01-19 21:44:56 +00002559 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002560 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002561 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002562
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002563 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002564 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002565
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002566 // Strip the quotes.
2567 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002568
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002569 // Attempt to switch the lexer to the included file before consuming the end
2570 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002571 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002572 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002573 return true;
2574 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002575
2576 return false;
2577}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002578
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002579/// ParseDirectiveIncbin
2580/// ::= .incbin "filename"
2581bool AsmParser::ParseDirectiveIncbin() {
2582 if (getLexer().isNot(AsmToken::String))
2583 return TokError("expected string in '.incbin' directive");
2584
2585 std::string Filename = getTok().getString();
2586 SMLoc IncbinLoc = getLexer().getLoc();
2587 Lex();
2588
2589 if (getLexer().isNot(AsmToken::EndOfStatement))
2590 return TokError("unexpected token in '.incbin' directive");
2591
2592 // Strip the quotes.
2593 Filename = Filename.substr(1, Filename.size()-2);
2594
2595 // Attempt to process the included file.
2596 if (ProcessIncbinFile(Filename)) {
2597 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2598 return true;
2599 }
2600
2601 return false;
2602}
2603
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002604/// ParseDirectiveIf
2605/// ::= .if expression
2606bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002607 TheCondStack.push_back(TheCondState);
2608 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002609 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002610 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002611 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002612 int64_t ExprValue;
2613 if (ParseAbsoluteExpression(ExprValue))
2614 return true;
2615
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002616 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002617 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002618
Sean Callanan79ed1a82010-01-19 20:22:31 +00002619 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002620
2621 TheCondState.CondMet = ExprValue;
2622 TheCondState.Ignore = !TheCondState.CondMet;
2623 }
2624
2625 return false;
2626}
2627
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002628/// ParseDirectiveIfb
2629/// ::= .ifb string
2630bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2631 TheCondStack.push_back(TheCondState);
2632 TheCondState.TheCond = AsmCond::IfCond;
2633
Benjamin Kramer29739e72012-05-12 16:52:21 +00002634 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002635 EatToEndOfStatement();
2636 } else {
2637 StringRef Str = ParseStringToEndOfStatement();
2638
2639 if (getLexer().isNot(AsmToken::EndOfStatement))
2640 return TokError("unexpected token in '.ifb' directive");
2641
2642 Lex();
2643
2644 TheCondState.CondMet = ExpectBlank == Str.empty();
2645 TheCondState.Ignore = !TheCondState.CondMet;
2646 }
2647
2648 return false;
2649}
2650
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002651/// ParseDirectiveIfc
2652/// ::= .ifc string1, string2
2653bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2654 TheCondStack.push_back(TheCondState);
2655 TheCondState.TheCond = AsmCond::IfCond;
2656
Benjamin Kramer29739e72012-05-12 16:52:21 +00002657 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002658 EatToEndOfStatement();
2659 } else {
2660 StringRef Str1 = ParseStringToComma();
2661
2662 if (getLexer().isNot(AsmToken::Comma))
2663 return TokError("unexpected token in '.ifc' directive");
2664
2665 Lex();
2666
2667 StringRef Str2 = ParseStringToEndOfStatement();
2668
2669 if (getLexer().isNot(AsmToken::EndOfStatement))
2670 return TokError("unexpected token in '.ifc' directive");
2671
2672 Lex();
2673
2674 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2675 TheCondState.Ignore = !TheCondState.CondMet;
2676 }
2677
2678 return false;
2679}
2680
2681/// ParseDirectiveIfdef
2682/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002683bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2684 StringRef Name;
2685 TheCondStack.push_back(TheCondState);
2686 TheCondState.TheCond = AsmCond::IfCond;
2687
2688 if (TheCondState.Ignore) {
2689 EatToEndOfStatement();
2690 } else {
2691 if (ParseIdentifier(Name))
2692 return TokError("expected identifier after '.ifdef'");
2693
2694 Lex();
2695
2696 MCSymbol *Sym = getContext().LookupSymbol(Name);
2697
2698 if (expect_defined)
2699 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2700 else
2701 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2702 TheCondState.Ignore = !TheCondState.CondMet;
2703 }
2704
2705 return false;
2706}
2707
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002708/// ParseDirectiveElseIf
2709/// ::= .elseif expression
2710bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2711 if (TheCondState.TheCond != AsmCond::IfCond &&
2712 TheCondState.TheCond != AsmCond::ElseIfCond)
2713 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2714 " an .elseif");
2715 TheCondState.TheCond = AsmCond::ElseIfCond;
2716
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002717 bool LastIgnoreState = false;
2718 if (!TheCondStack.empty())
2719 LastIgnoreState = TheCondStack.back().Ignore;
2720 if (LastIgnoreState || TheCondState.CondMet) {
2721 TheCondState.Ignore = true;
2722 EatToEndOfStatement();
2723 }
2724 else {
2725 int64_t ExprValue;
2726 if (ParseAbsoluteExpression(ExprValue))
2727 return true;
2728
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002729 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002730 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002731
Sean Callanan79ed1a82010-01-19 20:22:31 +00002732 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002733 TheCondState.CondMet = ExprValue;
2734 TheCondState.Ignore = !TheCondState.CondMet;
2735 }
2736
2737 return false;
2738}
2739
2740/// ParseDirectiveElse
2741/// ::= .else
2742bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002743 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002744 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002745
Sean Callanan79ed1a82010-01-19 20:22:31 +00002746 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002747
2748 if (TheCondState.TheCond != AsmCond::IfCond &&
2749 TheCondState.TheCond != AsmCond::ElseIfCond)
2750 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2751 ".elseif");
2752 TheCondState.TheCond = AsmCond::ElseCond;
2753 bool LastIgnoreState = false;
2754 if (!TheCondStack.empty())
2755 LastIgnoreState = TheCondStack.back().Ignore;
2756 if (LastIgnoreState || TheCondState.CondMet)
2757 TheCondState.Ignore = true;
2758 else
2759 TheCondState.Ignore = false;
2760
2761 return false;
2762}
2763
2764/// ParseDirectiveEndIf
2765/// ::= .endif
2766bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002767 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002768 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002769
Sean Callanan79ed1a82010-01-19 20:22:31 +00002770 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002771
2772 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2773 TheCondStack.empty())
2774 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2775 ".else");
2776 if (!TheCondStack.empty()) {
2777 TheCondState = TheCondStack.back();
2778 TheCondStack.pop_back();
2779 }
2780
2781 return false;
2782}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002783
2784/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002785/// ::= .file [number] filename
2786/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002787bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002788 // FIXME: I'm not sure what this is.
2789 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002790 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002791 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002792 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002793 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002794
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002795 if (FileNumber < 1)
2796 return TokError("file number less than one");
2797 }
2798
Daniel Dunbareceec052010-07-12 17:45:27 +00002799 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002800 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002801
Nick Lewycky44d798d2011-10-17 23:05:28 +00002802 // Usually the directory and filename together, otherwise just the directory.
2803 StringRef Path = getTok().getString();
2804 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002805 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002806
Nick Lewycky44d798d2011-10-17 23:05:28 +00002807 StringRef Directory;
2808 StringRef Filename;
2809 if (getLexer().is(AsmToken::String)) {
2810 if (FileNumber == -1)
2811 return TokError("explicit path specified, but no file number");
2812 Filename = getTok().getString();
2813 Filename = Filename.substr(1, Filename.size()-2);
2814 Directory = Path;
2815 Lex();
2816 } else {
2817 Filename = Path;
2818 }
2819
Daniel Dunbareceec052010-07-12 17:45:27 +00002820 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002821 return TokError("unexpected token in '.file' directive");
2822
Chris Lattnerd32e8032010-01-25 19:02:58 +00002823 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002824 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002825 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002826 if (getContext().getGenDwarfForAssembly() == true)
2827 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2828 "used to generate dwarf debug info for assembly code");
2829
Nick Lewycky44d798d2011-10-17 23:05:28 +00002830 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002831 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002832 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002833
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002834 return false;
2835}
2836
2837/// ParseDirectiveLine
2838/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002839bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002840 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2841 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002842 return TokError("unexpected token in '.line' directive");
2843
Sean Callanan18b83232010-01-19 21:44:56 +00002844 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002845 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002846 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002847
2848 // FIXME: Do something with the .line.
2849 }
2850
Daniel Dunbareceec052010-07-12 17:45:27 +00002851 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002852 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002853
2854 return false;
2855}
2856
2857
2858/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002859/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002860/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2861/// The first number is a file number, must have been previously assigned with
2862/// a .file directive, the second number is the line number and optionally the
2863/// third number is a column position (zero if not specified). The remaining
2864/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002865bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002866
Daniel Dunbareceec052010-07-12 17:45:27 +00002867 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002868 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002869 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002870 if (FileNumber < 1)
2871 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002872 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002873 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002874 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002875
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002876 int64_t LineNumber = 0;
2877 if (getLexer().is(AsmToken::Integer)) {
2878 LineNumber = getTok().getIntVal();
2879 if (LineNumber < 1)
2880 return TokError("line number less than one in '.loc' directive");
2881 Lex();
2882 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002883
2884 int64_t ColumnPos = 0;
2885 if (getLexer().is(AsmToken::Integer)) {
2886 ColumnPos = getTok().getIntVal();
2887 if (ColumnPos < 0)
2888 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002889 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002890 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002891
Kevin Enderbyc0957932010-09-30 16:52:03 +00002892 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002893 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002894 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002895 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2896 for (;;) {
2897 if (getLexer().is(AsmToken::EndOfStatement))
2898 break;
2899
2900 StringRef Name;
2901 SMLoc Loc = getTok().getLoc();
2902 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002903 return TokError("unexpected token in '.loc' directive");
2904
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002905 if (Name == "basic_block")
2906 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2907 else if (Name == "prologue_end")
2908 Flags |= DWARF2_FLAG_PROLOGUE_END;
2909 else if (Name == "epilogue_begin")
2910 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2911 else if (Name == "is_stmt") {
2912 SMLoc Loc = getTok().getLoc();
2913 const MCExpr *Value;
2914 if (getParser().ParseExpression(Value))
2915 return true;
2916 // The expression must be the constant 0 or 1.
2917 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2918 int Value = MCE->getValue();
2919 if (Value == 0)
2920 Flags &= ~DWARF2_FLAG_IS_STMT;
2921 else if (Value == 1)
2922 Flags |= DWARF2_FLAG_IS_STMT;
2923 else
2924 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002925 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002926 else {
2927 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2928 }
2929 }
2930 else if (Name == "isa") {
2931 SMLoc Loc = getTok().getLoc();
2932 const MCExpr *Value;
2933 if (getParser().ParseExpression(Value))
2934 return true;
2935 // The expression must be a constant greater or equal to 0.
2936 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2937 int Value = MCE->getValue();
2938 if (Value < 0)
2939 return Error(Loc, "isa number less than zero");
2940 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002941 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002942 else {
2943 return Error(Loc, "isa number not a constant value");
2944 }
2945 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002946 else if (Name == "discriminator") {
2947 if (getParser().ParseAbsoluteExpression(Discriminator))
2948 return true;
2949 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002950 else {
2951 return Error(Loc, "unknown sub-directive in '.loc' directive");
2952 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002953
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002954 if (getLexer().is(AsmToken::EndOfStatement))
2955 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002956 }
2957 }
2958
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002959 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002960 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002961
2962 return false;
2963}
2964
Daniel Dunbar138abae2010-10-16 04:56:42 +00002965/// ParseDirectiveStabs
2966/// ::= .stabs string, number, number, number
2967bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2968 SMLoc DirectiveLoc) {
2969 return TokError("unsupported directive '" + Directive + "'");
2970}
2971
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002972/// ParseDirectiveCFISections
2973/// ::= .cfi_sections section [, section]
2974bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2975 SMLoc DirectiveLoc) {
2976 StringRef Name;
2977 bool EH = false;
2978 bool Debug = false;
2979
2980 if (getParser().ParseIdentifier(Name))
2981 return TokError("Expected an identifier");
2982
2983 if (Name == ".eh_frame")
2984 EH = true;
2985 else if (Name == ".debug_frame")
2986 Debug = true;
2987
2988 if (getLexer().is(AsmToken::Comma)) {
2989 Lex();
2990
2991 if (getParser().ParseIdentifier(Name))
2992 return TokError("Expected an identifier");
2993
2994 if (Name == ".eh_frame")
2995 EH = true;
2996 else if (Name == ".debug_frame")
2997 Debug = true;
2998 }
2999
3000 getStreamer().EmitCFISections(EH, Debug);
3001
3002 return false;
3003}
3004
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003005/// ParseDirectiveCFIStartProc
3006/// ::= .cfi_startproc
3007bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3008 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003009 getStreamer().EmitCFIStartProc();
3010 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003011}
3012
3013/// ParseDirectiveCFIEndProc
3014/// ::= .cfi_endproc
3015bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003016 getStreamer().EmitCFIEndProc();
3017 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003018}
3019
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003020/// ParseRegisterOrRegisterNumber - parse register name or number.
3021bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3022 SMLoc DirectiveLoc) {
3023 unsigned RegNo;
3024
Jim Grosbach6f888a82011-06-02 17:14:04 +00003025 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003026 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3027 DirectiveLoc))
3028 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00003029 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003030 } else
3031 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00003032
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003033 return false;
3034}
3035
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003036/// ParseDirectiveCFIDefCfa
3037/// ::= .cfi_def_cfa register, offset
3038bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3039 SMLoc DirectiveLoc) {
3040 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003041 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003042 return true;
3043
3044 if (getLexer().isNot(AsmToken::Comma))
3045 return TokError("unexpected token in directive");
3046 Lex();
3047
3048 int64_t Offset = 0;
3049 if (getParser().ParseAbsoluteExpression(Offset))
3050 return true;
3051
Rafael Espindola066c2f42011-04-12 23:59:07 +00003052 getStreamer().EmitCFIDefCfa(Register, Offset);
3053 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003054}
3055
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003056/// ParseDirectiveCFIDefCfaOffset
3057/// ::= .cfi_def_cfa_offset offset
3058bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3059 SMLoc DirectiveLoc) {
3060 int64_t Offset = 0;
3061 if (getParser().ParseAbsoluteExpression(Offset))
3062 return true;
3063
Rafael Espindola066c2f42011-04-12 23:59:07 +00003064 getStreamer().EmitCFIDefCfaOffset(Offset);
3065 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003066}
3067
3068/// ParseDirectiveCFIAdjustCfaOffset
3069/// ::= .cfi_adjust_cfa_offset adjustment
3070bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3071 SMLoc DirectiveLoc) {
3072 int64_t Adjustment = 0;
3073 if (getParser().ParseAbsoluteExpression(Adjustment))
3074 return true;
3075
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003076 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3077 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003078}
3079
3080/// ParseDirectiveCFIDefCfaRegister
3081/// ::= .cfi_def_cfa_register register
3082bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3083 SMLoc DirectiveLoc) {
3084 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003085 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003086 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003087
Rafael Espindola066c2f42011-04-12 23:59:07 +00003088 getStreamer().EmitCFIDefCfaRegister(Register);
3089 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003090}
3091
3092/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003093/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003094bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3095 int64_t Register = 0;
3096 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003097
3098 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003099 return true;
3100
3101 if (getLexer().isNot(AsmToken::Comma))
3102 return TokError("unexpected token in directive");
3103 Lex();
3104
3105 if (getParser().ParseAbsoluteExpression(Offset))
3106 return true;
3107
Rafael Espindola066c2f42011-04-12 23:59:07 +00003108 getStreamer().EmitCFIOffset(Register, Offset);
3109 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003110}
3111
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003112/// ParseDirectiveCFIRelOffset
3113/// ::= .cfi_rel_offset register, offset
3114bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3115 SMLoc DirectiveLoc) {
3116 int64_t Register = 0;
3117
3118 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3119 return true;
3120
3121 if (getLexer().isNot(AsmToken::Comma))
3122 return TokError("unexpected token in directive");
3123 Lex();
3124
3125 int64_t Offset = 0;
3126 if (getParser().ParseAbsoluteExpression(Offset))
3127 return true;
3128
Rafael Espindola25f492e2011-04-12 16:12:03 +00003129 getStreamer().EmitCFIRelOffset(Register, Offset);
3130 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003131}
3132
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003133static bool isValidEncoding(int64_t Encoding) {
3134 if (Encoding & ~0xff)
3135 return false;
3136
3137 if (Encoding == dwarf::DW_EH_PE_omit)
3138 return true;
3139
3140 const unsigned Format = Encoding & 0xf;
3141 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3142 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3143 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3144 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3145 return false;
3146
Rafael Espindolacaf11582010-12-29 04:31:26 +00003147 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003148 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003149 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003150 return false;
3151
3152 return true;
3153}
3154
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003155/// ParseDirectiveCFIPersonalityOrLsda
3156/// ::= .cfi_personality encoding, [symbol_name]
3157/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003158bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003159 SMLoc DirectiveLoc) {
3160 int64_t Encoding = 0;
3161 if (getParser().ParseAbsoluteExpression(Encoding))
3162 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003163 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003164 return false;
3165
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003166 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003167 return TokError("unsupported encoding.");
3168
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003169 if (getLexer().isNot(AsmToken::Comma))
3170 return TokError("unexpected token in directive");
3171 Lex();
3172
3173 StringRef Name;
3174 if (getParser().ParseIdentifier(Name))
3175 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003176
3177 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3178
3179 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003180 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003181 else {
3182 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003183 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003184 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003185 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003186}
3187
Rafael Espindolafe024d02010-12-28 18:36:23 +00003188/// ParseDirectiveCFIRememberState
3189/// ::= .cfi_remember_state
3190bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3191 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003192 getStreamer().EmitCFIRememberState();
3193 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003194}
3195
3196/// ParseDirectiveCFIRestoreState
3197/// ::= .cfi_remember_state
3198bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3199 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003200 getStreamer().EmitCFIRestoreState();
3201 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003202}
3203
Rafael Espindolac5754392011-04-12 15:31:05 +00003204/// ParseDirectiveCFISameValue
3205/// ::= .cfi_same_value register
3206bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3207 SMLoc DirectiveLoc) {
3208 int64_t Register = 0;
3209
3210 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3211 return true;
3212
3213 getStreamer().EmitCFISameValue(Register);
3214
3215 return false;
3216}
3217
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003218/// ParseDirectiveCFIRestore
3219/// ::= .cfi_restore register
3220bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003221 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003222 int64_t Register = 0;
3223 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3224 return true;
3225
3226 getStreamer().EmitCFIRestore(Register);
3227
3228 return false;
3229}
3230
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003231/// ParseDirectiveCFIEscape
3232/// ::= .cfi_escape expression[,...]
3233bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003234 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003235 std::string Values;
3236 int64_t CurrValue;
3237 if (getParser().ParseAbsoluteExpression(CurrValue))
3238 return true;
3239
3240 Values.push_back((uint8_t)CurrValue);
3241
3242 while (getLexer().is(AsmToken::Comma)) {
3243 Lex();
3244
3245 if (getParser().ParseAbsoluteExpression(CurrValue))
3246 return true;
3247
3248 Values.push_back((uint8_t)CurrValue);
3249 }
3250
3251 getStreamer().EmitCFIEscape(Values);
3252 return false;
3253}
3254
Rafael Espindola16d7d432012-01-23 21:51:52 +00003255/// ParseDirectiveCFISignalFrame
3256/// ::= .cfi_signal_frame
3257bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3258 SMLoc DirectiveLoc) {
3259 if (getLexer().isNot(AsmToken::EndOfStatement))
3260 return Error(getLexer().getLoc(),
3261 "unexpected token in '" + Directive + "' directive");
3262
3263 getStreamer().EmitCFISignalFrame();
3264
3265 return false;
3266}
3267
Rafael Espindolac8fec7e2012-11-23 16:59:41 +00003268/// ParseDirectiveCFIUndefined
3269/// ::= .cfi_undefined register
3270bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3271 SMLoc DirectiveLoc) {
3272 int64_t Register = 0;
3273
3274 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3275 return true;
3276
3277 getStreamer().EmitCFIUndefined(Register);
3278
3279 return false;
3280}
3281
Rafael Espindolaf4f14f62012-11-25 15:14:49 +00003282/// ParseDirectiveCFIRegister
3283/// ::= .cfi_register register, register
3284bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3285 SMLoc DirectiveLoc) {
3286 int64_t Register1 = 0;
3287
3288 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3289 return true;
3290
3291 if (getLexer().isNot(AsmToken::Comma))
3292 return TokError("unexpected token in directive");
3293 Lex();
3294
3295 int64_t Register2 = 0;
3296
3297 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3298 return true;
3299
3300 getStreamer().EmitCFIRegister(Register1, Register2);
3301
3302 return false;
3303}
3304
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003305/// ParseDirectiveMacrosOnOff
3306/// ::= .macros_on
3307/// ::= .macros_off
3308bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3309 SMLoc DirectiveLoc) {
3310 if (getLexer().isNot(AsmToken::EndOfStatement))
3311 return Error(getLexer().getLoc(),
3312 "unexpected token in '" + Directive + "' directive");
3313
3314 getParser().MacrosEnabled = Directive == ".macros_on";
3315
3316 return false;
3317}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003318
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003319/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003320/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003321bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3322 SMLoc DirectiveLoc) {
3323 StringRef Name;
3324 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003325 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003326
Rafael Espindola8a403d32012-08-08 14:51:03 +00003327 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003328 // Argument delimiter is initially unknown. It will be set by
3329 // ParseMacroArgument()
3330 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003331 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003332 for (;;) {
3333 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003334 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003335 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003336
3337 if (getLexer().is(AsmToken::Equal)) {
3338 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003339 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003340 return true;
3341 }
3342
Rafael Espindola65366442011-06-05 02:43:45 +00003343 Parameters.push_back(Parameter);
3344
Preston Gurd7b6f2032012-09-19 20:36:12 +00003345 if (getLexer().is(AsmToken::Comma))
3346 Lex();
3347 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003348 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003349 }
3350 }
3351
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003352 // Eat the end of statement.
3353 Lex();
3354
3355 AsmToken EndToken, StartToken = getTok();
3356
3357 // Lex the macro definition.
3358 for (;;) {
3359 // Check whether we have reached the end of the file.
3360 if (getLexer().is(AsmToken::Eof))
3361 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3362
3363 // Otherwise, check whether we have reach the .endmacro.
3364 if (getLexer().is(AsmToken::Identifier) &&
3365 (getTok().getIdentifier() == ".endm" ||
3366 getTok().getIdentifier() == ".endmacro")) {
3367 EndToken = getTok();
3368 Lex();
3369 if (getLexer().isNot(AsmToken::EndOfStatement))
3370 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3371 "' directive");
3372 break;
3373 }
3374
3375 // Otherwise, scan til the end of the statement.
3376 getParser().EatToEndOfStatement();
3377 }
3378
3379 if (getParser().MacroMap.lookup(Name)) {
3380 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3381 }
3382
3383 const char *BodyStart = StartToken.getLoc().getPointer();
3384 const char *BodyEnd = EndToken.getLoc().getPointer();
3385 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003386 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003387 return false;
3388}
3389
3390/// ParseDirectiveEndMacro
3391/// ::= .endm
3392/// ::= .endmacro
3393bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003394 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003395 if (getLexer().isNot(AsmToken::EndOfStatement))
3396 return TokError("unexpected token in '" + Directive + "' directive");
3397
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003398 // If we are inside a macro instantiation, terminate the current
3399 // instantiation.
3400 if (!getParser().ActiveMacros.empty()) {
3401 getParser().HandleMacroExit();
3402 return false;
3403 }
3404
3405 // Otherwise, this .endmacro is a stray entry in the file; well formed
3406 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003407 return TokError("unexpected '" + Directive + "' in file, "
3408 "no current macro definition");
3409}
3410
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003411/// ParseDirectivePurgeMacro
3412/// ::= .purgem
3413bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3414 SMLoc DirectiveLoc) {
3415 StringRef Name;
3416 if (getParser().ParseIdentifier(Name))
3417 return TokError("expected identifier in '.purgem' directive");
3418
3419 if (getLexer().isNot(AsmToken::EndOfStatement))
3420 return TokError("unexpected token in '.purgem' directive");
3421
3422 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3423 if (I == getParser().MacroMap.end())
3424 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3425
3426 // Undefine the macro.
3427 delete I->getValue();
3428 getParser().MacroMap.erase(I);
3429 return false;
3430}
3431
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003432bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003433 getParser().CheckForValidSection();
3434
3435 const MCExpr *Value;
3436
3437 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003438 return true;
3439
3440 if (getLexer().isNot(AsmToken::EndOfStatement))
3441 return TokError("unexpected token in directive");
3442
3443 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003444 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003445 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003446 getStreamer().EmitULEB128Value(Value);
3447
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003448 return false;
3449}
3450
Rafael Espindola761cb062012-06-03 23:57:14 +00003451Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003452 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003453
Rafael Espindola761cb062012-06-03 23:57:14 +00003454 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003455 for (;;) {
3456 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003457 if (getLexer().is(AsmToken::Eof)) {
3458 Error(DirectiveLoc, "no matching '.endr' in definition");
3459 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003460 }
3461
Rafael Espindola761cb062012-06-03 23:57:14 +00003462 if (Lexer.is(AsmToken::Identifier) &&
3463 (getTok().getIdentifier() == ".rept")) {
3464 ++NestLevel;
3465 }
3466
3467 // Otherwise, check whether we have reached the .endr.
3468 if (Lexer.is(AsmToken::Identifier) &&
3469 getTok().getIdentifier() == ".endr") {
3470 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003471 EndToken = getTok();
3472 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003473 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3474 TokError("unexpected token in '.endr' directive");
3475 return 0;
3476 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003477 break;
3478 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003479 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003480 }
3481
Rafael Espindola761cb062012-06-03 23:57:14 +00003482 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003483 EatToEndOfStatement();
3484 }
3485
3486 const char *BodyStart = StartToken.getLoc().getPointer();
3487 const char *BodyEnd = EndToken.getLoc().getPointer();
3488 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3489
Rafael Espindola761cb062012-06-03 23:57:14 +00003490 // We Are Anonymous.
3491 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003492 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003493 return new Macro(Name, Body, Parameters);
3494}
3495
3496void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3497 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003498 OS << ".endr\n";
3499
3500 MemoryBuffer *Instantiation =
3501 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3502
Rafael Espindola761cb062012-06-03 23:57:14 +00003503 // Create the macro instantiation object and add to the current macro
3504 // instantiation stack.
3505 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003506 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003507 getTok().getLoc(),
3508 Instantiation);
3509 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003510
Rafael Espindola761cb062012-06-03 23:57:14 +00003511 // Jump to the macro instantiation and prime the lexer.
3512 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3513 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3514 Lex();
3515}
3516
3517bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3518 int64_t Count;
3519 if (ParseAbsoluteExpression(Count))
3520 return TokError("unexpected token in '.rept' directive");
3521
3522 if (Count < 0)
3523 return TokError("Count is negative");
3524
3525 if (Lexer.isNot(AsmToken::EndOfStatement))
3526 return TokError("unexpected token in '.rept' directive");
3527
3528 // Eat the end of statement.
3529 Lex();
3530
3531 // Lex the rept definition.
3532 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3533 if (!M)
3534 return true;
3535
3536 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3537 // to hold the macro body with substitutions.
3538 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003539 MacroParameters Parameters;
3540 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003541 raw_svector_ostream OS(Buf);
3542 while (Count--) {
3543 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3544 return true;
3545 }
3546 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003547
3548 return false;
3549}
3550
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003551/// ParseDirectiveIrp
3552/// ::= .irp symbol,values
3553bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003554 MacroParameters Parameters;
3555 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003556
Preston Gurd6c9176a2012-09-19 20:29:04 +00003557 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003558 return TokError("expected identifier in '.irp' directive");
3559
3560 Parameters.push_back(Parameter);
3561
3562 if (Lexer.isNot(AsmToken::Comma))
3563 return TokError("expected comma in '.irp' directive");
3564
3565 Lex();
3566
Rafael Espindola8a403d32012-08-08 14:51:03 +00003567 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003568 if (ParseMacroArguments(0, A))
3569 return true;
3570
3571 // Eat the end of statement.
3572 Lex();
3573
3574 // Lex the irp definition.
3575 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3576 if (!M)
3577 return true;
3578
3579 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3580 // to hold the macro body with substitutions.
3581 SmallString<256> Buf;
3582 raw_svector_ostream OS(Buf);
3583
Rafael Espindola7996d042012-08-21 16:06:48 +00003584 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3585 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003586 Args.push_back(*i);
3587
3588 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3589 return true;
3590 }
3591
3592 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3593
3594 return false;
3595}
3596
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003597/// ParseDirectiveIrpc
3598/// ::= .irpc symbol,values
3599bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003600 MacroParameters Parameters;
3601 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003602
Preston Gurd6c9176a2012-09-19 20:29:04 +00003603 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003604 return TokError("expected identifier in '.irpc' directive");
3605
3606 Parameters.push_back(Parameter);
3607
3608 if (Lexer.isNot(AsmToken::Comma))
3609 return TokError("expected comma in '.irpc' directive");
3610
3611 Lex();
3612
Rafael Espindola8a403d32012-08-08 14:51:03 +00003613 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003614 if (ParseMacroArguments(0, A))
3615 return true;
3616
3617 if (A.size() != 1 || A.front().size() != 1)
3618 return TokError("unexpected token in '.irpc' directive");
3619
3620 // Eat the end of statement.
3621 Lex();
3622
3623 // Lex the irpc definition.
3624 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3625 if (!M)
3626 return true;
3627
3628 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3629 // to hold the macro body with substitutions.
3630 SmallString<256> Buf;
3631 raw_svector_ostream OS(Buf);
3632
3633 StringRef Values = A.front().front().getString();
3634 std::size_t I, End = Values.size();
3635 for (I = 0; I < End; ++I) {
3636 MacroArgument Arg;
3637 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3638
Rafael Espindola8a403d32012-08-08 14:51:03 +00003639 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003640 Args.push_back(Arg);
3641
3642 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3643 return true;
3644 }
3645
3646 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3647
3648 return false;
3649}
3650
Rafael Espindola761cb062012-06-03 23:57:14 +00003651bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3652 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003653 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003654
3655 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003656 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003657 assert(getLexer().is(AsmToken::EndOfStatement));
3658
Rafael Espindola761cb062012-06-03 23:57:14 +00003659 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003660 return false;
3661}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003662
Eli Friedman2128aae2012-10-22 23:58:19 +00003663bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3664 const MCExpr *Value;
3665 SMLoc ExprLoc = getLexer().getLoc();
3666 if (ParseExpression(Value))
3667 return true;
3668 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3669 if (!MCE)
3670 return Error(ExprLoc, "unexpected expression in _emit");
3671 uint64_t IntValue = MCE->getValue();
3672 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3673 return Error(ExprLoc, "literal value out of range for directive");
3674
3675 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3676 return false;
3677}
3678
Chad Rosierb1f8c132012-10-18 15:49:34 +00003679bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3680 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003681 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003682 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003683 SmallVectorImpl<std::string> &Clobbers,
3684 const MCInstrInfo *MII,
3685 const MCInstPrinter *IP,
3686 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003687 SmallVector<void *, 4> InputDecls;
3688 SmallVector<void *, 4> OutputDecls;
3689 SmallVector<bool, 4> InputDeclsOffsetOf;
3690 SmallVector<bool, 4> OutputDeclsOffsetOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003691 SmallVector<std::string, 4> InputConstraints;
3692 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003693 std::set<std::string> ClobberRegs;
3694
Chad Rosier4e472d22012-10-20 01:02:45 +00003695 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003696
3697 // Prime the lexer.
3698 Lex();
3699
3700 // While we have input, parse each statement.
3701 unsigned InputIdx = 0;
3702 unsigned OutputIdx = 0;
3703 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003704 ParseStatementInfo Info(&AsmStrRewrites);
3705 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003706 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003707
Eli Friedman2128aae2012-10-22 23:58:19 +00003708 if (Info.Opcode != ~0U) {
3709 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003710
3711 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003712 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3713 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003714
3715 // Immediate.
3716 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003717 if (Operand->needAsmRewrite())
3718 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3719 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003720 continue;
3721 }
3722
3723 // Register operand.
Chad Rosierc0a14b82012-10-24 17:22:29 +00003724 if (Operand->isReg() && !Operand->isOffsetOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003725 unsigned NumDefs = Desc.getNumDefs();
3726 // Clobber.
3727 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3728 std::string Reg;
3729 raw_string_ostream OS(Reg);
3730 IP->printRegName(OS, Operand->getReg());
3731 ClobberRegs.insert(StringRef(OS.str()));
3732 }
3733 continue;
3734 }
3735
3736 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003737 unsigned Size;
3738 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3739 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003740 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003741 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc0a14b82012-10-24 17:22:29 +00003742 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003743 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003744 Operand->getStartLoc(),
3745 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003746 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003747 if (isOutput) {
3748 std::string Constraint = "=";
3749 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003750 OutputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003751 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003752 Constraint += Operand->getConstraint().str();
3753 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003754 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003755 Operand->getStartLoc(),
3756 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003757 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003758 InputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003759 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003760 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003761 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003762 Operand->getStartLoc(),
3763 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003764 }
3765 }
3766 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003767 }
3768 }
3769
3770 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003771 NumOutputs = OutputDecls.size();
3772 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003773
3774 // Set the unique clobbers.
3775 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3776 E = ClobberRegs.end(); I != E; ++I)
3777 Clobbers.push_back(*I);
3778
3779 // Merge the various outputs and inputs. Output are expected first.
3780 if (NumOutputs || NumInputs) {
3781 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003782 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003783 Constraints.resize(NumExprs);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003784 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3785 // constraint for offsetof. This needs to be cleaned up!
Chad Rosierb1f8c132012-10-18 15:49:34 +00003786 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003787 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3788 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003789 }
3790 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003791 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3792 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003793 }
3794 }
3795
3796 // Build the IR assembly string.
3797 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003798 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003799 raw_string_ostream OS(AsmStringIR);
3800 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003801 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003802 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3803 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003804
Chad Rosier4e472d22012-10-20 01:02:45 +00003805 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003806
3807 // Emit everything up to the immediate/expression. If the previous rewrite
3808 // was a size directive, then this has already been done.
3809 if (PrevKind != AOK_SizeDirective)
3810 OS << StringRef(Start, Loc - Start);
3811 PrevKind = Kind;
3812
Chad Rosier5a719fc2012-10-23 17:43:43 +00003813 // Skip the original expression.
3814 if (Kind == AOK_Skip) {
3815 Start = Loc + (*I).Len;
3816 continue;
3817 }
3818
Chad Rosierb1f8c132012-10-18 15:49:34 +00003819 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00003820 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003821 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003822 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00003823 OS << Twine("$$");
3824 OS << (*I).Val;
3825 break;
3826 case AOK_ImmPrefix:
3827 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00003828 break;
3829 case AOK_Input:
3830 OS << '$';
3831 OS << InputIdx++;
3832 break;
3833 case AOK_Output:
3834 OS << '$';
3835 OS << OutputIdx++;
3836 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00003837 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00003838 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00003839 default: break;
3840 case 8: OS << "byte ptr "; break;
3841 case 16: OS << "word ptr "; break;
3842 case 32: OS << "dword ptr "; break;
3843 case 64: OS << "qword ptr "; break;
3844 case 80: OS << "xword ptr "; break;
3845 case 128: OS << "xmmword ptr "; break;
3846 case 256: OS << "ymmword ptr "; break;
3847 }
Eli Friedman2128aae2012-10-22 23:58:19 +00003848 break;
3849 case AOK_Emit:
3850 OS << ".byte";
3851 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00003852 case AOK_DotOperator:
3853 OS << (*I).Val;
3854 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003855 }
Chad Rosier96d58e62012-10-19 20:57:14 +00003856
Chad Rosierb1f8c132012-10-18 15:49:34 +00003857 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00003858 if (Kind != AOK_SizeDirective)
3859 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003860 }
3861
3862 // Emit the remainder of the asm string.
3863 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3864 if (Start != AsmEnd)
3865 OS << StringRef(Start, AsmEnd - Start);
3866
3867 AsmString = OS.str();
3868 return false;
3869}
3870
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003871/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003872MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003873 MCContext &C, MCStreamer &Out,
3874 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003875 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003876}