blob: 0a8053121c85ff8fc19d2464a5867aa48450f7e6 [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"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000022#include "llvm/MC/MCParser/AsmCond.h"
23#include "llvm/MC/MCParser/AsmLexer.h"
24#include "llvm/MC/MCParser/MCAsmParser.h"
25#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000026#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000027#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000028#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000029#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000030#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000031#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000032#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000033#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000035#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000036#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000037#include <cctype>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000039using namespace llvm;
40
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000041static cl::opt<bool>
42FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
44
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000045namespace {
46
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000047/// \brief Helper class for tracking macro definitions.
Rafael Espindola28c1f6662012-06-03 22:41:23 +000048typedef std::vector<AsmToken> MacroArgument;
Rafael Espindola8a403d32012-08-08 14:51:03 +000049typedef std::vector<MacroArgument> MacroArguments;
Preston Gurd6c9176a2012-09-19 20:29:04 +000050typedef std::pair<StringRef, MacroArgument> MacroParameter;
Rafael Espindola8a403d32012-08-08 14:51:03 +000051typedef std::vector<MacroParameter> MacroParameters;
Rafael Espindola28c1f6662012-06-03 22:41:23 +000052
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000053struct Macro {
54 StringRef Name;
55 StringRef Body;
Rafael Espindola8a403d32012-08-08 14:51:03 +000056 MacroParameters Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000057
58public:
Rafael Espindola8a403d32012-08-08 14:51:03 +000059 Macro(StringRef N, StringRef B, const MacroParameters &P) :
Rafael Espindola65366442011-06-05 02:43:45 +000060 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000061};
62
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000063/// \brief Helper class for storing information about an active macro
64/// instantiation.
65struct MacroInstantiation {
66 /// The macro being instantiated.
67 const Macro *TheMacro;
68
69 /// The macro instantiation with substitutions.
70 MemoryBuffer *Instantiation;
71
72 /// The location of the instantiation.
73 SMLoc InstantiationLoc;
74
75 /// The location where parsing should resume upon instantiation completion.
76 SMLoc ExitLoc;
77
78public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000079 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000080 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000081};
82
Daniel Dunbaraef87e32010-07-18 18:31:38 +000083/// \brief The concrete assembly parser instance.
84class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +000085 friend class GenericAsmParser;
86
Craig Topper85aadc02012-09-15 16:23:52 +000087 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
88 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000089private:
90 AsmLexer Lexer;
91 MCContext &Ctx;
92 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +000093 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000094 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +000095 SourceMgr::DiagHandlerTy SavedDiagHandler;
96 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000097 MCAsmParserExtension *GenericParser;
98 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +000099
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000100 /// This is the current buffer index we're lexing from as managed by the
101 /// SourceMgr object.
102 int CurBuffer;
103
104 AsmCond TheCondState;
105 std::vector<AsmCond> TheCondStack;
106
107 /// DirectiveMap - This is a table handlers for directives. Each handler is
108 /// invoked after the directive identifier is read and is responsible for
109 /// parsing and validating the rest of the directive. The handler is passed
110 /// in the directive name and the location of the directive keyword.
111 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000112
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000113 /// MacroMap - Map of currently defined macros.
114 StringMap<Macro*> MacroMap;
115
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000116 /// ActiveMacros - Stack of active macro instantiations.
117 std::vector<MacroInstantiation*> ActiveMacros;
118
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000119 /// Boolean tracking whether macro substitution is enabled.
120 unsigned MacrosEnabled : 1;
121
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000122 /// Flag tracking whether any errors have been encountered.
123 unsigned HadError : 1;
124
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000125 /// The values from the last parsed cpp hash file line comment if any.
126 StringRef CppHashFilename;
127 int64_t CppHashLineNumber;
128 SMLoc CppHashLoc;
129
Devang Patel0db58bf2012-01-31 18:14:05 +0000130 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
131 unsigned AssemblerDialect;
132
Preston Gurd7b6f2032012-09-19 20:36:12 +0000133 /// IsDarwin - is Darwin compatibility enabled?
134 bool IsDarwin;
135
Chad Rosier8f138d12012-10-15 17:19:13 +0000136 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000137 bool ParsingInlineAsm;
138
Chad Rosier8f138d12012-10-15 17:19:13 +0000139 /// IsInstruction - Was the last parsed statement an instruction?
140 bool IsInstruction;
141
142 /// ParsedOperands - The parsed operands from the last parsed statement.
143 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
144
145 /// Opcode - The opcode from the last parsed instruction.
146 unsigned Opcode;
147
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000148public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000149 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000150 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000151 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000152
153 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
154
Craig Topper345d16d2012-08-29 05:48:09 +0000155 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
156 StringRef Directive,
157 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000158 DirectiveMap[Directive] = std::make_pair(Object, Handler);
159 }
160
161public:
162 /// @name MCAsmParser Interface
163 /// {
164
165 virtual SourceMgr &getSourceManager() { return SrcMgr; }
166 virtual MCAsmLexer &getLexer() { return Lexer; }
167 virtual MCContext &getContext() { return Ctx; }
168 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000169 virtual unsigned getAssemblerDialect() {
170 if (AssemblerDialect == ~0U)
171 return MAI.getAssemblerDialect();
172 else
173 return AssemblerDialect;
174 }
175 virtual void setAssemblerDialect(unsigned i) {
176 AssemblerDialect = i;
177 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000178
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000179 virtual bool Warning(SMLoc L, const Twine &Msg,
180 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
181 virtual bool Error(SMLoc L, const Twine &Msg,
182 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000183
Craig Topper345d16d2012-08-29 05:48:09 +0000184 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000185
Chad Rosier8f138d12012-10-15 17:19:13 +0000186 bool ParseStatement();
Chad Rosier84125ca2012-10-13 00:26:04 +0000187 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosier8f138d12012-10-15 17:19:13 +0000188 unsigned getNumParsedOperands() { return ParsedOperands.size(); }
189 MCParsedAsmOperand &getParsedOperand(unsigned OpNum) {
190 assert (ParsedOperands.size() > OpNum);
191 return *ParsedOperands[OpNum];
192 }
193 void freeParsedOperands() {
194 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
195 delete ParsedOperands[i];
196 ParsedOperands.clear();
197 }
198 bool isInstruction() { return IsInstruction; }
199 unsigned getOpcode() { return Opcode; }
Chad Rosier84125ca2012-10-13 00:26:04 +0000200
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000201 bool ParseExpression(const MCExpr *&Res);
202 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
203 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
204 virtual bool ParseAbsoluteExpression(int64_t &Res);
205
206 /// }
207
208private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000209 void CheckForValidSection();
210
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000211 void EatToEndOfLine();
212 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000213
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000214 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000215 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000216 const MacroParameters &Parameters,
217 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000218 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000219 void HandleMacroExit();
220
221 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000222 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000223 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
224 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000225 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000226 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000227
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000228 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
229 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000230 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
231 /// This returns true on failure.
232 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000233
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000234 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000235 /// current token is not set; clients should ensure Lex() is called
236 /// subsequently.
237 void JumpToLoc(SMLoc Loc);
238
Craig Topper345d16d2012-08-29 05:48:09 +0000239 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000240
Preston Gurd7b6f2032012-09-19 20:36:12 +0000241 bool ParseMacroArgument(MacroArgument &MA,
242 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000243 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000244
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000245 /// \brief Parse up to the end of statement and a return the contents from the
246 /// current token until the end of the statement; the current token on exit
247 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000248 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000249
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000250 /// \brief Parse until the end of a statement or a comma is encountered,
251 /// return the contents from the current token up to the end or comma.
252 StringRef ParseStringToComma();
253
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000254 bool ParseAssignment(StringRef Name, bool allow_redef,
255 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000256
257 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
258 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
259 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000260 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000261
262 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000263 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000264 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000265
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000266 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000267
268 // ".ascii", ".asciiz", ".string"
269 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000270 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000271 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000272 bool ParseDirectiveFill(); // ".fill"
273 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000274 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000275 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000276 bool ParseDirectiveOrg(); // ".org"
277 // ".align{,32}", ".p2align{,w,l}"
278 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
279
280 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
281 /// accepts a single symbol (which should be a label or an external).
282 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000283
284 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
285
286 bool ParseDirectiveAbort(); // ".abort"
287 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000288 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000289
290 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000291 // ".ifb" or ".ifnb", depending on ExpectBlank.
292 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000293 // ".ifc" or ".ifnc", depending on ExpectEqual.
294 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000295 // ".ifdef" or ".ifndef", depending on expect_defined
296 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000297 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
298 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
299 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
300
301 /// ParseEscapedString - Parse the current token as a string which may include
302 /// escaped characters and return the string contents.
303 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000304
305 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
306 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000307
Rafael Espindola761cb062012-06-03 23:57:14 +0000308 // Macro-like directives
309 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
310 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
311 raw_svector_ostream &OS);
312 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000313 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000314 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000315 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000316};
317
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000318/// \brief Generic implementations of directive handling, etc. which is shared
319/// (or the default, at least) for all assembler parser.
320class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000321 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
322 void AddDirectiveHandler(StringRef Directive) {
323 getParser().AddDirectiveHandler(this, Directive,
324 HandleDirective<GenericAsmParser, Handler>);
325 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000326public:
327 GenericAsmParser() {}
328
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000329 AsmParser &getParser() {
330 return (AsmParser&) this->MCAsmParserExtension::getParser();
331 }
332
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000333 virtual void Initialize(MCAsmParser &Parser) {
334 // Call the base implementation.
335 this->MCAsmParserExtension::Initialize(Parser);
336
337 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000338 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
339 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
340 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000341 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000342
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000343 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000344 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
345 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000346 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
347 ".cfi_startproc");
348 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
349 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000350 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
351 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000352 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
353 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000354 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
355 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000356 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
357 ".cfi_def_cfa_register");
358 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
359 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000360 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
361 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000362 AddDirectiveHandler<
363 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
364 AddDirectiveHandler<
365 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000366 AddDirectiveHandler<
367 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
368 AddDirectiveHandler<
369 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000370 AddDirectiveHandler<
371 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000372 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000373 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
374 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000375 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000376 AddDirectiveHandler<
377 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000378
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000379 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000380 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
381 ".macros_on");
382 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
383 ".macros_off");
384 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
385 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
386 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000387 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000388
389 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000391 }
392
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000393 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
394
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000395 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
396 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
397 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000398 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000399 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000400 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
401 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000402 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000403 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000404 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000405 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
406 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000407 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000408 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000409 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
410 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000411 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000412 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000413 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000414 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000415
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000416 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000417 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
418 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000419 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000420
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000421 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000422};
423
424}
425
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000426namespace llvm {
427
428extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000429extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000430extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000431
432}
433
Chris Lattneraaec2052010-01-19 19:46:13 +0000434enum { DEFAULT_ADDRSPACE = 0 };
435
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000436AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000437 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000438 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000439 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000440 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Chad Rosier8f138d12012-10-15 17:19:13 +0000441 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false),
442 IsInstruction(false), Opcode(0) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000443 // Save the old handler.
444 SavedDiagHandler = SrcMgr.getDiagHandler();
445 SavedDiagContext = SrcMgr.getDiagContext();
446 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000447 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000448 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000449
450 // Initialize the generic parser.
451 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000452
453 // Initialize the platform / file format parser.
454 //
455 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
456 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000457 if (_MAI.hasMicrosoftFastStdCallMangling()) {
458 PlatformParser = createCOFFAsmParser();
459 PlatformParser->Initialize(*this);
460 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000461 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000462 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000463 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000464 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000465 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000466 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000467 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000468}
469
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000470AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000471 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
472
473 // Destroy any macros.
474 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
475 ie = MacroMap.end(); it != ie; ++it)
476 delete it->getValue();
477
Daniel Dunbare4749702010-07-12 18:12:02 +0000478 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000479 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000480}
481
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000482void AsmParser::PrintMacroInstantiations() {
483 // Print the active macro instantiation stack.
484 for (std::vector<MacroInstantiation*>::const_reverse_iterator
485 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000486 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
487 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000488}
489
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000490bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000491 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000492 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000493 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000494 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000495 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000496}
497
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000498bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000499 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000500 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000501 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000502 return true;
503}
504
Sean Callananfd0b0282010-01-21 00:19:58 +0000505bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000506 std::string IncludedFile;
507 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000508 if (NewBuf == -1)
509 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000510
Sean Callananfd0b0282010-01-21 00:19:58 +0000511 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000512
Sean Callananfd0b0282010-01-21 00:19:58 +0000513 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000514
Sean Callananfd0b0282010-01-21 00:19:58 +0000515 return false;
516}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000517
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000518/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000519/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000520/// returns true on failure.
521bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
522 std::string IncludedFile;
523 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
524 if (NewBuf == -1)
525 return true;
526
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000527 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000528 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
529 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000530 return false;
531}
532
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000533void AsmParser::JumpToLoc(SMLoc Loc) {
534 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
535 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
536}
537
Sean Callananfd0b0282010-01-21 00:19:58 +0000538const AsmToken &AsmParser::Lex() {
539 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000540
Sean Callananfd0b0282010-01-21 00:19:58 +0000541 if (tok->is(AsmToken::Eof)) {
542 // If this is the end of an included file, pop the parent file off the
543 // include stack.
544 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
545 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000546 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000547 tok = &Lexer.Lex();
548 }
549 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000550
Sean Callananfd0b0282010-01-21 00:19:58 +0000551 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000552 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000553
Sean Callananfd0b0282010-01-21 00:19:58 +0000554 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000555}
556
Chris Lattner79180e22010-04-05 23:15:42 +0000557bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000558 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000559 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000560 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000561
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000562 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000563 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000564
565 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000566 AsmCond StartingCondState = TheCondState;
567
Kevin Enderby613b7572011-11-01 22:27:22 +0000568 // If we are generating dwarf for assembly source files save the initial text
569 // section and generate a .file directive.
570 if (getContext().getGenDwarfForAssembly()) {
571 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000572 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
573 getStreamer().EmitLabel(SectionStartSym);
574 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000575 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
576 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
577 }
578
Chris Lattnerb717fb02009-07-02 21:53:43 +0000579 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000580 while (Lexer.isNot(AsmToken::Eof)) {
Chris Lattnerb717fb02009-07-02 21:53:43 +0000581 if (!ParseStatement()) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000582
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000583 // We had an error, validate that one was emitted and recover by skipping to
584 // the next line.
585 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000586 EatToEndOfStatement();
587 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000588
589 if (TheCondState.TheCond != StartingCondState.TheCond ||
590 TheCondState.Ignore != StartingCondState.Ignore)
591 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000592
593 // Check to see there are no empty DwarfFile slots.
594 const std::vector<MCDwarfFile *> &MCDwarfFiles =
595 getContext().getMCDwarfFiles();
596 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000597 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000598 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000599 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000600
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000601 // Check to see that all assembler local symbols were actually defined.
602 // Targets that don't do subsections via symbols may not want this, though,
603 // so conservatively exclude them. Only do this if we're finalizing, though,
604 // as otherwise we won't necessarilly have seen everything yet.
605 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
606 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
607 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
608 e = Symbols.end();
609 i != e; ++i) {
610 MCSymbol *Sym = i->getValue();
611 // Variable symbols may not be marked as defined, so check those
612 // explicitly. If we know it's a variable, we have a definition for
613 // the purposes of this check.
614 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
615 // FIXME: We would really like to refer back to where the symbol was
616 // first referenced for a source location. We need to add something
617 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000618 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
619 "assembler local symbol '" + Sym->getName() +
620 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000621 }
622 }
623
624
Chris Lattner79180e22010-04-05 23:15:42 +0000625 // Finalize the output stream if there are no errors and if the client wants
626 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000627 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000628 Out.Finish();
629
Chris Lattnerb717fb02009-07-02 21:53:43 +0000630 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000631}
632
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000633void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000634 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000635 TokError("expected section directive before assembly directive");
636 Out.SwitchSection(Ctx.getMachOSection(
637 "__TEXT", "__text",
638 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
639 0, SectionKind::getText()));
640 }
641}
642
Chris Lattner2cf5f142009-06-22 01:29:09 +0000643/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
644void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000645 while (Lexer.isNot(AsmToken::EndOfStatement) &&
646 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000647 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000648
Chris Lattner2cf5f142009-06-22 01:29:09 +0000649 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000650 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000651 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000652}
653
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000654StringRef AsmParser::ParseStringToEndOfStatement() {
655 const char *Start = getTok().getLoc().getPointer();
656
657 while (Lexer.isNot(AsmToken::EndOfStatement) &&
658 Lexer.isNot(AsmToken::Eof))
659 Lex();
660
661 const char *End = getTok().getLoc().getPointer();
662 return StringRef(Start, End - Start);
663}
Chris Lattnerc4193832009-06-22 05:51:26 +0000664
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000665StringRef AsmParser::ParseStringToComma() {
666 const char *Start = getTok().getLoc().getPointer();
667
668 while (Lexer.isNot(AsmToken::EndOfStatement) &&
669 Lexer.isNot(AsmToken::Comma) &&
670 Lexer.isNot(AsmToken::Eof))
671 Lex();
672
673 const char *End = getTok().getLoc().getPointer();
674 return StringRef(Start, End - Start);
675}
676
Chris Lattner74ec1a32009-06-22 06:32:03 +0000677/// ParseParenExpr - Parse a paren expression and return it.
678/// NOTE: This assumes the leading '(' has already been consumed.
679///
680/// parenexpr ::= expr)
681///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000682bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000683 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000684 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000685 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000686 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000687 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000688 return false;
689}
Chris Lattnerc4193832009-06-22 05:51:26 +0000690
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000691/// ParseBracketExpr - Parse a bracket expression and return it.
692/// NOTE: This assumes the leading '[' has already been consumed.
693///
694/// bracketexpr ::= expr]
695///
696bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
697 if (ParseExpression(Res)) return true;
698 if (Lexer.isNot(AsmToken::RBrac))
699 return TokError("expected ']' in brackets expression");
700 EndLoc = Lexer.getLoc();
701 Lex();
702 return false;
703}
704
Chris Lattner74ec1a32009-06-22 06:32:03 +0000705/// ParsePrimaryExpr - Parse a primary expression and return it.
706/// primaryexpr ::= (parenexpr
707/// primaryexpr ::= symbol
708/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000709/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000710/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000711bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000712 switch (Lexer.getKind()) {
713 default:
714 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000715 // If we have an error assume that we've already handled it.
716 case AsmToken::Error:
717 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000718 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000719 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000720 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000721 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000722 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000723 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000724 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000725 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000726 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000727 EndLoc = Lexer.getLoc();
728
729 StringRef Identifier;
730 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000731 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000732
Daniel Dunbarfffff912009-10-16 01:34:54 +0000733 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000734 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000735 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000736
737 // Lookup the symbol variant if used.
738 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000739 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000740 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000741 if (Variant == MCSymbolRefExpr::VK_Invalid) {
742 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000743 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000744 }
745 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000746
Daniel Dunbarfffff912009-10-16 01:34:54 +0000747 // If this is an absolute variable reference, substitute it now to preserve
748 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000749 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000750 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000751 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000752
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000753 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000754 return false;
755 }
756
757 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000758 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000759 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000760 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000761 case AsmToken::Integer: {
762 SMLoc Loc = getTok().getLoc();
763 int64_t IntVal = getTok().getIntVal();
764 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000765 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000766 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000767 // Look for 'b' or 'f' following an Integer as a directional label
768 if (Lexer.getKind() == AsmToken::Identifier) {
769 StringRef IDVal = getTok().getString();
770 if (IDVal == "f" || IDVal == "b"){
771 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
772 IDVal == "f" ? 1 : 0);
773 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
774 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000775 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000776 return Error(Loc, "invalid reference to undefined symbol");
777 EndLoc = Lexer.getLoc();
778 Lex(); // Eat identifier.
779 }
780 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000781 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000782 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000783 case AsmToken::Real: {
784 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000785 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000786 Res = MCConstantExpr::Create(IntVal, getContext());
787 Lex(); // Eat token.
788 return false;
789 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000790 case AsmToken::Dot: {
791 // This is a '.' reference, which references the current PC. Emit a
792 // temporary label to the streamer and refer to it.
793 MCSymbol *Sym = Ctx.CreateTempSymbol();
794 Out.EmitLabel(Sym);
795 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
796 EndLoc = Lexer.getLoc();
797 Lex(); // Eat identifier.
798 return false;
799 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000800 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000801 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000802 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000803 case AsmToken::LBrac:
804 if (!PlatformParser->HasBracketExpressions())
805 return TokError("brackets expression not supported on this target");
806 Lex(); // Eat the '['.
807 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000808 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000809 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000810 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000811 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000812 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000813 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000814 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000815 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000816 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000817 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000818 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000819 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000820 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000821 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000822 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000823 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000824 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000825 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000826 }
827}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000828
Chris Lattnerb4307b32010-01-15 19:28:38 +0000829bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000830 SMLoc EndLoc;
831 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000832}
833
Daniel Dunbarcceba832010-09-17 02:47:07 +0000834const MCExpr *
835AsmParser::ApplyModifierToExpr(const MCExpr *E,
836 MCSymbolRefExpr::VariantKind Variant) {
837 // Recurse over the given expression, rebuilding it to apply the given variant
838 // if there is exactly one symbol.
839 switch (E->getKind()) {
840 case MCExpr::Target:
841 case MCExpr::Constant:
842 return 0;
843
844 case MCExpr::SymbolRef: {
845 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
846
847 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
848 TokError("invalid variant on expression '" +
849 getTok().getIdentifier() + "' (already modified)");
850 return E;
851 }
852
853 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
854 }
855
856 case MCExpr::Unary: {
857 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
858 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
859 if (!Sub)
860 return 0;
861 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
862 }
863
864 case MCExpr::Binary: {
865 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
866 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
867 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
868
869 if (!LHS && !RHS)
870 return 0;
871
872 if (!LHS) LHS = BE->getLHS();
873 if (!RHS) RHS = BE->getRHS();
874
875 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
876 }
877 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000878
Craig Topper85814382012-02-07 05:05:23 +0000879 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000880}
881
Chris Lattner74ec1a32009-06-22 06:32:03 +0000882/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000883///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000884/// expr ::= expr &&,|| expr -> lowest.
885/// expr ::= expr |,^,&,! expr
886/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
887/// expr ::= expr <<,>> expr
888/// expr ::= expr +,- expr
889/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000890/// expr ::= primaryexpr
891///
Chris Lattner54482b42010-01-15 19:39:23 +0000892bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000893 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000894 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000895 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
896 return true;
897
Daniel Dunbarcceba832010-09-17 02:47:07 +0000898 // As a special case, we support 'a op b @ modifier' by rewriting the
899 // expression to include the modifier. This is inefficient, but in general we
900 // expect users to use 'a@modifier op b'.
901 if (Lexer.getKind() == AsmToken::At) {
902 Lex();
903
904 if (Lexer.isNot(AsmToken::Identifier))
905 return TokError("unexpected symbol modifier following '@'");
906
907 MCSymbolRefExpr::VariantKind Variant =
908 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
909 if (Variant == MCSymbolRefExpr::VK_Invalid)
910 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
911
912 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
913 if (!ModifiedRes) {
914 return TokError("invalid modifier '" + getTok().getIdentifier() +
915 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000916 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000917
Daniel Dunbarcceba832010-09-17 02:47:07 +0000918 Res = ModifiedRes;
919 Lex();
920 }
921
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000922 // Try to constant fold it up front, if possible.
923 int64_t Value;
924 if (Res->EvaluateAsAbsolute(Value))
925 Res = MCConstantExpr::Create(Value, getContext());
926
927 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000928}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000929
Chris Lattnerb4307b32010-01-15 19:28:38 +0000930bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000931 Res = 0;
932 return ParseParenExpr(Res, EndLoc) ||
933 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000934}
935
Daniel Dunbar475839e2009-06-29 20:37:27 +0000936bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000937 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000938
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000939 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000940 if (ParseExpression(Expr))
941 return true;
942
Daniel Dunbare00b0112009-10-16 01:57:52 +0000943 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000944 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000945
946 return false;
947}
948
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000949static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000950 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000951 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000952 default:
953 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000954
Jim Grosbachfbe16812011-08-20 16:24:13 +0000955 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000956 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000957 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000958 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000959 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000960 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000961 return 1;
962
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000963
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000964 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000965 //
966 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000967 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000968 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000969 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000970 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000971 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000972 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000973 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000974 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000975 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000976
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000977 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000978 case AsmToken::EqualEqual:
979 Kind = MCBinaryExpr::EQ;
980 return 3;
981 case AsmToken::ExclaimEqual:
982 case AsmToken::LessGreater:
983 Kind = MCBinaryExpr::NE;
984 return 3;
985 case AsmToken::Less:
986 Kind = MCBinaryExpr::LT;
987 return 3;
988 case AsmToken::LessEqual:
989 Kind = MCBinaryExpr::LTE;
990 return 3;
991 case AsmToken::Greater:
992 Kind = MCBinaryExpr::GT;
993 return 3;
994 case AsmToken::GreaterEqual:
995 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000996 return 3;
997
Jim Grosbachfbe16812011-08-20 16:24:13 +0000998 // Intermediate Precedence: <<, >>
999 case AsmToken::LessLess:
1000 Kind = MCBinaryExpr::Shl;
1001 return 4;
1002 case AsmToken::GreaterGreater:
1003 Kind = MCBinaryExpr::Shr;
1004 return 4;
1005
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001006 // High Intermediate Precedence: +, -
1007 case AsmToken::Plus:
1008 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001009 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001010 case AsmToken::Minus:
1011 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001012 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001013
Jim Grosbachfbe16812011-08-20 16:24:13 +00001014 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001015 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001016 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001017 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001018 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001019 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001020 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001021 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001022 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001023 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001024 }
1025}
1026
1027
1028/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1029/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001030bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1031 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001032 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001033 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001034 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001035
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001036 // If the next token is lower precedence than we are allowed to eat, return
1037 // successfully with what we ate already.
1038 if (TokPrec < Precedence)
1039 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001040
Sean Callanan79ed1a82010-01-19 20:22:31 +00001041 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001042
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001043 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001044 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001045 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001046
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001047 // If BinOp binds less tightly with RHS than the operator after RHS, let
1048 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001049 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001050 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001051 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001052 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001053 }
1054
Daniel Dunbar475839e2009-06-29 20:37:27 +00001055 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001056 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001057 }
1058}
1059
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001060/// ParseStatement:
1061/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001062/// ::= Label* Directive ...Operands... EndOfStatement
1063/// ::= Label* Identifier OperandList* EndOfStatement
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001064bool AsmParser::ParseStatement() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001065 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001066 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001067 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001068 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001069 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001070
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001071 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001072 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001073 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001074 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001075 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001076 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001077 if (Lexer.is(AsmToken::Hash))
1078 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001079
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001080 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001081 if (Lexer.is(AsmToken::Integer)) {
1082 LocalLabelVal = getTok().getIntVal();
1083 if (LocalLabelVal < 0) {
1084 if (!TheCondState.Ignore)
1085 return TokError("unexpected token at start of statement");
1086 IDVal = "";
1087 }
1088 else {
1089 IDVal = getTok().getString();
1090 Lex(); // Consume the integer token to be used as an identifier token.
1091 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001092 if (!TheCondState.Ignore)
1093 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001094 }
1095 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001096
1097 } else if (Lexer.is(AsmToken::Dot)) {
1098 // Treat '.' as a valid identifier in this context.
1099 Lex();
1100 IDVal = ".";
1101
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001102 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001103 if (!TheCondState.Ignore)
1104 return TokError("unexpected token at start of statement");
1105 IDVal = "";
1106 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001107
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001108
Chris Lattner7834fac2010-04-17 18:14:27 +00001109 // Handle conditional assembly here before checking for skipping. We
1110 // have to do this so that .endif isn't skipped in a ".if 0" block for
1111 // example.
1112 if (IDVal == ".if")
1113 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001114 if (IDVal == ".ifb")
1115 return ParseDirectiveIfb(IDLoc, true);
1116 if (IDVal == ".ifnb")
1117 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001118 if (IDVal == ".ifc")
1119 return ParseDirectiveIfc(IDLoc, true);
1120 if (IDVal == ".ifnc")
1121 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001122 if (IDVal == ".ifdef")
1123 return ParseDirectiveIfdef(IDLoc, true);
1124 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1125 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001126 if (IDVal == ".elseif")
1127 return ParseDirectiveElseIf(IDLoc);
1128 if (IDVal == ".else")
1129 return ParseDirectiveElse(IDLoc);
1130 if (IDVal == ".endif")
1131 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001132
Chris Lattner7834fac2010-04-17 18:14:27 +00001133 // If we are in a ".if 0" block, ignore this statement.
1134 if (TheCondState.Ignore) {
1135 EatToEndOfStatement();
1136 return false;
1137 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001138
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001139 // FIXME: Recurse on local labels?
1140
1141 // See what kind of statement we have.
1142 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001143 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001144 CheckForValidSection();
1145
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001146 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001147 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001148
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001149 // Diagnose attempt to use '.' as a label.
1150 if (IDVal == ".")
1151 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1152
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001153 // Diagnose attempt to use a variable as a label.
1154 //
1155 // FIXME: Diagnostics. Note the location of the definition as a label.
1156 // FIXME: This doesn't diagnose assignment to a symbol which has been
1157 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001158 MCSymbol *Sym;
1159 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001160 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001161 else
1162 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001163 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001164 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001165
Daniel Dunbar959fd882009-08-26 22:13:22 +00001166 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001167 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001168
Kevin Enderby94c2e852011-12-09 18:09:40 +00001169 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001170 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001171 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001172 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1173 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001174
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001175 // Consume any end of statement token, if present, to avoid spurious
1176 // AddBlankLine calls().
1177 if (Lexer.is(AsmToken::EndOfStatement)) {
1178 Lex();
1179 if (Lexer.is(AsmToken::Eof))
1180 return false;
1181 }
1182
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001183 return ParseStatement();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001184 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001185
Daniel Dunbar3f872332009-07-28 16:08:33 +00001186 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001187 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001188 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001189
Nico Weber4c4c7322011-01-28 03:04:41 +00001190 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001191
1192 default: // Normal instruction or directive.
1193 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001194 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001195
1196 // If macros are enabled, check to see if this is a macro instantiation.
1197 if (MacrosEnabled)
1198 if (const Macro *M = MacroMap.lookup(IDVal))
1199 return HandleMacroEntry(IDVal, IDLoc, M);
1200
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001201 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001202 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001203
1204 // Target hook for parsing target specific directives.
1205 if (!getTargetParser().ParseDirective(ID))
1206 return false;
1207
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001208 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001209 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001210 return ParseDirectiveSet(IDVal, true);
1211 if (IDVal == ".equiv")
1212 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001213
Daniel Dunbara0d14262009-06-24 23:30:00 +00001214 // Data directives
1215
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001216 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001217 return ParseDirectiveAscii(IDVal, false);
1218 if (IDVal == ".asciz" || IDVal == ".string")
1219 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001220
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001221 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001222 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001223 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001224 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001225 if (IDVal == ".value")
1226 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001227 if (IDVal == ".2byte")
1228 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001229 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001230 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001231 if (IDVal == ".int")
1232 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001233 if (IDVal == ".4byte")
1234 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001235 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001236 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001237 if (IDVal == ".8byte")
1238 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001239 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001240 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1241 if (IDVal == ".double")
1242 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001243
Eli Friedman5d68ec22010-07-19 04:17:25 +00001244 if (IDVal == ".align") {
1245 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1246 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1247 }
1248 if (IDVal == ".align32") {
1249 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1250 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1251 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001252 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001253 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001254 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001255 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001256 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001257 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001258 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001259 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001260 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001261 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001262 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001263 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1264
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001265 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001266 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001267
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001268 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001269 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001270 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001271 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001272 if (IDVal == ".zero")
1273 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001274
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001275 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001276
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001277 if (IDVal == ".extern") {
1278 EatToEndOfStatement(); // .extern is the default, ignore it.
1279 return false;
1280 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001281 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001282 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001283 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001284 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001285 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001286 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001287 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001288 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001289 if (IDVal == ".symbol_resolver")
1290 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001291 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001292 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001293 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001294 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001295 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001296 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001297 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001298 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001299 if (IDVal == ".weak_def_can_be_hidden")
1300 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001301
Hans Wennborg5cc64912011-06-18 13:51:54 +00001302 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001303 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001304 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001305 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001306
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001307 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001308 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001309 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001310 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001311 if (IDVal == ".incbin")
1312 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001313
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001314 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001315 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001316
Rafael Espindola761cb062012-06-03 23:57:14 +00001317 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001318 if (IDVal == ".rept")
1319 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001320 if (IDVal == ".irp")
1321 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001322 if (IDVal == ".irpc")
1323 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001324 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001325 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001326
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001327 // Look up the handler in the handler table.
1328 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1329 DirectiveMap.lookup(IDVal);
1330 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001331 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001332
Kevin Enderby9c656452009-09-10 20:51:44 +00001333
Jim Grosbach686c0182012-05-01 18:38:27 +00001334 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001335 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001336
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001337 CheckForValidSection();
1338
Chris Lattnera7f13542010-05-19 23:34:33 +00001339 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001340 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001341 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001342 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001343
Chad Rosier8f138d12012-10-15 17:19:13 +00001344 bool HadError = getTargetParser().ParseInstruction(OpcodeStr.str(), IDLoc,
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001345 ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001346
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001347 // Dump the parsed representation, if requested.
1348 if (getShowParsedOperands()) {
1349 SmallString<256> Str;
1350 raw_svector_ostream OS(Str);
1351 OS << "parsed instruction: [";
1352 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1353 if (i != 0)
1354 OS << ", ";
Jim Grosbachb7f689b2011-07-13 15:34:57 +00001355 ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001356 }
1357 OS << "]";
1358
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001359 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001360 }
1361
Kevin Enderby613b7572011-11-01 22:27:22 +00001362 // If we are generating dwarf for assembly source files and the current
1363 // section is the initial text section then generate a .loc directive for
1364 // the instruction.
1365 if (!HadError && getContext().getGenDwarfForAssembly() &&
1366 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1367 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1368 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1369 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001370 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001371 StringRef());
1372 }
1373
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001374 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001375 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001376 unsigned ErrorInfo;
1377 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Opcode,
Chad Rosier8f138d12012-10-15 17:19:13 +00001378 ParsedOperands, Out,
1379 ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001380 ParsingInlineAsm);
1381 }
Chris Lattner98986712010-01-14 22:21:20 +00001382
Chad Rosier8f138d12012-10-15 17:19:13 +00001383 // Free any parsed operands. If parsing ms-style inline assembly it is the
1384 // responsibility of the caller (i.e., clang) to free the parsed operands.
1385 if (!ParsingInlineAsm)
1386 freeParsedOperands();
Chris Lattner98986712010-01-14 22:21:20 +00001387
Chris Lattnercbf8a982010-09-11 16:18:25 +00001388 // Don't skip the rest of the line, the instruction parser is responsible for
1389 // that.
1390 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001391}
Chris Lattner9a023f72009-06-24 04:43:34 +00001392
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001393/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1394/// since they may not be able to be tokenized to get to the end of line token.
1395void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001396 if (!Lexer.is(AsmToken::EndOfStatement))
1397 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001398 // Eat EOL.
1399 Lex();
1400}
1401
1402/// ParseCppHashLineFilenameComment as this:
1403/// ::= # number "filename"
1404/// or just as a full line comment if it doesn't have a number and a string.
1405bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1406 Lex(); // Eat the hash token.
1407
1408 if (getLexer().isNot(AsmToken::Integer)) {
1409 // Consume the line since in cases it is not a well-formed line directive,
1410 // as if were simply a full line comment.
1411 EatToEndOfLine();
1412 return false;
1413 }
1414
1415 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001416 Lex();
1417
1418 if (getLexer().isNot(AsmToken::String)) {
1419 EatToEndOfLine();
1420 return false;
1421 }
1422
1423 StringRef Filename = getTok().getString();
1424 // Get rid of the enclosing quotes.
1425 Filename = Filename.substr(1, Filename.size()-2);
1426
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001427 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1428 CppHashLoc = L;
1429 CppHashFilename = Filename;
1430 CppHashLineNumber = LineNumber;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001431
1432 // Ignore any trailing characters, they're just comment.
1433 EatToEndOfLine();
1434 return false;
1435}
1436
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001437/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001438/// for the Filename and LineNo if any in the diagnostic.
1439void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1440 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1441 raw_ostream &OS = errs();
1442
1443 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1444 const SMLoc &DiagLoc = Diag.getLoc();
1445 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1446 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1447
1448 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1449 // before printing the message.
1450 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001451 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001452 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1453 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1454 }
1455
1456 // If we have not parsed a cpp hash line filename comment or the source
1457 // manager changed or buffer changed (like in a nested include) then just
1458 // print the normal diagnostic using its Filename and LineNo.
1459 if (!Parser->CppHashLineNumber ||
1460 &DiagSrcMgr != &Parser->SrcMgr ||
1461 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001462 if (Parser->SavedDiagHandler)
1463 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1464 else
1465 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001466 return;
1467 }
1468
1469 // Use the CppHashFilename and calculate a line number based on the
1470 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1471 // the diagnostic.
1472 const std::string Filename = Parser->CppHashFilename;
1473
1474 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1475 int CppHashLocLineNo =
1476 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1477 int LineNo = Parser->CppHashLineNumber - 1 +
1478 (DiagLocLineNo - CppHashLocLineNo);
1479
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001480 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1481 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001482 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001483 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001484
Benjamin Kramer04a04262011-10-16 10:48:29 +00001485 if (Parser->SavedDiagHandler)
1486 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1487 else
1488 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001489}
1490
Rafael Espindola799aacf2012-08-21 18:29:30 +00001491// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1492// difference being that that function accepts '@' as part of identifiers and
1493// we can't do that. AsmLexer.cpp should probably be changed to handle
1494// '@' as a special case when needed.
1495static bool isIdentifierChar(char c) {
1496 return isalnum(c) || c == '_' || c == '$' || c == '.';
1497}
1498
Rafael Espindola761cb062012-06-03 23:57:14 +00001499bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001500 const MacroParameters &Parameters,
1501 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001502 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001503 unsigned NParameters = Parameters.size();
1504 if (NParameters != 0 && NParameters != A.size())
1505 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001506
Preston Gurd7b6f2032012-09-19 20:36:12 +00001507 // A macro without parameters is handled differently on Darwin:
1508 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001509 while (!Body.empty()) {
1510 // Scan for the next substitution.
1511 std::size_t End = Body.size(), Pos = 0;
1512 for (; Pos != End; ++Pos) {
1513 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001514 if (!NParameters) {
1515 // This macro has no parameters, look for $0, $1, etc.
1516 if (Body[Pos] != '$' || Pos + 1 == End)
1517 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001518
Rafael Espindola65366442011-06-05 02:43:45 +00001519 char Next = Body[Pos + 1];
1520 if (Next == '$' || Next == 'n' || isdigit(Next))
1521 break;
1522 } else {
1523 // This macro has parameters, look for \foo, \bar, etc.
1524 if (Body[Pos] == '\\' && Pos + 1 != End)
1525 break;
1526 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001527 }
1528
1529 // Add the prefix.
1530 OS << Body.slice(0, Pos);
1531
1532 // Check if we reached the end.
1533 if (Pos == End)
1534 break;
1535
Rafael Espindola65366442011-06-05 02:43:45 +00001536 if (!NParameters) {
1537 switch (Body[Pos+1]) {
1538 // $$ => $
1539 case '$':
1540 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001541 break;
1542
Rafael Espindola65366442011-06-05 02:43:45 +00001543 // $n => number of arguments
1544 case 'n':
1545 OS << A.size();
1546 break;
1547
1548 // $[0-9] => argument
1549 default: {
1550 // Missing arguments are ignored.
1551 unsigned Index = Body[Pos+1] - '0';
1552 if (Index >= A.size())
1553 break;
1554
1555 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001556 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001557 ie = A[Index].end(); it != ie; ++it)
1558 OS << it->getString();
1559 break;
1560 }
1561 }
1562 Pos += 2;
1563 } else {
1564 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001565 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001566 ++I;
1567
1568 const char *Begin = Body.data() + Pos +1;
1569 StringRef Argument(Begin, I - (Pos +1));
1570 unsigned Index = 0;
1571 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001572 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001573 break;
1574
Preston Gurd7b6f2032012-09-19 20:36:12 +00001575 if (Index == NParameters) {
1576 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1577 Pos += 3;
1578 else {
1579 OS << '\\' << Argument;
1580 Pos = I;
1581 }
1582 } else {
1583 for (MacroArgument::const_iterator it = A[Index].begin(),
1584 ie = A[Index].end(); it != ie; ++it)
1585 if (it->getKind() == AsmToken::String)
1586 OS << it->getStringContents();
1587 else
1588 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001589
Preston Gurd7b6f2032012-09-19 20:36:12 +00001590 Pos += 1 + Argument.size();
1591 }
Rafael Espindola65366442011-06-05 02:43:45 +00001592 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001593 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001594 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001595 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001596
Rafael Espindola65366442011-06-05 02:43:45 +00001597 return false;
1598}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001599
Rafael Espindola65366442011-06-05 02:43:45 +00001600MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1601 MemoryBuffer *I)
1602 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1603{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001604}
1605
Preston Gurd7b6f2032012-09-19 20:36:12 +00001606static bool IsOperator(AsmToken::TokenKind kind)
1607{
1608 switch (kind)
1609 {
1610 default:
1611 return false;
1612 case AsmToken::Plus:
1613 case AsmToken::Minus:
1614 case AsmToken::Tilde:
1615 case AsmToken::Slash:
1616 case AsmToken::Star:
1617 case AsmToken::Dot:
1618 case AsmToken::Equal:
1619 case AsmToken::EqualEqual:
1620 case AsmToken::Pipe:
1621 case AsmToken::PipePipe:
1622 case AsmToken::Caret:
1623 case AsmToken::Amp:
1624 case AsmToken::AmpAmp:
1625 case AsmToken::Exclaim:
1626 case AsmToken::ExclaimEqual:
1627 case AsmToken::Percent:
1628 case AsmToken::Less:
1629 case AsmToken::LessEqual:
1630 case AsmToken::LessLess:
1631 case AsmToken::LessGreater:
1632 case AsmToken::Greater:
1633 case AsmToken::GreaterEqual:
1634 case AsmToken::GreaterGreater:
1635 return true;
1636 }
1637}
1638
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001639/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1640/// This is used for both default macro parameter values and the
1641/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001642bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1643 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001644 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001645 unsigned AddTokens = 0;
1646
1647 // gas accepts arguments separated by whitespace, except on Darwin
1648 if (!IsDarwin)
1649 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001650
1651 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001652 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1653 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001654 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001655 }
1656
1657 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1658 // Spaces and commas cannot be mixed to delimit parameters
1659 if (ArgumentDelimiter == AsmToken::Eof)
1660 ArgumentDelimiter = AsmToken::Comma;
1661 else if (ArgumentDelimiter != AsmToken::Comma) {
1662 Lexer.setSkipSpace(true);
1663 return TokError("expected ' ' for macro argument separator");
1664 }
1665 break;
1666 }
1667
1668 if (Lexer.is(AsmToken::Space)) {
1669 Lex(); // Eat spaces
1670
1671 // Spaces can delimit parameters, but could also be part an expression.
1672 // If the token after a space is an operator, add the token and the next
1673 // one into this argument
1674 if (ArgumentDelimiter == AsmToken::Space ||
1675 ArgumentDelimiter == AsmToken::Eof) {
1676 if (IsOperator(Lexer.getKind())) {
1677 // Check to see whether the token is used as an operator,
1678 // or part of an identifier
1679 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1680 if (*NextChar == ' ')
1681 AddTokens = 2;
1682 }
1683
1684 if (!AddTokens && ParenLevel == 0) {
1685 if (ArgumentDelimiter == AsmToken::Eof &&
1686 !IsOperator(Lexer.getKind()))
1687 ArgumentDelimiter = AsmToken::Space;
1688 break;
1689 }
1690 }
1691 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001692
1693 // HandleMacroEntry relies on not advancing the lexer here
1694 // to be able to fill in the remaining default parameter values
1695 if (Lexer.is(AsmToken::EndOfStatement))
1696 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001697
1698 // Adjust the current parentheses level.
1699 if (Lexer.is(AsmToken::LParen))
1700 ++ParenLevel;
1701 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1702 --ParenLevel;
1703
1704 // Append the token to the current argument list.
1705 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001706 if (AddTokens)
1707 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001708 Lex();
1709 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001710
1711 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001712 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001713 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001714 return false;
1715}
1716
1717// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001718bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001719 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001720 // Argument delimiter is initially unknown. It will be set by
1721 // ParseMacroArgument()
1722 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001723
1724 // Parse two kinds of macro invocations:
1725 // - macros defined without any parameters accept an arbitrary number of them
1726 // - macros defined with parameters accept at most that many of them
1727 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1728 ++Parameter) {
1729 MacroArgument MA;
1730
Preston Gurd7b6f2032012-09-19 20:36:12 +00001731 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001732 return true;
1733
Preston Gurd6c9176a2012-09-19 20:29:04 +00001734 if (!MA.empty() || !NParameters)
1735 A.push_back(MA);
1736 else if (NParameters) {
1737 if (!M->Parameters[Parameter].second.empty())
1738 A.push_back(M->Parameters[Parameter].second);
1739 }
Jim Grosbach97146442012-07-30 22:44:17 +00001740
Preston Gurd6c9176a2012-09-19 20:29:04 +00001741 // At the end of the statement, fill in remaining arguments that have
1742 // default values. If there aren't any, then the next argument is
1743 // required but missing
1744 if (Lexer.is(AsmToken::EndOfStatement)) {
1745 if (NParameters && Parameter < NParameters - 1) {
1746 if (M->Parameters[Parameter + 1].second.empty())
1747 return TokError("macro argument '" +
1748 Twine(M->Parameters[Parameter + 1].first) +
1749 "' is missing");
1750 else
1751 continue;
1752 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001753 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001754 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001755
1756 if (Lexer.is(AsmToken::Comma))
1757 Lex();
1758 }
1759 return TokError("Too many arguments");
1760}
1761
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001762bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1763 const Macro *M) {
1764 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1765 // this, although we should protect against infinite loops.
1766 if (ActiveMacros.size() == 20)
1767 return TokError("macros cannot be nested more than 20 levels deep");
1768
Rafael Espindola8a403d32012-08-08 14:51:03 +00001769 MacroArguments A;
1770 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001771 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001772
Jim Grosbach97146442012-07-30 22:44:17 +00001773 // Remove any trailing empty arguments. Do this after-the-fact as we have
1774 // to keep empty arguments in the middle of the list or positionality
1775 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001776 while (!A.empty() && A.back().empty())
1777 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001778
Rafael Espindola65366442011-06-05 02:43:45 +00001779 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1780 // to hold the macro body with substitutions.
1781 SmallString<256> Buf;
1782 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001783 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001784
Rafael Espindola8a403d32012-08-08 14:51:03 +00001785 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001786 return true;
1787
Rafael Espindola761cb062012-06-03 23:57:14 +00001788 // We include the .endmacro in the buffer as our queue to exit the macro
1789 // instantiation.
1790 OS << ".endmacro\n";
1791
Rafael Espindola65366442011-06-05 02:43:45 +00001792 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001793 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001794
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001795 // Create the macro instantiation object and add to the current macro
1796 // instantiation stack.
1797 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001798 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001799 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001800 ActiveMacros.push_back(MI);
1801
1802 // Jump to the macro instantiation and prime the lexer.
1803 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1804 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1805 Lex();
1806
1807 return false;
1808}
1809
1810void AsmParser::HandleMacroExit() {
1811 // Jump to the EndOfStatement we should return to, and consume it.
1812 JumpToLoc(ActiveMacros.back()->ExitLoc);
1813 Lex();
1814
1815 // Pop the instantiation entry.
1816 delete ActiveMacros.back();
1817 ActiveMacros.pop_back();
1818}
1819
Rafael Espindolae71cc862012-01-28 05:57:00 +00001820static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001821 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001822 case MCExpr::Binary: {
1823 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1824 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001825 break;
1826 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001827 case MCExpr::Target:
1828 case MCExpr::Constant:
1829 return false;
1830 case MCExpr::SymbolRef: {
1831 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001832 if (S.isVariable())
1833 return IsUsedIn(Sym, S.getVariableValue());
1834 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001835 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001836 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001837 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001838 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001839
1840 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001841}
1842
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001843bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1844 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001845 // FIXME: Use better location, we should use proper tokens.
1846 SMLoc EqualLoc = Lexer.getLoc();
1847
Daniel Dunbar821e3332009-08-31 08:09:28 +00001848 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001849 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001850 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001851
Rafael Espindolae71cc862012-01-28 05:57:00 +00001852 // Note: we don't count b as used in "a = b". This is to allow
1853 // a = b
1854 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001855
Daniel Dunbar3f872332009-07-28 16:08:33 +00001856 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001857 return TokError("unexpected token in assignment");
1858
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001859 // Error on assignment to '.'.
1860 if (Name == ".") {
1861 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1862 "(use '.space' or '.org').)"));
1863 }
1864
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001865 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001866 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001867
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001868 // Validate that the LHS is allowed to be a variable (either it has not been
1869 // used as a symbol, or it is an absolute symbol).
1870 MCSymbol *Sym = getContext().LookupSymbol(Name);
1871 if (Sym) {
1872 // Diagnose assignment to a label.
1873 //
1874 // FIXME: Diagnostics. Note the location of the definition as a label.
1875 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001876 if (IsUsedIn(Sym, Value))
1877 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1878 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001879 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001880 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1881 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001882 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001883 return Error(EqualLoc, "redefinition of '" + Name + "'");
1884 else if (!Sym->isVariable())
1885 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001886 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001887 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1888 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001889
1890 // Don't count these checks as uses.
1891 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001892 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001893 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001894
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001895 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001896
1897 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001898 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001899 if (NoDeadStrip)
1900 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1901
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001902
1903 return false;
1904}
1905
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001906/// ParseIdentifier:
1907/// ::= identifier
1908/// ::= string
1909bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001910 // The assembler has relaxed rules for accepting identifiers, in particular we
1911 // allow things like '.globl $foo', which would normally be separate
1912 // tokens. At this level, we have already lexed so we cannot (currently)
1913 // handle this as a context dependent token, instead we detect adjacent tokens
1914 // and return the combined identifier.
1915 if (Lexer.is(AsmToken::Dollar)) {
1916 SMLoc DollarLoc = getLexer().getLoc();
1917
1918 // Consume the dollar sign, and check for a following identifier.
1919 Lex();
1920 if (Lexer.isNot(AsmToken::Identifier))
1921 return true;
1922
1923 // We have a '$' followed by an identifier, make sure they are adjacent.
1924 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1925 return true;
1926
1927 // Construct the joined identifier and consume the token.
1928 Res = StringRef(DollarLoc.getPointer(),
1929 getTok().getIdentifier().size() + 1);
1930 Lex();
1931 return false;
1932 }
1933
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001934 if (Lexer.isNot(AsmToken::Identifier) &&
1935 Lexer.isNot(AsmToken::String))
1936 return true;
1937
Sean Callanan18b83232010-01-19 21:44:56 +00001938 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001939
Sean Callanan79ed1a82010-01-19 20:22:31 +00001940 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001941
1942 return false;
1943}
1944
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001945/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001946/// ::= .equ identifier ',' expression
1947/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001948/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001949bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001950 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001951
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001952 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001953 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001954
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001955 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001956 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001957 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001958
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001959 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001960}
1961
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001962bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001963 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001964
1965 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00001966 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001967 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1968 if (Str[i] != '\\') {
1969 Data += Str[i];
1970 continue;
1971 }
1972
1973 // Recognize escaped characters. Note that this escape semantics currently
1974 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1975 ++i;
1976 if (i == e)
1977 return TokError("unexpected backslash at end of string");
1978
1979 // Recognize octal sequences.
1980 if ((unsigned) (Str[i] - '0') <= 7) {
1981 // Consume up to three octal characters.
1982 unsigned Value = Str[i] - '0';
1983
1984 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1985 ++i;
1986 Value = Value * 8 + (Str[i] - '0');
1987
1988 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1989 ++i;
1990 Value = Value * 8 + (Str[i] - '0');
1991 }
1992 }
1993
1994 if (Value > 255)
1995 return TokError("invalid octal escape sequence (out of range)");
1996
1997 Data += (unsigned char) Value;
1998 continue;
1999 }
2000
2001 // Otherwise recognize individual escapes.
2002 switch (Str[i]) {
2003 default:
2004 // Just reject invalid escape sequences for now.
2005 return TokError("invalid escape sequence (unrecognized character)");
2006
2007 case 'b': Data += '\b'; break;
2008 case 'f': Data += '\f'; break;
2009 case 'n': Data += '\n'; break;
2010 case 'r': Data += '\r'; break;
2011 case 't': Data += '\t'; break;
2012 case '"': Data += '"'; break;
2013 case '\\': Data += '\\'; break;
2014 }
2015 }
2016
2017 return false;
2018}
2019
Daniel Dunbara0d14262009-06-24 23:30:00 +00002020/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002021/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2022bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002023 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002024 CheckForValidSection();
2025
Daniel Dunbara0d14262009-06-24 23:30:00 +00002026 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002027 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002028 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002029
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002030 std::string Data;
2031 if (ParseEscapedString(Data))
2032 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002033
2034 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002035 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002036 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2037
Sean Callanan79ed1a82010-01-19 20:22:31 +00002038 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002039
2040 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002041 break;
2042
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002043 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002044 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002045 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002046 }
2047 }
2048
Sean Callanan79ed1a82010-01-19 20:22:31 +00002049 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002050 return false;
2051}
2052
2053/// ParseDirectiveValue
2054/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2055bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002056 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002057 CheckForValidSection();
2058
Daniel Dunbara0d14262009-06-24 23:30:00 +00002059 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002060 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002061 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002062 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002063 return true;
2064
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002065 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002066 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2067 assert(Size <= 8 && "Invalid size");
2068 uint64_t IntValue = MCE->getValue();
2069 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2070 return Error(ExprLoc, "literal value out of range for directive");
2071 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2072 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002073 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002074
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002075 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002076 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002077
Daniel Dunbara0d14262009-06-24 23:30:00 +00002078 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002079 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002080 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002081 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002082 }
2083 }
2084
Sean Callanan79ed1a82010-01-19 20:22:31 +00002085 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002086 return false;
2087}
2088
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002089/// ParseDirectiveRealValue
2090/// ::= (.single | .double) [ expression (, expression)* ]
2091bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2092 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2093 CheckForValidSection();
2094
2095 for (;;) {
2096 // We don't truly support arithmetic on floating point expressions, so we
2097 // have to manually parse unary prefixes.
2098 bool IsNeg = false;
2099 if (getLexer().is(AsmToken::Minus)) {
2100 Lex();
2101 IsNeg = true;
2102 } else if (getLexer().is(AsmToken::Plus))
2103 Lex();
2104
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002105 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002106 getLexer().isNot(AsmToken::Real) &&
2107 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002108 return TokError("unexpected token in directive");
2109
2110 // Convert to an APFloat.
2111 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002112 StringRef IDVal = getTok().getString();
2113 if (getLexer().is(AsmToken::Identifier)) {
2114 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2115 Value = APFloat::getInf(Semantics);
2116 else if (!IDVal.compare_lower("nan"))
2117 Value = APFloat::getNaN(Semantics, false, ~0);
2118 else
2119 return TokError("invalid floating point literal");
2120 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002121 APFloat::opInvalidOp)
2122 return TokError("invalid floating point literal");
2123 if (IsNeg)
2124 Value.changeSign();
2125
2126 // Consume the numeric token.
2127 Lex();
2128
2129 // Emit the value as an integer.
2130 APInt AsInt = Value.bitcastToAPInt();
2131 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2132 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2133
2134 if (getLexer().is(AsmToken::EndOfStatement))
2135 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002136
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002137 if (getLexer().isNot(AsmToken::Comma))
2138 return TokError("unexpected token in directive");
2139 Lex();
2140 }
2141 }
2142
2143 Lex();
2144 return false;
2145}
2146
Daniel Dunbara0d14262009-06-24 23:30:00 +00002147/// ParseDirectiveSpace
2148/// ::= .space expression [ , expression ]
2149bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002150 CheckForValidSection();
2151
Daniel Dunbara0d14262009-06-24 23:30:00 +00002152 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002153 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002154 return true;
2155
2156 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002157 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2158 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002159 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002160 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002161
Daniel Dunbar475839e2009-06-29 20:37:27 +00002162 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002163 return true;
2164
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002165 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002166 return TokError("unexpected token in '.space' directive");
2167 }
2168
Sean Callanan79ed1a82010-01-19 20:22:31 +00002169 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002170
2171 if (NumBytes <= 0)
2172 return TokError("invalid number of bytes in '.space' directive");
2173
2174 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002175 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002176
2177 return false;
2178}
2179
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002180/// ParseDirectiveZero
2181/// ::= .zero expression
2182bool AsmParser::ParseDirectiveZero() {
2183 CheckForValidSection();
2184
2185 int64_t NumBytes;
2186 if (ParseAbsoluteExpression(NumBytes))
2187 return true;
2188
Rafael Espindolae452b172010-10-05 19:42:57 +00002189 int64_t Val = 0;
2190 if (getLexer().is(AsmToken::Comma)) {
2191 Lex();
2192 if (ParseAbsoluteExpression(Val))
2193 return true;
2194 }
2195
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002196 if (getLexer().isNot(AsmToken::EndOfStatement))
2197 return TokError("unexpected token in '.zero' directive");
2198
2199 Lex();
2200
Rafael Espindolae452b172010-10-05 19:42:57 +00002201 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002202
2203 return false;
2204}
2205
Daniel Dunbara0d14262009-06-24 23:30:00 +00002206/// ParseDirectiveFill
2207/// ::= .fill expression , expression , expression
2208bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002209 CheckForValidSection();
2210
Daniel Dunbara0d14262009-06-24 23:30:00 +00002211 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002212 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002213 return true;
2214
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002215 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002216 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002217 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002218
Daniel Dunbara0d14262009-06-24 23:30:00 +00002219 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002220 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002221 return true;
2222
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002223 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002224 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002225 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002226
Daniel Dunbara0d14262009-06-24 23:30:00 +00002227 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002228 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002229 return true;
2230
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002231 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002232 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002233
Sean Callanan79ed1a82010-01-19 20:22:31 +00002234 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002235
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002236 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2237 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002238
2239 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002240 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002241
2242 return false;
2243}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002244
2245/// ParseDirectiveOrg
2246/// ::= .org expression [ , expression ]
2247bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002248 CheckForValidSection();
2249
Daniel Dunbar821e3332009-08-31 08:09:28 +00002250 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002251 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002252 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002253 return true;
2254
2255 // Parse optional fill expression.
2256 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002257 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2258 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002259 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002260 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002261
Daniel Dunbar475839e2009-06-29 20:37:27 +00002262 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002263 return true;
2264
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002265 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002266 return TokError("unexpected token in '.org' directive");
2267 }
2268
Sean Callanan79ed1a82010-01-19 20:22:31 +00002269 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002270
Jim Grosbachebd4c052012-01-27 00:37:08 +00002271 // Only limited forms of relocatable expressions are accepted here, it
2272 // has to be relative to the current section. The streamer will return
2273 // 'true' if the expression wasn't evaluatable.
2274 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2275 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002276
2277 return false;
2278}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002279
2280/// ParseDirectiveAlign
2281/// ::= {.align, ...} expression [ , expression [ , expression ]]
2282bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002283 CheckForValidSection();
2284
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002285 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002286 int64_t Alignment;
2287 if (ParseAbsoluteExpression(Alignment))
2288 return true;
2289
2290 SMLoc MaxBytesLoc;
2291 bool HasFillExpr = false;
2292 int64_t FillExpr = 0;
2293 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002294 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2295 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002296 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002297 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002298
2299 // The fill expression can be omitted while specifying a maximum number of
2300 // alignment bytes, e.g:
2301 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002302 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002303 HasFillExpr = true;
2304 if (ParseAbsoluteExpression(FillExpr))
2305 return true;
2306 }
2307
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002308 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2309 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002310 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002311 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002312
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002313 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002314 if (ParseAbsoluteExpression(MaxBytesToFill))
2315 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002316
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002317 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002318 return TokError("unexpected token in directive");
2319 }
2320 }
2321
Sean Callanan79ed1a82010-01-19 20:22:31 +00002322 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002323
Daniel Dunbar648ac512010-05-17 21:54:30 +00002324 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002325 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002326
2327 // Compute alignment in bytes.
2328 if (IsPow2) {
2329 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002330 if (Alignment >= 32) {
2331 Error(AlignmentLoc, "invalid alignment value");
2332 Alignment = 31;
2333 }
2334
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002335 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002336 }
2337
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002338 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002339 if (MaxBytesLoc.isValid()) {
2340 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002341 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2342 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002343 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002344 }
2345
2346 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002347 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2348 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002349 MaxBytesToFill = 0;
2350 }
2351 }
2352
Daniel Dunbar648ac512010-05-17 21:54:30 +00002353 // Check whether we should use optimal code alignment for this .align
2354 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002355 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002356 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2357 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002358 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002359 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002360 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002361 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2362 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002363 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002364
2365 return false;
2366}
2367
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002368/// ParseDirectiveSymbolAttribute
2369/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002370bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002371 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002372 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002373 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002374 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002375
2376 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002377 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002378
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002379 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002380
Jim Grosbach10ec6502011-09-15 17:56:49 +00002381 // Assembler local symbols don't make any sense here. Complain loudly.
2382 if (Sym->isTemporary())
2383 return Error(Loc, "non-local symbol required in directive");
2384
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002385 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002386
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002387 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002388 break;
2389
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002390 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002391 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002392 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002393 }
2394 }
2395
Sean Callanan79ed1a82010-01-19 20:22:31 +00002396 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002397 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002398}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002399
2400/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002401/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2402bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002403 CheckForValidSection();
2404
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002405 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002406 StringRef Name;
2407 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002408 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002409
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002410 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002411 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002412
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002413 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002414 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002415 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002416
2417 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002418 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002419 if (ParseAbsoluteExpression(Size))
2420 return true;
2421
2422 int64_t Pow2Alignment = 0;
2423 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002424 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002425 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002426 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002427 if (ParseAbsoluteExpression(Pow2Alignment))
2428 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002429
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002430 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2431 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002432 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2433
Chris Lattner258281d2010-01-19 06:22:22 +00002434 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002435 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2436 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002437 if (!isPowerOf2_64(Pow2Alignment))
2438 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2439 Pow2Alignment = Log2_64(Pow2Alignment);
2440 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002441 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002442
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002443 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002444 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002445
Sean Callanan79ed1a82010-01-19 20:22:31 +00002446 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002447
Chris Lattner1fc3d752009-07-09 17:25:12 +00002448 // NOTE: a size of zero for a .comm should create a undefined symbol
2449 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002450 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002451 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2452 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002453
Eric Christopherc260a3e2010-05-14 01:38:54 +00002454 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002455 // may internally end up wanting an alignment in bytes.
2456 // FIXME: Diagnose overflow.
2457 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002458 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2459 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002460
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002461 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002462 return Error(IDLoc, "invalid symbol redefinition");
2463
Chris Lattner1fc3d752009-07-09 17:25:12 +00002464 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002465 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002466 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002467 return false;
2468 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002469
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002470 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002471 return false;
2472}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002473
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002474/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002475/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002476bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002477 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002478 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002479
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002480 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002481 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002482 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002483
Sean Callanan79ed1a82010-01-19 20:22:31 +00002484 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002485
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002486 if (Str.empty())
2487 Error(Loc, ".abort detected. Assembly stopping.");
2488 else
2489 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002490 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002491
2492 return false;
2493}
Kevin Enderby71148242009-07-14 21:35:03 +00002494
Kevin Enderby1f049b22009-07-14 23:21:55 +00002495/// ParseDirectiveInclude
2496/// ::= .include "filename"
2497bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002498 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002499 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002500
Sean Callanan18b83232010-01-19 21:44:56 +00002501 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002502 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002503 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002504
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002505 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002506 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002507
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002508 // Strip the quotes.
2509 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002510
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002511 // Attempt to switch the lexer to the included file before consuming the end
2512 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002513 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002514 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002515 return true;
2516 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002517
2518 return false;
2519}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002520
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002521/// ParseDirectiveIncbin
2522/// ::= .incbin "filename"
2523bool AsmParser::ParseDirectiveIncbin() {
2524 if (getLexer().isNot(AsmToken::String))
2525 return TokError("expected string in '.incbin' directive");
2526
2527 std::string Filename = getTok().getString();
2528 SMLoc IncbinLoc = getLexer().getLoc();
2529 Lex();
2530
2531 if (getLexer().isNot(AsmToken::EndOfStatement))
2532 return TokError("unexpected token in '.incbin' directive");
2533
2534 // Strip the quotes.
2535 Filename = Filename.substr(1, Filename.size()-2);
2536
2537 // Attempt to process the included file.
2538 if (ProcessIncbinFile(Filename)) {
2539 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2540 return true;
2541 }
2542
2543 return false;
2544}
2545
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002546/// ParseDirectiveIf
2547/// ::= .if expression
2548bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002549 TheCondStack.push_back(TheCondState);
2550 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002551 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002552 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002553 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002554 int64_t ExprValue;
2555 if (ParseAbsoluteExpression(ExprValue))
2556 return true;
2557
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002558 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002559 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002560
Sean Callanan79ed1a82010-01-19 20:22:31 +00002561 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002562
2563 TheCondState.CondMet = ExprValue;
2564 TheCondState.Ignore = !TheCondState.CondMet;
2565 }
2566
2567 return false;
2568}
2569
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002570/// ParseDirectiveIfb
2571/// ::= .ifb string
2572bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2573 TheCondStack.push_back(TheCondState);
2574 TheCondState.TheCond = AsmCond::IfCond;
2575
Benjamin Kramer29739e72012-05-12 16:52:21 +00002576 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002577 EatToEndOfStatement();
2578 } else {
2579 StringRef Str = ParseStringToEndOfStatement();
2580
2581 if (getLexer().isNot(AsmToken::EndOfStatement))
2582 return TokError("unexpected token in '.ifb' directive");
2583
2584 Lex();
2585
2586 TheCondState.CondMet = ExpectBlank == Str.empty();
2587 TheCondState.Ignore = !TheCondState.CondMet;
2588 }
2589
2590 return false;
2591}
2592
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002593/// ParseDirectiveIfc
2594/// ::= .ifc string1, string2
2595bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2596 TheCondStack.push_back(TheCondState);
2597 TheCondState.TheCond = AsmCond::IfCond;
2598
Benjamin Kramer29739e72012-05-12 16:52:21 +00002599 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002600 EatToEndOfStatement();
2601 } else {
2602 StringRef Str1 = ParseStringToComma();
2603
2604 if (getLexer().isNot(AsmToken::Comma))
2605 return TokError("unexpected token in '.ifc' directive");
2606
2607 Lex();
2608
2609 StringRef Str2 = ParseStringToEndOfStatement();
2610
2611 if (getLexer().isNot(AsmToken::EndOfStatement))
2612 return TokError("unexpected token in '.ifc' directive");
2613
2614 Lex();
2615
2616 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2617 TheCondState.Ignore = !TheCondState.CondMet;
2618 }
2619
2620 return false;
2621}
2622
2623/// ParseDirectiveIfdef
2624/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002625bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2626 StringRef Name;
2627 TheCondStack.push_back(TheCondState);
2628 TheCondState.TheCond = AsmCond::IfCond;
2629
2630 if (TheCondState.Ignore) {
2631 EatToEndOfStatement();
2632 } else {
2633 if (ParseIdentifier(Name))
2634 return TokError("expected identifier after '.ifdef'");
2635
2636 Lex();
2637
2638 MCSymbol *Sym = getContext().LookupSymbol(Name);
2639
2640 if (expect_defined)
2641 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2642 else
2643 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2644 TheCondState.Ignore = !TheCondState.CondMet;
2645 }
2646
2647 return false;
2648}
2649
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002650/// ParseDirectiveElseIf
2651/// ::= .elseif expression
2652bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2653 if (TheCondState.TheCond != AsmCond::IfCond &&
2654 TheCondState.TheCond != AsmCond::ElseIfCond)
2655 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2656 " an .elseif");
2657 TheCondState.TheCond = AsmCond::ElseIfCond;
2658
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002659 bool LastIgnoreState = false;
2660 if (!TheCondStack.empty())
2661 LastIgnoreState = TheCondStack.back().Ignore;
2662 if (LastIgnoreState || TheCondState.CondMet) {
2663 TheCondState.Ignore = true;
2664 EatToEndOfStatement();
2665 }
2666 else {
2667 int64_t ExprValue;
2668 if (ParseAbsoluteExpression(ExprValue))
2669 return true;
2670
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002671 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002672 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002673
Sean Callanan79ed1a82010-01-19 20:22:31 +00002674 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002675 TheCondState.CondMet = ExprValue;
2676 TheCondState.Ignore = !TheCondState.CondMet;
2677 }
2678
2679 return false;
2680}
2681
2682/// ParseDirectiveElse
2683/// ::= .else
2684bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002685 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002686 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002687
Sean Callanan79ed1a82010-01-19 20:22:31 +00002688 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002689
2690 if (TheCondState.TheCond != AsmCond::IfCond &&
2691 TheCondState.TheCond != AsmCond::ElseIfCond)
2692 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2693 ".elseif");
2694 TheCondState.TheCond = AsmCond::ElseCond;
2695 bool LastIgnoreState = false;
2696 if (!TheCondStack.empty())
2697 LastIgnoreState = TheCondStack.back().Ignore;
2698 if (LastIgnoreState || TheCondState.CondMet)
2699 TheCondState.Ignore = true;
2700 else
2701 TheCondState.Ignore = false;
2702
2703 return false;
2704}
2705
2706/// ParseDirectiveEndIf
2707/// ::= .endif
2708bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002709 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002710 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002711
Sean Callanan79ed1a82010-01-19 20:22:31 +00002712 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002713
2714 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2715 TheCondStack.empty())
2716 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2717 ".else");
2718 if (!TheCondStack.empty()) {
2719 TheCondState = TheCondStack.back();
2720 TheCondStack.pop_back();
2721 }
2722
2723 return false;
2724}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002725
2726/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002727/// ::= .file [number] filename
2728/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002729bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002730 // FIXME: I'm not sure what this is.
2731 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002732 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002733 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002734 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002735 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002736
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002737 if (FileNumber < 1)
2738 return TokError("file number less than one");
2739 }
2740
Daniel Dunbareceec052010-07-12 17:45:27 +00002741 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002742 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002743
Nick Lewycky44d798d2011-10-17 23:05:28 +00002744 // Usually the directory and filename together, otherwise just the directory.
2745 StringRef Path = getTok().getString();
2746 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002747 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002748
Nick Lewycky44d798d2011-10-17 23:05:28 +00002749 StringRef Directory;
2750 StringRef Filename;
2751 if (getLexer().is(AsmToken::String)) {
2752 if (FileNumber == -1)
2753 return TokError("explicit path specified, but no file number");
2754 Filename = getTok().getString();
2755 Filename = Filename.substr(1, Filename.size()-2);
2756 Directory = Path;
2757 Lex();
2758 } else {
2759 Filename = Path;
2760 }
2761
Daniel Dunbareceec052010-07-12 17:45:27 +00002762 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002763 return TokError("unexpected token in '.file' directive");
2764
Chris Lattnerd32e8032010-01-25 19:02:58 +00002765 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002766 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002767 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002768 if (getContext().getGenDwarfForAssembly() == true)
2769 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2770 "used to generate dwarf debug info for assembly code");
2771
Nick Lewycky44d798d2011-10-17 23:05:28 +00002772 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002773 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002774 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002775
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002776 return false;
2777}
2778
2779/// ParseDirectiveLine
2780/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002781bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002782 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2783 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002784 return TokError("unexpected token in '.line' directive");
2785
Sean Callanan18b83232010-01-19 21:44:56 +00002786 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002787 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002788 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002789
2790 // FIXME: Do something with the .line.
2791 }
2792
Daniel Dunbareceec052010-07-12 17:45:27 +00002793 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002794 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002795
2796 return false;
2797}
2798
2799
2800/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002801/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002802/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2803/// The first number is a file number, must have been previously assigned with
2804/// a .file directive, the second number is the line number and optionally the
2805/// third number is a column position (zero if not specified). The remaining
2806/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002807bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002808
Daniel Dunbareceec052010-07-12 17:45:27 +00002809 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002810 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002811 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002812 if (FileNumber < 1)
2813 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002814 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002815 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002816 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002817
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002818 int64_t LineNumber = 0;
2819 if (getLexer().is(AsmToken::Integer)) {
2820 LineNumber = getTok().getIntVal();
2821 if (LineNumber < 1)
2822 return TokError("line number less than one in '.loc' directive");
2823 Lex();
2824 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002825
2826 int64_t ColumnPos = 0;
2827 if (getLexer().is(AsmToken::Integer)) {
2828 ColumnPos = getTok().getIntVal();
2829 if (ColumnPos < 0)
2830 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002831 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002832 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002833
Kevin Enderbyc0957932010-09-30 16:52:03 +00002834 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002835 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002836 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002837 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2838 for (;;) {
2839 if (getLexer().is(AsmToken::EndOfStatement))
2840 break;
2841
2842 StringRef Name;
2843 SMLoc Loc = getTok().getLoc();
2844 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002845 return TokError("unexpected token in '.loc' directive");
2846
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002847 if (Name == "basic_block")
2848 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2849 else if (Name == "prologue_end")
2850 Flags |= DWARF2_FLAG_PROLOGUE_END;
2851 else if (Name == "epilogue_begin")
2852 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2853 else if (Name == "is_stmt") {
2854 SMLoc Loc = getTok().getLoc();
2855 const MCExpr *Value;
2856 if (getParser().ParseExpression(Value))
2857 return true;
2858 // The expression must be the constant 0 or 1.
2859 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2860 int Value = MCE->getValue();
2861 if (Value == 0)
2862 Flags &= ~DWARF2_FLAG_IS_STMT;
2863 else if (Value == 1)
2864 Flags |= DWARF2_FLAG_IS_STMT;
2865 else
2866 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002867 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002868 else {
2869 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2870 }
2871 }
2872 else if (Name == "isa") {
2873 SMLoc Loc = getTok().getLoc();
2874 const MCExpr *Value;
2875 if (getParser().ParseExpression(Value))
2876 return true;
2877 // The expression must be a constant greater or equal to 0.
2878 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2879 int Value = MCE->getValue();
2880 if (Value < 0)
2881 return Error(Loc, "isa number less than zero");
2882 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002883 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002884 else {
2885 return Error(Loc, "isa number not a constant value");
2886 }
2887 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002888 else if (Name == "discriminator") {
2889 if (getParser().ParseAbsoluteExpression(Discriminator))
2890 return true;
2891 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002892 else {
2893 return Error(Loc, "unknown sub-directive in '.loc' directive");
2894 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002895
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002896 if (getLexer().is(AsmToken::EndOfStatement))
2897 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002898 }
2899 }
2900
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002901 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002902 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002903
2904 return false;
2905}
2906
Daniel Dunbar138abae2010-10-16 04:56:42 +00002907/// ParseDirectiveStabs
2908/// ::= .stabs string, number, number, number
2909bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2910 SMLoc DirectiveLoc) {
2911 return TokError("unsupported directive '" + Directive + "'");
2912}
2913
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002914/// ParseDirectiveCFISections
2915/// ::= .cfi_sections section [, section]
2916bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2917 SMLoc DirectiveLoc) {
2918 StringRef Name;
2919 bool EH = false;
2920 bool Debug = false;
2921
2922 if (getParser().ParseIdentifier(Name))
2923 return TokError("Expected an identifier");
2924
2925 if (Name == ".eh_frame")
2926 EH = true;
2927 else if (Name == ".debug_frame")
2928 Debug = true;
2929
2930 if (getLexer().is(AsmToken::Comma)) {
2931 Lex();
2932
2933 if (getParser().ParseIdentifier(Name))
2934 return TokError("Expected an identifier");
2935
2936 if (Name == ".eh_frame")
2937 EH = true;
2938 else if (Name == ".debug_frame")
2939 Debug = true;
2940 }
2941
2942 getStreamer().EmitCFISections(EH, Debug);
2943
2944 return false;
2945}
2946
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002947/// ParseDirectiveCFIStartProc
2948/// ::= .cfi_startproc
2949bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2950 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002951 getStreamer().EmitCFIStartProc();
2952 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002953}
2954
2955/// ParseDirectiveCFIEndProc
2956/// ::= .cfi_endproc
2957bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002958 getStreamer().EmitCFIEndProc();
2959 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002960}
2961
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002962/// ParseRegisterOrRegisterNumber - parse register name or number.
2963bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2964 SMLoc DirectiveLoc) {
2965 unsigned RegNo;
2966
Jim Grosbach6f888a82011-06-02 17:14:04 +00002967 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002968 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2969 DirectiveLoc))
2970 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00002971 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002972 } else
2973 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00002974
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002975 return false;
2976}
2977
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002978/// ParseDirectiveCFIDefCfa
2979/// ::= .cfi_def_cfa register, offset
2980bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2981 SMLoc DirectiveLoc) {
2982 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002983 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002984 return true;
2985
2986 if (getLexer().isNot(AsmToken::Comma))
2987 return TokError("unexpected token in directive");
2988 Lex();
2989
2990 int64_t Offset = 0;
2991 if (getParser().ParseAbsoluteExpression(Offset))
2992 return true;
2993
Rafael Espindola066c2f42011-04-12 23:59:07 +00002994 getStreamer().EmitCFIDefCfa(Register, Offset);
2995 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002996}
2997
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002998/// ParseDirectiveCFIDefCfaOffset
2999/// ::= .cfi_def_cfa_offset offset
3000bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3001 SMLoc DirectiveLoc) {
3002 int64_t Offset = 0;
3003 if (getParser().ParseAbsoluteExpression(Offset))
3004 return true;
3005
Rafael Espindola066c2f42011-04-12 23:59:07 +00003006 getStreamer().EmitCFIDefCfaOffset(Offset);
3007 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003008}
3009
3010/// ParseDirectiveCFIAdjustCfaOffset
3011/// ::= .cfi_adjust_cfa_offset adjustment
3012bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3013 SMLoc DirectiveLoc) {
3014 int64_t Adjustment = 0;
3015 if (getParser().ParseAbsoluteExpression(Adjustment))
3016 return true;
3017
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003018 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3019 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003020}
3021
3022/// ParseDirectiveCFIDefCfaRegister
3023/// ::= .cfi_def_cfa_register register
3024bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3025 SMLoc DirectiveLoc) {
3026 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003027 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003028 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003029
Rafael Espindola066c2f42011-04-12 23:59:07 +00003030 getStreamer().EmitCFIDefCfaRegister(Register);
3031 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003032}
3033
3034/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003035/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003036bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3037 int64_t Register = 0;
3038 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003039
3040 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003041 return true;
3042
3043 if (getLexer().isNot(AsmToken::Comma))
3044 return TokError("unexpected token in directive");
3045 Lex();
3046
3047 if (getParser().ParseAbsoluteExpression(Offset))
3048 return true;
3049
Rafael Espindola066c2f42011-04-12 23:59:07 +00003050 getStreamer().EmitCFIOffset(Register, Offset);
3051 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003052}
3053
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003054/// ParseDirectiveCFIRelOffset
3055/// ::= .cfi_rel_offset register, offset
3056bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3057 SMLoc DirectiveLoc) {
3058 int64_t Register = 0;
3059
3060 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3061 return true;
3062
3063 if (getLexer().isNot(AsmToken::Comma))
3064 return TokError("unexpected token in directive");
3065 Lex();
3066
3067 int64_t Offset = 0;
3068 if (getParser().ParseAbsoluteExpression(Offset))
3069 return true;
3070
Rafael Espindola25f492e2011-04-12 16:12:03 +00003071 getStreamer().EmitCFIRelOffset(Register, Offset);
3072 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003073}
3074
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003075static bool isValidEncoding(int64_t Encoding) {
3076 if (Encoding & ~0xff)
3077 return false;
3078
3079 if (Encoding == dwarf::DW_EH_PE_omit)
3080 return true;
3081
3082 const unsigned Format = Encoding & 0xf;
3083 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3084 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3085 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3086 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3087 return false;
3088
Rafael Espindolacaf11582010-12-29 04:31:26 +00003089 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003090 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003091 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003092 return false;
3093
3094 return true;
3095}
3096
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003097/// ParseDirectiveCFIPersonalityOrLsda
3098/// ::= .cfi_personality encoding, [symbol_name]
3099/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003100bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003101 SMLoc DirectiveLoc) {
3102 int64_t Encoding = 0;
3103 if (getParser().ParseAbsoluteExpression(Encoding))
3104 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003105 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003106 return false;
3107
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003108 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003109 return TokError("unsupported encoding.");
3110
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003111 if (getLexer().isNot(AsmToken::Comma))
3112 return TokError("unexpected token in directive");
3113 Lex();
3114
3115 StringRef Name;
3116 if (getParser().ParseIdentifier(Name))
3117 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003118
3119 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3120
3121 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003122 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003123 else {
3124 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003125 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003126 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003127 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003128}
3129
Rafael Espindolafe024d02010-12-28 18:36:23 +00003130/// ParseDirectiveCFIRememberState
3131/// ::= .cfi_remember_state
3132bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3133 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003134 getStreamer().EmitCFIRememberState();
3135 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003136}
3137
3138/// ParseDirectiveCFIRestoreState
3139/// ::= .cfi_remember_state
3140bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3141 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003142 getStreamer().EmitCFIRestoreState();
3143 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003144}
3145
Rafael Espindolac5754392011-04-12 15:31:05 +00003146/// ParseDirectiveCFISameValue
3147/// ::= .cfi_same_value register
3148bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3149 SMLoc DirectiveLoc) {
3150 int64_t Register = 0;
3151
3152 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3153 return true;
3154
3155 getStreamer().EmitCFISameValue(Register);
3156
3157 return false;
3158}
3159
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003160/// ParseDirectiveCFIRestore
3161/// ::= .cfi_restore register
3162bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003163 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003164 int64_t Register = 0;
3165 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3166 return true;
3167
3168 getStreamer().EmitCFIRestore(Register);
3169
3170 return false;
3171}
3172
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003173/// ParseDirectiveCFIEscape
3174/// ::= .cfi_escape expression[,...]
3175bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003176 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003177 std::string Values;
3178 int64_t CurrValue;
3179 if (getParser().ParseAbsoluteExpression(CurrValue))
3180 return true;
3181
3182 Values.push_back((uint8_t)CurrValue);
3183
3184 while (getLexer().is(AsmToken::Comma)) {
3185 Lex();
3186
3187 if (getParser().ParseAbsoluteExpression(CurrValue))
3188 return true;
3189
3190 Values.push_back((uint8_t)CurrValue);
3191 }
3192
3193 getStreamer().EmitCFIEscape(Values);
3194 return false;
3195}
3196
Rafael Espindola16d7d432012-01-23 21:51:52 +00003197/// ParseDirectiveCFISignalFrame
3198/// ::= .cfi_signal_frame
3199bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3200 SMLoc DirectiveLoc) {
3201 if (getLexer().isNot(AsmToken::EndOfStatement))
3202 return Error(getLexer().getLoc(),
3203 "unexpected token in '" + Directive + "' directive");
3204
3205 getStreamer().EmitCFISignalFrame();
3206
3207 return false;
3208}
3209
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003210/// ParseDirectiveMacrosOnOff
3211/// ::= .macros_on
3212/// ::= .macros_off
3213bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3214 SMLoc DirectiveLoc) {
3215 if (getLexer().isNot(AsmToken::EndOfStatement))
3216 return Error(getLexer().getLoc(),
3217 "unexpected token in '" + Directive + "' directive");
3218
3219 getParser().MacrosEnabled = Directive == ".macros_on";
3220
3221 return false;
3222}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003223
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003224/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003225/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003226bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3227 SMLoc DirectiveLoc) {
3228 StringRef Name;
3229 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003230 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003231
Rafael Espindola8a403d32012-08-08 14:51:03 +00003232 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003233 // Argument delimiter is initially unknown. It will be set by
3234 // ParseMacroArgument()
3235 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003236 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003237 for (;;) {
3238 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003239 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003240 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003241
3242 if (getLexer().is(AsmToken::Equal)) {
3243 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003244 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003245 return true;
3246 }
3247
Rafael Espindola65366442011-06-05 02:43:45 +00003248 Parameters.push_back(Parameter);
3249
Preston Gurd7b6f2032012-09-19 20:36:12 +00003250 if (getLexer().is(AsmToken::Comma))
3251 Lex();
3252 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003253 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003254 }
3255 }
3256
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003257 // Eat the end of statement.
3258 Lex();
3259
3260 AsmToken EndToken, StartToken = getTok();
3261
3262 // Lex the macro definition.
3263 for (;;) {
3264 // Check whether we have reached the end of the file.
3265 if (getLexer().is(AsmToken::Eof))
3266 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3267
3268 // Otherwise, check whether we have reach the .endmacro.
3269 if (getLexer().is(AsmToken::Identifier) &&
3270 (getTok().getIdentifier() == ".endm" ||
3271 getTok().getIdentifier() == ".endmacro")) {
3272 EndToken = getTok();
3273 Lex();
3274 if (getLexer().isNot(AsmToken::EndOfStatement))
3275 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3276 "' directive");
3277 break;
3278 }
3279
3280 // Otherwise, scan til the end of the statement.
3281 getParser().EatToEndOfStatement();
3282 }
3283
3284 if (getParser().MacroMap.lookup(Name)) {
3285 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3286 }
3287
3288 const char *BodyStart = StartToken.getLoc().getPointer();
3289 const char *BodyEnd = EndToken.getLoc().getPointer();
3290 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003291 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003292 return false;
3293}
3294
3295/// ParseDirectiveEndMacro
3296/// ::= .endm
3297/// ::= .endmacro
3298bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003299 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003300 if (getLexer().isNot(AsmToken::EndOfStatement))
3301 return TokError("unexpected token in '" + Directive + "' directive");
3302
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003303 // If we are inside a macro instantiation, terminate the current
3304 // instantiation.
3305 if (!getParser().ActiveMacros.empty()) {
3306 getParser().HandleMacroExit();
3307 return false;
3308 }
3309
3310 // Otherwise, this .endmacro is a stray entry in the file; well formed
3311 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003312 return TokError("unexpected '" + Directive + "' in file, "
3313 "no current macro definition");
3314}
3315
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003316/// ParseDirectivePurgeMacro
3317/// ::= .purgem
3318bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3319 SMLoc DirectiveLoc) {
3320 StringRef Name;
3321 if (getParser().ParseIdentifier(Name))
3322 return TokError("expected identifier in '.purgem' directive");
3323
3324 if (getLexer().isNot(AsmToken::EndOfStatement))
3325 return TokError("unexpected token in '.purgem' directive");
3326
3327 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3328 if (I == getParser().MacroMap.end())
3329 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3330
3331 // Undefine the macro.
3332 delete I->getValue();
3333 getParser().MacroMap.erase(I);
3334 return false;
3335}
3336
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003337bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003338 getParser().CheckForValidSection();
3339
3340 const MCExpr *Value;
3341
3342 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003343 return true;
3344
3345 if (getLexer().isNot(AsmToken::EndOfStatement))
3346 return TokError("unexpected token in directive");
3347
3348 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003349 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003350 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003351 getStreamer().EmitULEB128Value(Value);
3352
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003353 return false;
3354}
3355
Rafael Espindola761cb062012-06-03 23:57:14 +00003356Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003357 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003358
Rafael Espindola761cb062012-06-03 23:57:14 +00003359 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003360 for (;;) {
3361 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003362 if (getLexer().is(AsmToken::Eof)) {
3363 Error(DirectiveLoc, "no matching '.endr' in definition");
3364 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003365 }
3366
Rafael Espindola761cb062012-06-03 23:57:14 +00003367 if (Lexer.is(AsmToken::Identifier) &&
3368 (getTok().getIdentifier() == ".rept")) {
3369 ++NestLevel;
3370 }
3371
3372 // Otherwise, check whether we have reached the .endr.
3373 if (Lexer.is(AsmToken::Identifier) &&
3374 getTok().getIdentifier() == ".endr") {
3375 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003376 EndToken = getTok();
3377 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003378 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3379 TokError("unexpected token in '.endr' directive");
3380 return 0;
3381 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003382 break;
3383 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003384 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003385 }
3386
Rafael Espindola761cb062012-06-03 23:57:14 +00003387 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003388 EatToEndOfStatement();
3389 }
3390
3391 const char *BodyStart = StartToken.getLoc().getPointer();
3392 const char *BodyEnd = EndToken.getLoc().getPointer();
3393 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3394
Rafael Espindola761cb062012-06-03 23:57:14 +00003395 // We Are Anonymous.
3396 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003397 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003398 return new Macro(Name, Body, Parameters);
3399}
3400
3401void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3402 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003403 OS << ".endr\n";
3404
3405 MemoryBuffer *Instantiation =
3406 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3407
Rafael Espindola761cb062012-06-03 23:57:14 +00003408 // Create the macro instantiation object and add to the current macro
3409 // instantiation stack.
3410 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3411 getTok().getLoc(),
3412 Instantiation);
3413 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003414
Rafael Espindola761cb062012-06-03 23:57:14 +00003415 // Jump to the macro instantiation and prime the lexer.
3416 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3417 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3418 Lex();
3419}
3420
3421bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3422 int64_t Count;
3423 if (ParseAbsoluteExpression(Count))
3424 return TokError("unexpected token in '.rept' directive");
3425
3426 if (Count < 0)
3427 return TokError("Count is negative");
3428
3429 if (Lexer.isNot(AsmToken::EndOfStatement))
3430 return TokError("unexpected token in '.rept' directive");
3431
3432 // Eat the end of statement.
3433 Lex();
3434
3435 // Lex the rept definition.
3436 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3437 if (!M)
3438 return true;
3439
3440 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3441 // to hold the macro body with substitutions.
3442 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003443 MacroParameters Parameters;
3444 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003445 raw_svector_ostream OS(Buf);
3446 while (Count--) {
3447 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3448 return true;
3449 }
3450 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003451
3452 return false;
3453}
3454
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003455/// ParseDirectiveIrp
3456/// ::= .irp symbol,values
3457bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003458 MacroParameters Parameters;
3459 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003460
Preston Gurd6c9176a2012-09-19 20:29:04 +00003461 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003462 return TokError("expected identifier in '.irp' directive");
3463
3464 Parameters.push_back(Parameter);
3465
3466 if (Lexer.isNot(AsmToken::Comma))
3467 return TokError("expected comma in '.irp' directive");
3468
3469 Lex();
3470
Rafael Espindola8a403d32012-08-08 14:51:03 +00003471 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003472 if (ParseMacroArguments(0, A))
3473 return true;
3474
3475 // Eat the end of statement.
3476 Lex();
3477
3478 // Lex the irp definition.
3479 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3480 if (!M)
3481 return true;
3482
3483 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3484 // to hold the macro body with substitutions.
3485 SmallString<256> Buf;
3486 raw_svector_ostream OS(Buf);
3487
Rafael Espindola7996d042012-08-21 16:06:48 +00003488 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3489 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003490 Args.push_back(*i);
3491
3492 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3493 return true;
3494 }
3495
3496 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3497
3498 return false;
3499}
3500
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003501/// ParseDirectiveIrpc
3502/// ::= .irpc symbol,values
3503bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003504 MacroParameters Parameters;
3505 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003506
Preston Gurd6c9176a2012-09-19 20:29:04 +00003507 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003508 return TokError("expected identifier in '.irpc' directive");
3509
3510 Parameters.push_back(Parameter);
3511
3512 if (Lexer.isNot(AsmToken::Comma))
3513 return TokError("expected comma in '.irpc' directive");
3514
3515 Lex();
3516
Rafael Espindola8a403d32012-08-08 14:51:03 +00003517 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003518 if (ParseMacroArguments(0, A))
3519 return true;
3520
3521 if (A.size() != 1 || A.front().size() != 1)
3522 return TokError("unexpected token in '.irpc' directive");
3523
3524 // Eat the end of statement.
3525 Lex();
3526
3527 // Lex the irpc definition.
3528 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3529 if (!M)
3530 return true;
3531
3532 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3533 // to hold the macro body with substitutions.
3534 SmallString<256> Buf;
3535 raw_svector_ostream OS(Buf);
3536
3537 StringRef Values = A.front().front().getString();
3538 std::size_t I, End = Values.size();
3539 for (I = 0; I < End; ++I) {
3540 MacroArgument Arg;
3541 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3542
Rafael Espindola8a403d32012-08-08 14:51:03 +00003543 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003544 Args.push_back(Arg);
3545
3546 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3547 return true;
3548 }
3549
3550 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3551
3552 return false;
3553}
3554
Rafael Espindola761cb062012-06-03 23:57:14 +00003555bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3556 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003557 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003558
3559 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003560 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003561 assert(getLexer().is(AsmToken::EndOfStatement));
3562
Rafael Espindola761cb062012-06-03 23:57:14 +00003563 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003564 return false;
3565}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003566
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003567/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003568MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003569 MCContext &C, MCStreamer &Out,
3570 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003571 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003572}