blob: ab5ddaf4ac005b311100234e31a561bc605071c4 [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"
Matt Fleming924c5e52010-05-21 11:36:59 +000017#include "llvm/ADT/StringSwitch.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000021#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000022#include "llvm/MC/MCExpr.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000023#include "llvm/MC/MCParser/AsmCond.h"
24#include "llvm/MC/MCParser/AsmLexer.h"
25#include "llvm/MC/MCParser/MCAsmParser.h"
26#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000027#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000028#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000029#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000030#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000031#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000032#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000033#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000034#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000035#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000036#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000037#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000038#include <cctype>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000039#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000040using namespace llvm;
41
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000042static cl::opt<bool>
43FatalAssemblerWarnings("fatal-assembler-warnings",
44 cl::desc("Consider warnings as error"));
45
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000046namespace {
47
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000048/// \brief Helper class for tracking macro definitions.
49struct Macro {
50 StringRef Name;
51 StringRef Body;
Rafael Espindola65366442011-06-05 02:43:45 +000052 std::vector<StringRef> Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000053
54public:
Rafael Espindola65366442011-06-05 02:43:45 +000055 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
56 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000057};
58
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000059/// \brief Helper class for storing information about an active macro
60/// instantiation.
61struct MacroInstantiation {
62 /// The macro being instantiated.
63 const Macro *TheMacro;
64
65 /// The macro instantiation with substitutions.
66 MemoryBuffer *Instantiation;
67
68 /// The location of the instantiation.
69 SMLoc InstantiationLoc;
70
71 /// The location where parsing should resume upon instantiation completion.
72 SMLoc ExitLoc;
73
74public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000075 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000076 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000077};
78
Daniel Dunbaraef87e32010-07-18 18:31:38 +000079/// \brief The concrete assembly parser instance.
80class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +000081 friend class GenericAsmParser;
82
Daniel Dunbaraef87e32010-07-18 18:31:38 +000083 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
84 void operator=(const AsmParser &); // DO NOT IMPLEMENT
85private:
86 AsmLexer Lexer;
87 MCContext &Ctx;
88 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +000089 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000090 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +000091 SourceMgr::DiagHandlerTy SavedDiagHandler;
92 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000093 MCAsmParserExtension *GenericParser;
94 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +000095
Daniel Dunbaraef87e32010-07-18 18:31:38 +000096 /// This is the current buffer index we're lexing from as managed by the
97 /// SourceMgr object.
98 int CurBuffer;
99
100 AsmCond TheCondState;
101 std::vector<AsmCond> TheCondStack;
102
103 /// DirectiveMap - This is a table handlers for directives. Each handler is
104 /// invoked after the directive identifier is read and is responsible for
105 /// parsing and validating the rest of the directive. The handler is passed
106 /// in the directive name and the location of the directive keyword.
107 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000108
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000109 /// MacroMap - Map of currently defined macros.
110 StringMap<Macro*> MacroMap;
111
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000112 /// ActiveMacros - Stack of active macro instantiations.
113 std::vector<MacroInstantiation*> ActiveMacros;
114
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000115 /// Boolean tracking whether macro substitution is enabled.
116 unsigned MacrosEnabled : 1;
117
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000118 /// Flag tracking whether any errors have been encountered.
119 unsigned HadError : 1;
120
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000121 /// The values from the last parsed cpp hash file line comment if any.
122 StringRef CppHashFilename;
123 int64_t CppHashLineNumber;
124 SMLoc CppHashLoc;
125
Devang Patel0db58bf2012-01-31 18:14:05 +0000126 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
127 unsigned AssemblerDialect;
128
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000129public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000130 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000131 const MCAsmInfo &MAI);
132 ~AsmParser();
133
134 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
135
136 void AddDirectiveHandler(MCAsmParserExtension *Object,
137 StringRef Directive,
138 DirectiveHandler Handler) {
139 DirectiveMap[Directive] = std::make_pair(Object, Handler);
140 }
141
142public:
143 /// @name MCAsmParser Interface
144 /// {
145
146 virtual SourceMgr &getSourceManager() { return SrcMgr; }
147 virtual MCAsmLexer &getLexer() { return Lexer; }
148 virtual MCContext &getContext() { return Ctx; }
149 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000150 virtual unsigned getAssemblerDialect() {
151 if (AssemblerDialect == ~0U)
152 return MAI.getAssemblerDialect();
153 else
154 return AssemblerDialect;
155 }
156 virtual void setAssemblerDialect(unsigned i) {
157 AssemblerDialect = i;
158 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000159
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000160 virtual bool Warning(SMLoc L, const Twine &Msg,
161 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
162 virtual bool Error(SMLoc L, const Twine &Msg,
163 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000164
165 const AsmToken &Lex();
166
167 bool ParseExpression(const MCExpr *&Res);
168 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
169 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
170 virtual bool ParseAbsoluteExpression(int64_t &Res);
171
172 /// }
173
174private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000175 void CheckForValidSection();
176
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000177 bool ParseStatement();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000178 void EatToEndOfLine();
179 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000180
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000181 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola65366442011-06-05 02:43:45 +0000182 bool expandMacro(SmallString<256> &Buf, StringRef Body,
183 const std::vector<StringRef> &Parameters,
184 const std::vector<std::vector<AsmToken> > &A,
185 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000186 void HandleMacroExit();
187
188 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000189 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000190 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
191 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000192 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000193 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000194
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000195 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
196 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000197 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
198 /// This returns true on failure.
199 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000200
201 /// \brief Reset the current lexer position to that given by \arg Loc. The
202 /// current token is not set; clients should ensure Lex() is called
203 /// subsequently.
204 void JumpToLoc(SMLoc Loc);
205
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000206 void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000207
208 /// \brief Parse up to the end of statement and a return the contents from the
209 /// current token until the end of the statement; the current token on exit
210 /// will be either the EndOfStatement or EOF.
211 StringRef ParseStringToEndOfStatement();
212
Nico Weber4c4c7322011-01-28 03:04:41 +0000213 bool ParseAssignment(StringRef Name, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000214
215 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
216 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
217 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000218 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000219
220 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
221 /// and set \arg Res to the identifier contents.
222 bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000223
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000224 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000225
226 // ".ascii", ".asciiz", ".string"
227 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000228 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000229 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000230 bool ParseDirectiveFill(); // ".fill"
231 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000232 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000233 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000234 bool ParseDirectiveOrg(); // ".org"
235 // ".align{,32}", ".p2align{,w,l}"
236 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
237
238 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
239 /// accepts a single symbol (which should be a label or an external).
240 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000241
242 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
243
244 bool ParseDirectiveAbort(); // ".abort"
245 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000246 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000247
248 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000249 // ".ifdef" or ".ifndef", depending on expect_defined
250 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000251 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
252 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
253 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
254
255 /// ParseEscapedString - Parse the current token as a string which may include
256 /// escaped characters and return the string contents.
257 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000258
259 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
260 MCSymbolRefExpr::VariantKind Variant);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000261};
262
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000263/// \brief Generic implementations of directive handling, etc. which is shared
264/// (or the default, at least) for all assembler parser.
265class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000266 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
267 void AddDirectiveHandler(StringRef Directive) {
268 getParser().AddDirectiveHandler(this, Directive,
269 HandleDirective<GenericAsmParser, Handler>);
270 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000271public:
272 GenericAsmParser() {}
273
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000274 AsmParser &getParser() {
275 return (AsmParser&) this->MCAsmParserExtension::getParser();
276 }
277
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000278 virtual void Initialize(MCAsmParser &Parser) {
279 // Call the base implementation.
280 this->MCAsmParserExtension::Initialize(Parser);
281
282 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000283 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
285 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000287
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000288 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000289 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
290 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000291 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
292 ".cfi_startproc");
293 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
294 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000295 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
296 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000297 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
298 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000299 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
300 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000301 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
302 ".cfi_def_cfa_register");
303 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
304 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000305 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
306 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000307 AddDirectiveHandler<
308 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
309 AddDirectiveHandler<
310 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000311 AddDirectiveHandler<
312 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
313 AddDirectiveHandler<
314 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000315 AddDirectiveHandler<
316 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000317 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000318 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
319 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000320 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000321 AddDirectiveHandler<
322 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000323
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000324 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000325 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
326 ".macros_on");
327 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
328 ".macros_off");
329 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
330 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
331 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000332
333 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
334 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000335 }
336
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000337 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
338
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000339 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
340 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
341 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000342 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000343 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000344 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
345 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000346 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000347 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000348 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000349 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
350 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000351 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000352 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000353 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
354 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000355 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000356 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000357 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000358 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000359
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000360 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000361 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
362 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000363
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000364 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000365};
366
367}
368
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000369namespace llvm {
370
371extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000372extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000373extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000374
375}
376
Chris Lattneraaec2052010-01-19 19:46:13 +0000377enum { DEFAULT_ADDRSPACE = 0 };
378
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000379AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000380 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000381 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000382 GenericParser(new GenericAsmParser), PlatformParser(0),
Devang Patel0db58bf2012-01-31 18:14:05 +0000383 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
384 AssemblerDialect(~0U) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000385 // Save the old handler.
386 SavedDiagHandler = SrcMgr.getDiagHandler();
387 SavedDiagContext = SrcMgr.getDiagContext();
388 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000389 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000390 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000391
392 // Initialize the generic parser.
393 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000394
395 // Initialize the platform / file format parser.
396 //
397 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
398 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000399 if (_MAI.hasMicrosoftFastStdCallMangling()) {
400 PlatformParser = createCOFFAsmParser();
401 PlatformParser->Initialize(*this);
402 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000403 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000404 PlatformParser->Initialize(*this);
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000405 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000406 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000407 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000408 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000409}
410
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000411AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000412 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
413
414 // Destroy any macros.
415 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
416 ie = MacroMap.end(); it != ie; ++it)
417 delete it->getValue();
418
Daniel Dunbare4749702010-07-12 18:12:02 +0000419 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000420 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000421}
422
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000423void AsmParser::PrintMacroInstantiations() {
424 // Print the active macro instantiation stack.
425 for (std::vector<MacroInstantiation*>::const_reverse_iterator
426 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000427 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
428 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000429}
430
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000431bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000432 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000433 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000434 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000435 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000436 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000437}
438
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000439bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000440 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000441 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000442 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000443 return true;
444}
445
Sean Callananfd0b0282010-01-21 00:19:58 +0000446bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000447 std::string IncludedFile;
448 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000449 if (NewBuf == -1)
450 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000451
Sean Callananfd0b0282010-01-21 00:19:58 +0000452 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000453
Sean Callananfd0b0282010-01-21 00:19:58 +0000454 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000455
Sean Callananfd0b0282010-01-21 00:19:58 +0000456 return false;
457}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000458
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000459/// Process the specified .incbin file by seaching for it in the include paths
460/// then just emiting the byte contents of the file to the streamer. This
461/// returns true on failure.
462bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
463 std::string IncludedFile;
464 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
465 if (NewBuf == -1)
466 return true;
467
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000468 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000469 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
470 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000471 return false;
472}
473
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000474void AsmParser::JumpToLoc(SMLoc Loc) {
475 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
476 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
477}
478
Sean Callananfd0b0282010-01-21 00:19:58 +0000479const AsmToken &AsmParser::Lex() {
480 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000481
Sean Callananfd0b0282010-01-21 00:19:58 +0000482 if (tok->is(AsmToken::Eof)) {
483 // If this is the end of an included file, pop the parent file off the
484 // include stack.
485 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
486 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000487 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000488 tok = &Lexer.Lex();
489 }
490 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000491
Sean Callananfd0b0282010-01-21 00:19:58 +0000492 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000493 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000494
Sean Callananfd0b0282010-01-21 00:19:58 +0000495 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000496}
497
Chris Lattner79180e22010-04-05 23:15:42 +0000498bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000499 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000500 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000501 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000502
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000503 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000504 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000505
506 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000507 AsmCond StartingCondState = TheCondState;
508
Kevin Enderby613b7572011-11-01 22:27:22 +0000509 // If we are generating dwarf for assembly source files save the initial text
510 // section and generate a .file directive.
511 if (getContext().getGenDwarfForAssembly()) {
512 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000513 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
514 getStreamer().EmitLabel(SectionStartSym);
515 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000516 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
517 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
518 }
519
Chris Lattnerb717fb02009-07-02 21:53:43 +0000520 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000521 while (Lexer.isNot(AsmToken::Eof)) {
Chris Lattnerb717fb02009-07-02 21:53:43 +0000522 if (!ParseStatement()) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000523
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000524 // We had an error, validate that one was emitted and recover by skipping to
525 // the next line.
526 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000527 EatToEndOfStatement();
528 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000529
530 if (TheCondState.TheCond != StartingCondState.TheCond ||
531 TheCondState.Ignore != StartingCondState.Ignore)
532 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000533
534 // Check to see there are no empty DwarfFile slots.
535 const std::vector<MCDwarfFile *> &MCDwarfFiles =
536 getContext().getMCDwarfFiles();
537 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000538 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000539 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000540 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000541
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000542 // Check to see that all assembler local symbols were actually defined.
543 // Targets that don't do subsections via symbols may not want this, though,
544 // so conservatively exclude them. Only do this if we're finalizing, though,
545 // as otherwise we won't necessarilly have seen everything yet.
546 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
547 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
548 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
549 e = Symbols.end();
550 i != e; ++i) {
551 MCSymbol *Sym = i->getValue();
552 // Variable symbols may not be marked as defined, so check those
553 // explicitly. If we know it's a variable, we have a definition for
554 // the purposes of this check.
555 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
556 // FIXME: We would really like to refer back to where the symbol was
557 // first referenced for a source location. We need to add something
558 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000559 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
560 "assembler local symbol '" + Sym->getName() +
561 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000562 }
563 }
564
565
Chris Lattner79180e22010-04-05 23:15:42 +0000566 // Finalize the output stream if there are no errors and if the client wants
567 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000568 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000569 Out.Finish();
570
Chris Lattnerb717fb02009-07-02 21:53:43 +0000571 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000572}
573
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000574void AsmParser::CheckForValidSection() {
575 if (!getStreamer().getCurrentSection()) {
576 TokError("expected section directive before assembly directive");
577 Out.SwitchSection(Ctx.getMachOSection(
578 "__TEXT", "__text",
579 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
580 0, SectionKind::getText()));
581 }
582}
583
Chris Lattner2cf5f142009-06-22 01:29:09 +0000584/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
585void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000586 while (Lexer.isNot(AsmToken::EndOfStatement) &&
587 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000588 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000589
Chris Lattner2cf5f142009-06-22 01:29:09 +0000590 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000591 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000592 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000593}
594
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000595StringRef AsmParser::ParseStringToEndOfStatement() {
596 const char *Start = getTok().getLoc().getPointer();
597
598 while (Lexer.isNot(AsmToken::EndOfStatement) &&
599 Lexer.isNot(AsmToken::Eof))
600 Lex();
601
602 const char *End = getTok().getLoc().getPointer();
603 return StringRef(Start, End - Start);
604}
Chris Lattnerc4193832009-06-22 05:51:26 +0000605
Chris Lattner74ec1a32009-06-22 06:32:03 +0000606/// ParseParenExpr - Parse a paren expression and return it.
607/// NOTE: This assumes the leading '(' has already been consumed.
608///
609/// parenexpr ::= expr)
610///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000611bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000612 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000613 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000614 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000615 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000616 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000617 return false;
618}
Chris Lattnerc4193832009-06-22 05:51:26 +0000619
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000620/// ParseBracketExpr - Parse a bracket expression and return it.
621/// NOTE: This assumes the leading '[' has already been consumed.
622///
623/// bracketexpr ::= expr]
624///
625bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
626 if (ParseExpression(Res)) return true;
627 if (Lexer.isNot(AsmToken::RBrac))
628 return TokError("expected ']' in brackets expression");
629 EndLoc = Lexer.getLoc();
630 Lex();
631 return false;
632}
633
Chris Lattner74ec1a32009-06-22 06:32:03 +0000634/// ParsePrimaryExpr - Parse a primary expression and return it.
635/// primaryexpr ::= (parenexpr
636/// primaryexpr ::= symbol
637/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000638/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000639/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000640bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000641 switch (Lexer.getKind()) {
642 default:
643 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000644 // If we have an error assume that we've already handled it.
645 case AsmToken::Error:
646 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000647 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000648 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000649 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000650 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000651 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000652 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000653 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000654 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000655 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000656 EndLoc = Lexer.getLoc();
657
658 StringRef Identifier;
659 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000660 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000661
Daniel Dunbarfffff912009-10-16 01:34:54 +0000662 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000663 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000664 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000665
666 // Lookup the symbol variant if used.
667 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000668 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000669 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000670 if (Variant == MCSymbolRefExpr::VK_Invalid) {
671 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000672 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000673 }
674 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000675
Daniel Dunbarfffff912009-10-16 01:34:54 +0000676 // If this is an absolute variable reference, substitute it now to preserve
677 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000678 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000679 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000680 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000681
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000682 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000683 return false;
684 }
685
686 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000687 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000688 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000689 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000690 case AsmToken::Integer: {
691 SMLoc Loc = getTok().getLoc();
692 int64_t IntVal = getTok().getIntVal();
693 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000694 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000695 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000696 // Look for 'b' or 'f' following an Integer as a directional label
697 if (Lexer.getKind() == AsmToken::Identifier) {
698 StringRef IDVal = getTok().getString();
699 if (IDVal == "f" || IDVal == "b"){
700 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
701 IDVal == "f" ? 1 : 0);
702 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
703 getContext());
704 if(IDVal == "b" && Sym->isUndefined())
705 return Error(Loc, "invalid reference to undefined symbol");
706 EndLoc = Lexer.getLoc();
707 Lex(); // Eat identifier.
708 }
709 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000710 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000711 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000712 case AsmToken::Real: {
713 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000714 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000715 Res = MCConstantExpr::Create(IntVal, getContext());
716 Lex(); // Eat token.
717 return false;
718 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000719 case AsmToken::Dot: {
720 // This is a '.' reference, which references the current PC. Emit a
721 // temporary label to the streamer and refer to it.
722 MCSymbol *Sym = Ctx.CreateTempSymbol();
723 Out.EmitLabel(Sym);
724 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
725 EndLoc = Lexer.getLoc();
726 Lex(); // Eat identifier.
727 return false;
728 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000729 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000730 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000731 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000732 case AsmToken::LBrac:
733 if (!PlatformParser->HasBracketExpressions())
734 return TokError("brackets expression not supported on this target");
735 Lex(); // Eat the '['.
736 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000737 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000738 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000739 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000740 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000741 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000742 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000743 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000744 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000745 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000746 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000747 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000748 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000749 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000750 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000751 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000752 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000753 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000754 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000755 }
756}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000757
Chris Lattnerb4307b32010-01-15 19:28:38 +0000758bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000759 SMLoc EndLoc;
760 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000761}
762
Daniel Dunbarcceba832010-09-17 02:47:07 +0000763const MCExpr *
764AsmParser::ApplyModifierToExpr(const MCExpr *E,
765 MCSymbolRefExpr::VariantKind Variant) {
766 // Recurse over the given expression, rebuilding it to apply the given variant
767 // if there is exactly one symbol.
768 switch (E->getKind()) {
769 case MCExpr::Target:
770 case MCExpr::Constant:
771 return 0;
772
773 case MCExpr::SymbolRef: {
774 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
775
776 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
777 TokError("invalid variant on expression '" +
778 getTok().getIdentifier() + "' (already modified)");
779 return E;
780 }
781
782 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
783 }
784
785 case MCExpr::Unary: {
786 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
787 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
788 if (!Sub)
789 return 0;
790 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
791 }
792
793 case MCExpr::Binary: {
794 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
795 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
796 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
797
798 if (!LHS && !RHS)
799 return 0;
800
801 if (!LHS) LHS = BE->getLHS();
802 if (!RHS) RHS = BE->getRHS();
803
804 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
805 }
806 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000807
Craig Topper85814382012-02-07 05:05:23 +0000808 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000809}
810
Chris Lattner74ec1a32009-06-22 06:32:03 +0000811/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000812///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000813/// expr ::= expr &&,|| expr -> lowest.
814/// expr ::= expr |,^,&,! expr
815/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
816/// expr ::= expr <<,>> expr
817/// expr ::= expr +,- expr
818/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000819/// expr ::= primaryexpr
820///
Chris Lattner54482b42010-01-15 19:39:23 +0000821bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000822 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000823 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000824 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
825 return true;
826
Daniel Dunbarcceba832010-09-17 02:47:07 +0000827 // As a special case, we support 'a op b @ modifier' by rewriting the
828 // expression to include the modifier. This is inefficient, but in general we
829 // expect users to use 'a@modifier op b'.
830 if (Lexer.getKind() == AsmToken::At) {
831 Lex();
832
833 if (Lexer.isNot(AsmToken::Identifier))
834 return TokError("unexpected symbol modifier following '@'");
835
836 MCSymbolRefExpr::VariantKind Variant =
837 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
838 if (Variant == MCSymbolRefExpr::VK_Invalid)
839 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
840
841 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
842 if (!ModifiedRes) {
843 return TokError("invalid modifier '" + getTok().getIdentifier() +
844 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000845 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000846
Daniel Dunbarcceba832010-09-17 02:47:07 +0000847 Res = ModifiedRes;
848 Lex();
849 }
850
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000851 // Try to constant fold it up front, if possible.
852 int64_t Value;
853 if (Res->EvaluateAsAbsolute(Value))
854 Res = MCConstantExpr::Create(Value, getContext());
855
856 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000857}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000858
Chris Lattnerb4307b32010-01-15 19:28:38 +0000859bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000860 Res = 0;
861 return ParseParenExpr(Res, EndLoc) ||
862 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000863}
864
Daniel Dunbar475839e2009-06-29 20:37:27 +0000865bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000866 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000867
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000868 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000869 if (ParseExpression(Expr))
870 return true;
871
Daniel Dunbare00b0112009-10-16 01:57:52 +0000872 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000873 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000874
875 return false;
876}
877
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000878static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000879 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000880 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000881 default:
882 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000883
Jim Grosbachfbe16812011-08-20 16:24:13 +0000884 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000885 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000886 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000887 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000888 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000889 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000890 return 1;
891
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000892
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000893 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000894 //
895 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000896 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000897 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000898 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000899 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000900 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000901 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000902 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000903 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000904 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000905
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000906 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000907 case AsmToken::EqualEqual:
908 Kind = MCBinaryExpr::EQ;
909 return 3;
910 case AsmToken::ExclaimEqual:
911 case AsmToken::LessGreater:
912 Kind = MCBinaryExpr::NE;
913 return 3;
914 case AsmToken::Less:
915 Kind = MCBinaryExpr::LT;
916 return 3;
917 case AsmToken::LessEqual:
918 Kind = MCBinaryExpr::LTE;
919 return 3;
920 case AsmToken::Greater:
921 Kind = MCBinaryExpr::GT;
922 return 3;
923 case AsmToken::GreaterEqual:
924 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000925 return 3;
926
Jim Grosbachfbe16812011-08-20 16:24:13 +0000927 // Intermediate Precedence: <<, >>
928 case AsmToken::LessLess:
929 Kind = MCBinaryExpr::Shl;
930 return 4;
931 case AsmToken::GreaterGreater:
932 Kind = MCBinaryExpr::Shr;
933 return 4;
934
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000935 // High Intermediate Precedence: +, -
936 case AsmToken::Plus:
937 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000938 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000939 case AsmToken::Minus:
940 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000941 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000942
Jim Grosbachfbe16812011-08-20 16:24:13 +0000943 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +0000944 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000945 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000946 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000947 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000948 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000949 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000950 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000951 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000952 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000953 }
954}
955
956
957/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
958/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000959bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
960 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000961 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000962 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000963 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000964
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000965 // If the next token is lower precedence than we are allowed to eat, return
966 // successfully with what we ate already.
967 if (TokPrec < Precedence)
968 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000969
Sean Callanan79ed1a82010-01-19 20:22:31 +0000970 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000971
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000972 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000973 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +0000974 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000975
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000976 // If BinOp binds less tightly with RHS than the operator after RHS, let
977 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000978 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000979 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000980 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +0000981 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000982 }
983
Daniel Dunbar475839e2009-06-29 20:37:27 +0000984 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000985 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000986 }
987}
988
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000989
990
991
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000992/// ParseStatement:
993/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +0000994/// ::= Label* Directive ...Operands... EndOfStatement
995/// ::= Label* Identifier OperandList* EndOfStatement
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000996bool AsmParser::ParseStatement() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000997 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +0000998 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000999 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001000 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001001 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001002
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001003 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001004 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001005 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001006 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001007 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001008 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001009 if (Lexer.is(AsmToken::Hash))
1010 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001011
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001012 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001013 if (Lexer.is(AsmToken::Integer)) {
1014 LocalLabelVal = getTok().getIntVal();
1015 if (LocalLabelVal < 0) {
1016 if (!TheCondState.Ignore)
1017 return TokError("unexpected token at start of statement");
1018 IDVal = "";
1019 }
1020 else {
1021 IDVal = getTok().getString();
1022 Lex(); // Consume the integer token to be used as an identifier token.
1023 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001024 if (!TheCondState.Ignore)
1025 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001026 }
1027 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001028
1029 } else if (Lexer.is(AsmToken::Dot)) {
1030 // Treat '.' as a valid identifier in this context.
1031 Lex();
1032 IDVal = ".";
1033
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001034 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001035 if (!TheCondState.Ignore)
1036 return TokError("unexpected token at start of statement");
1037 IDVal = "";
1038 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001039
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001040
Chris Lattner7834fac2010-04-17 18:14:27 +00001041 // Handle conditional assembly here before checking for skipping. We
1042 // have to do this so that .endif isn't skipped in a ".if 0" block for
1043 // example.
1044 if (IDVal == ".if")
1045 return ParseDirectiveIf(IDLoc);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001046 if (IDVal == ".ifdef")
1047 return ParseDirectiveIfdef(IDLoc, true);
1048 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1049 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001050 if (IDVal == ".elseif")
1051 return ParseDirectiveElseIf(IDLoc);
1052 if (IDVal == ".else")
1053 return ParseDirectiveElse(IDLoc);
1054 if (IDVal == ".endif")
1055 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001056
Chris Lattner7834fac2010-04-17 18:14:27 +00001057 // If we are in a ".if 0" block, ignore this statement.
1058 if (TheCondState.Ignore) {
1059 EatToEndOfStatement();
1060 return false;
1061 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001062
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001063 // FIXME: Recurse on local labels?
1064
1065 // See what kind of statement we have.
1066 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001067 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001068 CheckForValidSection();
1069
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001070 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001071 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001072
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001073 // Diagnose attempt to use '.' as a label.
1074 if (IDVal == ".")
1075 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1076
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001077 // Diagnose attempt to use a variable as a label.
1078 //
1079 // FIXME: Diagnostics. Note the location of the definition as a label.
1080 // FIXME: This doesn't diagnose assignment to a symbol which has been
1081 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001082 MCSymbol *Sym;
1083 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001084 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001085 else
1086 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001087 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001088 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001089
Daniel Dunbar959fd882009-08-26 22:13:22 +00001090 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001091 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001092
Kevin Enderby94c2e852011-12-09 18:09:40 +00001093 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001094 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001095 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001096 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1097 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001098
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001099 // Consume any end of statement token, if present, to avoid spurious
1100 // AddBlankLine calls().
1101 if (Lexer.is(AsmToken::EndOfStatement)) {
1102 Lex();
1103 if (Lexer.is(AsmToken::Eof))
1104 return false;
1105 }
1106
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001107 return ParseStatement();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001108 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001109
Daniel Dunbar3f872332009-07-28 16:08:33 +00001110 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001111 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001112 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001113
Nico Weber4c4c7322011-01-28 03:04:41 +00001114 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001115
1116 default: // Normal instruction or directive.
1117 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001118 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001119
1120 // If macros are enabled, check to see if this is a macro instantiation.
1121 if (MacrosEnabled)
1122 if (const Macro *M = MacroMap.lookup(IDVal))
1123 return HandleMacroEntry(IDVal, IDLoc, M);
1124
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001125 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001126 if (IDVal[0] == '.' && IDVal != ".") {
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001127 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001128 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001129 return ParseDirectiveSet(IDVal, true);
1130 if (IDVal == ".equiv")
1131 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001132
Daniel Dunbara0d14262009-06-24 23:30:00 +00001133 // Data directives
1134
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001135 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001136 return ParseDirectiveAscii(IDVal, false);
1137 if (IDVal == ".asciz" || IDVal == ".string")
1138 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001139
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001140 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001141 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001142 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001143 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001144 if (IDVal == ".value")
1145 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001146 if (IDVal == ".2byte")
1147 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001148 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001149 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001150 if (IDVal == ".int")
1151 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001152 if (IDVal == ".4byte")
1153 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001154 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001155 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001156 if (IDVal == ".8byte")
1157 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001158 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001159 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1160 if (IDVal == ".double")
1161 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001162
Eli Friedman5d68ec22010-07-19 04:17:25 +00001163 if (IDVal == ".align") {
1164 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1165 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1166 }
1167 if (IDVal == ".align32") {
1168 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1169 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1170 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001171 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001172 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001173 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001174 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001175 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001176 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001177 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001178 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001179 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001180 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001181 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001182 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1183
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001184 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001185 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001186
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001187 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001188 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001189 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001190 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001191 if (IDVal == ".zero")
1192 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001193
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001194 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001195
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001196 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001197 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001198 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001199 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001200 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001201 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001202 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001203 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001204 if (IDVal == ".symbol_resolver")
1205 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001206 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001207 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001208 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001209 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001210 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001211 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001212 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001213 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001214 if (IDVal == ".weak_def_can_be_hidden")
1215 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001216
Hans Wennborg5cc64912011-06-18 13:51:54 +00001217 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001218 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001219 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001220 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001221
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001222 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001223 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001224 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001225 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001226 if (IDVal == ".incbin")
1227 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001228
Evan Chengbd27f5a2011-07-27 00:38:12 +00001229 if (IDVal == ".code16")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001230 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001231
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001232 // Look up the handler in the handler table.
1233 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1234 DirectiveMap.lookup(IDVal);
1235 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001236 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001237
Kevin Enderby9c656452009-09-10 20:51:44 +00001238 // Target hook for parsing target specific directives.
1239 if (!getTargetParser().ParseDirective(ID))
1240 return false;
1241
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +00001242 bool retval = Warning(IDLoc, "ignoring directive for now");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001243 EatToEndOfStatement();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +00001244 return retval;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001245 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001246
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001247 CheckForValidSection();
1248
Chris Lattnera7f13542010-05-19 23:34:33 +00001249 // Canonicalize the opcode to lower case.
1250 SmallString<128> Opcode;
1251 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1252 Opcode.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001253
Chris Lattner98986712010-01-14 22:21:20 +00001254 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
Chris Lattnera7f13542010-05-19 23:34:33 +00001255 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001256 ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001257
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001258 // Dump the parsed representation, if requested.
1259 if (getShowParsedOperands()) {
1260 SmallString<256> Str;
1261 raw_svector_ostream OS(Str);
1262 OS << "parsed instruction: [";
1263 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1264 if (i != 0)
1265 OS << ", ";
Jim Grosbachb7f689b2011-07-13 15:34:57 +00001266 ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001267 }
1268 OS << "]";
1269
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001270 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001271 }
1272
Kevin Enderby613b7572011-11-01 22:27:22 +00001273 // If we are generating dwarf for assembly source files and the current
1274 // section is the initial text section then generate a .loc directive for
1275 // the instruction.
1276 if (!HadError && getContext().getGenDwarfForAssembly() &&
1277 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1278 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1279 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1280 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001281 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001282 StringRef());
1283 }
1284
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001285 // If parsing succeeded, match the instruction.
Chris Lattner7036f8b2010-09-29 01:42:58 +00001286 if (!HadError)
1287 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1288 Out);
Chris Lattner98986712010-01-14 22:21:20 +00001289
Chris Lattner98986712010-01-14 22:21:20 +00001290 // Free any parsed operands.
1291 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1292 delete ParsedOperands[i];
1293
Chris Lattnercbf8a982010-09-11 16:18:25 +00001294 // Don't skip the rest of the line, the instruction parser is responsible for
1295 // that.
1296 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001297}
Chris Lattner9a023f72009-06-24 04:43:34 +00001298
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001299/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1300/// since they may not be able to be tokenized to get to the end of line token.
1301void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001302 if (!Lexer.is(AsmToken::EndOfStatement))
1303 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001304 // Eat EOL.
1305 Lex();
1306}
1307
1308/// ParseCppHashLineFilenameComment as this:
1309/// ::= # number "filename"
1310/// or just as a full line comment if it doesn't have a number and a string.
1311bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1312 Lex(); // Eat the hash token.
1313
1314 if (getLexer().isNot(AsmToken::Integer)) {
1315 // Consume the line since in cases it is not a well-formed line directive,
1316 // as if were simply a full line comment.
1317 EatToEndOfLine();
1318 return false;
1319 }
1320
1321 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001322 Lex();
1323
1324 if (getLexer().isNot(AsmToken::String)) {
1325 EatToEndOfLine();
1326 return false;
1327 }
1328
1329 StringRef Filename = getTok().getString();
1330 // Get rid of the enclosing quotes.
1331 Filename = Filename.substr(1, Filename.size()-2);
1332
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001333 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1334 CppHashLoc = L;
1335 CppHashFilename = Filename;
1336 CppHashLineNumber = LineNumber;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001337
1338 // Ignore any trailing characters, they're just comment.
1339 EatToEndOfLine();
1340 return false;
1341}
1342
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001343/// DiagHandler - will use the the last parsed cpp hash line filename comment
1344/// for the Filename and LineNo if any in the diagnostic.
1345void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1346 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1347 raw_ostream &OS = errs();
1348
1349 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1350 const SMLoc &DiagLoc = Diag.getLoc();
1351 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1352 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1353
1354 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1355 // before printing the message.
1356 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001357 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001358 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1359 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1360 }
1361
1362 // If we have not parsed a cpp hash line filename comment or the source
1363 // manager changed or buffer changed (like in a nested include) then just
1364 // print the normal diagnostic using its Filename and LineNo.
1365 if (!Parser->CppHashLineNumber ||
1366 &DiagSrcMgr != &Parser->SrcMgr ||
1367 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001368 if (Parser->SavedDiagHandler)
1369 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1370 else
1371 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001372 return;
1373 }
1374
1375 // Use the CppHashFilename and calculate a line number based on the
1376 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1377 // the diagnostic.
1378 const std::string Filename = Parser->CppHashFilename;
1379
1380 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1381 int CppHashLocLineNo =
1382 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1383 int LineNo = Parser->CppHashLineNumber - 1 +
1384 (DiagLocLineNo - CppHashLocLineNo);
1385
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001386 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1387 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001388 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001389 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001390
Benjamin Kramer04a04262011-10-16 10:48:29 +00001391 if (Parser->SavedDiagHandler)
1392 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1393 else
1394 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001395}
1396
Rafael Espindola65366442011-06-05 02:43:45 +00001397bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1398 const std::vector<StringRef> &Parameters,
1399 const std::vector<std::vector<AsmToken> > &A,
1400 const SMLoc &L) {
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001401 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001402 unsigned NParameters = Parameters.size();
1403 if (NParameters != 0 && NParameters != A.size())
1404 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001405
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001406 while (!Body.empty()) {
1407 // Scan for the next substitution.
1408 std::size_t End = Body.size(), Pos = 0;
1409 for (; Pos != End; ++Pos) {
1410 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001411 if (!NParameters) {
1412 // This macro has no parameters, look for $0, $1, etc.
1413 if (Body[Pos] != '$' || Pos + 1 == End)
1414 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001415
Rafael Espindola65366442011-06-05 02:43:45 +00001416 char Next = Body[Pos + 1];
1417 if (Next == '$' || Next == 'n' || isdigit(Next))
1418 break;
1419 } else {
1420 // This macro has parameters, look for \foo, \bar, etc.
1421 if (Body[Pos] == '\\' && Pos + 1 != End)
1422 break;
1423 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001424 }
1425
1426 // Add the prefix.
1427 OS << Body.slice(0, Pos);
1428
1429 // Check if we reached the end.
1430 if (Pos == End)
1431 break;
1432
Rafael Espindola65366442011-06-05 02:43:45 +00001433 if (!NParameters) {
1434 switch (Body[Pos+1]) {
1435 // $$ => $
1436 case '$':
1437 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001438 break;
1439
Rafael Espindola65366442011-06-05 02:43:45 +00001440 // $n => number of arguments
1441 case 'n':
1442 OS << A.size();
1443 break;
1444
1445 // $[0-9] => argument
1446 default: {
1447 // Missing arguments are ignored.
1448 unsigned Index = Body[Pos+1] - '0';
1449 if (Index >= A.size())
1450 break;
1451
1452 // Otherwise substitute with the token values, with spaces eliminated.
1453 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1454 ie = A[Index].end(); it != ie; ++it)
1455 OS << it->getString();
1456 break;
1457 }
1458 }
1459 Pos += 2;
1460 } else {
1461 unsigned I = Pos + 1;
1462 while (isalnum(Body[I]) && I + 1 != End)
1463 ++I;
1464
1465 const char *Begin = Body.data() + Pos +1;
1466 StringRef Argument(Begin, I - (Pos +1));
1467 unsigned Index = 0;
1468 for (; Index < NParameters; ++Index)
1469 if (Parameters[Index] == Argument)
1470 break;
1471
1472 // FIXME: We should error at the macro definition.
1473 if (Index == NParameters)
1474 return Error(L, "Parameter not found");
1475
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001476 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1477 ie = A[Index].end(); it != ie; ++it)
1478 OS << it->getString();
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001479
Rafael Espindola65366442011-06-05 02:43:45 +00001480 Pos += 1 + Argument.size();
1481 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001482 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001483 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001484 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001485
1486 // We include the .endmacro in the buffer as our queue to exit the macro
1487 // instantiation.
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001488 OS << ".endmacro\n";
Rafael Espindola65366442011-06-05 02:43:45 +00001489 return false;
1490}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001491
Rafael Espindola65366442011-06-05 02:43:45 +00001492MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1493 MemoryBuffer *I)
1494 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1495{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001496}
1497
1498bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1499 const Macro *M) {
1500 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1501 // this, although we should protect against infinite loops.
1502 if (ActiveMacros.size() == 20)
1503 return TokError("macros cannot be nested more than 20 levels deep");
1504
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001505 // Parse the macro instantiation arguments.
1506 std::vector<std::vector<AsmToken> > MacroArguments;
1507 MacroArguments.push_back(std::vector<AsmToken>());
1508 unsigned ParenLevel = 0;
1509 for (;;) {
1510 if (Lexer.is(AsmToken::Eof))
1511 return TokError("unexpected token in macro instantiation");
1512 if (Lexer.is(AsmToken::EndOfStatement))
1513 break;
1514
1515 // If we aren't inside parentheses and this is a comma, start a new token
1516 // list.
1517 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1518 MacroArguments.push_back(std::vector<AsmToken>());
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001519 } else {
Daniel Dunbare25c6b92010-08-10 17:38:52 +00001520 // Adjust the current parentheses level.
1521 if (Lexer.is(AsmToken::LParen))
1522 ++ParenLevel;
1523 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1524 --ParenLevel;
1525
1526 // Append the token to the current argument list.
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001527 MacroArguments.back().push_back(getTok());
1528 }
1529 Lex();
1530 }
Jim Grosbachae151ed2012-03-17 00:11:42 +00001531 // If there weren't any arguments, erase the token vector so everything
1532 // else knows that. Leaving around the vestigal empty token list confuses
1533 // things.
1534 if (MacroArguments.size() == 1 && MacroArguments.back().empty())
1535 MacroArguments.clear();
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001536
Rafael Espindola65366442011-06-05 02:43:45 +00001537 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1538 // to hold the macro body with substitutions.
1539 SmallString<256> Buf;
1540 StringRef Body = M->Body;
1541
1542 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1543 return true;
1544
1545 MemoryBuffer *Instantiation =
1546 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1547
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001548 // Create the macro instantiation object and add to the current macro
1549 // instantiation stack.
1550 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001551 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001552 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001553 ActiveMacros.push_back(MI);
1554
1555 // Jump to the macro instantiation and prime the lexer.
1556 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1557 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1558 Lex();
1559
1560 return false;
1561}
1562
1563void AsmParser::HandleMacroExit() {
1564 // Jump to the EndOfStatement we should return to, and consume it.
1565 JumpToLoc(ActiveMacros.back()->ExitLoc);
1566 Lex();
1567
1568 // Pop the instantiation entry.
1569 delete ActiveMacros.back();
1570 ActiveMacros.pop_back();
1571}
1572
Rafael Espindolae71cc862012-01-28 05:57:00 +00001573static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001574 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001575 case MCExpr::Binary: {
1576 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1577 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001578 break;
1579 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001580 case MCExpr::Target:
1581 case MCExpr::Constant:
1582 return false;
1583 case MCExpr::SymbolRef: {
1584 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001585 if (S.isVariable())
1586 return IsUsedIn(Sym, S.getVariableValue());
1587 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001588 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001589 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001590 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001591 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001592
1593 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001594}
1595
Nico Weber4c4c7322011-01-28 03:04:41 +00001596bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001597 // FIXME: Use better location, we should use proper tokens.
1598 SMLoc EqualLoc = Lexer.getLoc();
1599
Daniel Dunbar821e3332009-08-31 08:09:28 +00001600 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001601 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001602 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001603
Rafael Espindolae71cc862012-01-28 05:57:00 +00001604 // Note: we don't count b as used in "a = b". This is to allow
1605 // a = b
1606 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001607
Daniel Dunbar3f872332009-07-28 16:08:33 +00001608 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001609 return TokError("unexpected token in assignment");
1610
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001611 // Error on assignment to '.'.
1612 if (Name == ".") {
1613 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1614 "(use '.space' or '.org').)"));
1615 }
1616
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001617 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001618 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001619
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001620 // Validate that the LHS is allowed to be a variable (either it has not been
1621 // used as a symbol, or it is an absolute symbol).
1622 MCSymbol *Sym = getContext().LookupSymbol(Name);
1623 if (Sym) {
1624 // Diagnose assignment to a label.
1625 //
1626 // FIXME: Diagnostics. Note the location of the definition as a label.
1627 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001628 if (IsUsedIn(Sym, Value))
1629 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1630 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001631 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001632 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1633 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001634 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001635 return Error(EqualLoc, "redefinition of '" + Name + "'");
1636 else if (!Sym->isVariable())
1637 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001638 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001639 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1640 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001641
1642 // Don't count these checks as uses.
1643 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001644 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001645 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001646
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001647 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001648
1649 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001650 Out.EmitAssignment(Sym, Value);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001651
1652 return false;
1653}
1654
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001655/// ParseIdentifier:
1656/// ::= identifier
1657/// ::= string
1658bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001659 // The assembler has relaxed rules for accepting identifiers, in particular we
1660 // allow things like '.globl $foo', which would normally be separate
1661 // tokens. At this level, we have already lexed so we cannot (currently)
1662 // handle this as a context dependent token, instead we detect adjacent tokens
1663 // and return the combined identifier.
1664 if (Lexer.is(AsmToken::Dollar)) {
1665 SMLoc DollarLoc = getLexer().getLoc();
1666
1667 // Consume the dollar sign, and check for a following identifier.
1668 Lex();
1669 if (Lexer.isNot(AsmToken::Identifier))
1670 return true;
1671
1672 // We have a '$' followed by an identifier, make sure they are adjacent.
1673 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1674 return true;
1675
1676 // Construct the joined identifier and consume the token.
1677 Res = StringRef(DollarLoc.getPointer(),
1678 getTok().getIdentifier().size() + 1);
1679 Lex();
1680 return false;
1681 }
1682
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001683 if (Lexer.isNot(AsmToken::Identifier) &&
1684 Lexer.isNot(AsmToken::String))
1685 return true;
1686
Sean Callanan18b83232010-01-19 21:44:56 +00001687 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001688
Sean Callanan79ed1a82010-01-19 20:22:31 +00001689 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001690
1691 return false;
1692}
1693
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001694/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001695/// ::= .equ identifier ',' expression
1696/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001697/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001698bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001699 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001700
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001701 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001702 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001703
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001704 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001705 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001706 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001707
Nico Weber4c4c7322011-01-28 03:04:41 +00001708 return ParseAssignment(Name, allow_redef);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001709}
1710
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001711bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001712 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001713
1714 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00001715 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001716 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1717 if (Str[i] != '\\') {
1718 Data += Str[i];
1719 continue;
1720 }
1721
1722 // Recognize escaped characters. Note that this escape semantics currently
1723 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1724 ++i;
1725 if (i == e)
1726 return TokError("unexpected backslash at end of string");
1727
1728 // Recognize octal sequences.
1729 if ((unsigned) (Str[i] - '0') <= 7) {
1730 // Consume up to three octal characters.
1731 unsigned Value = Str[i] - '0';
1732
1733 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1734 ++i;
1735 Value = Value * 8 + (Str[i] - '0');
1736
1737 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1738 ++i;
1739 Value = Value * 8 + (Str[i] - '0');
1740 }
1741 }
1742
1743 if (Value > 255)
1744 return TokError("invalid octal escape sequence (out of range)");
1745
1746 Data += (unsigned char) Value;
1747 continue;
1748 }
1749
1750 // Otherwise recognize individual escapes.
1751 switch (Str[i]) {
1752 default:
1753 // Just reject invalid escape sequences for now.
1754 return TokError("invalid escape sequence (unrecognized character)");
1755
1756 case 'b': Data += '\b'; break;
1757 case 'f': Data += '\f'; break;
1758 case 'n': Data += '\n'; break;
1759 case 'r': Data += '\r'; break;
1760 case 't': Data += '\t'; break;
1761 case '"': Data += '"'; break;
1762 case '\\': Data += '\\'; break;
1763 }
1764 }
1765
1766 return false;
1767}
1768
Daniel Dunbara0d14262009-06-24 23:30:00 +00001769/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00001770/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1771bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001772 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001773 CheckForValidSection();
1774
Daniel Dunbara0d14262009-06-24 23:30:00 +00001775 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001776 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00001777 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001778
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001779 std::string Data;
1780 if (ParseEscapedString(Data))
1781 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001782
1783 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001784 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001785 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1786
Sean Callanan79ed1a82010-01-19 20:22:31 +00001787 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001788
1789 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001790 break;
1791
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001792 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00001793 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001794 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001795 }
1796 }
1797
Sean Callanan79ed1a82010-01-19 20:22:31 +00001798 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001799 return false;
1800}
1801
1802/// ParseDirectiveValue
1803/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1804bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001805 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001806 CheckForValidSection();
1807
Daniel Dunbara0d14262009-06-24 23:30:00 +00001808 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00001809 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00001810 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00001811 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001812 return true;
1813
Daniel Dunbar414c0c42010-05-23 18:36:38 +00001814 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00001815 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1816 assert(Size <= 8 && "Invalid size");
1817 uint64_t IntValue = MCE->getValue();
1818 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1819 return Error(ExprLoc, "literal value out of range for directive");
1820 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1821 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001822 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001823
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001824 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001825 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001826
Daniel Dunbara0d14262009-06-24 23:30:00 +00001827 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001828 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001829 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001830 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001831 }
1832 }
1833
Sean Callanan79ed1a82010-01-19 20:22:31 +00001834 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001835 return false;
1836}
1837
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001838/// ParseDirectiveRealValue
1839/// ::= (.single | .double) [ expression (, expression)* ]
1840bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1841 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1842 CheckForValidSection();
1843
1844 for (;;) {
1845 // We don't truly support arithmetic on floating point expressions, so we
1846 // have to manually parse unary prefixes.
1847 bool IsNeg = false;
1848 if (getLexer().is(AsmToken::Minus)) {
1849 Lex();
1850 IsNeg = true;
1851 } else if (getLexer().is(AsmToken::Plus))
1852 Lex();
1853
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001854 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00001855 getLexer().isNot(AsmToken::Real) &&
1856 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001857 return TokError("unexpected token in directive");
1858
1859 // Convert to an APFloat.
1860 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00001861 StringRef IDVal = getTok().getString();
1862 if (getLexer().is(AsmToken::Identifier)) {
1863 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1864 Value = APFloat::getInf(Semantics);
1865 else if (!IDVal.compare_lower("nan"))
1866 Value = APFloat::getNaN(Semantics, false, ~0);
1867 else
1868 return TokError("invalid floating point literal");
1869 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001870 APFloat::opInvalidOp)
1871 return TokError("invalid floating point literal");
1872 if (IsNeg)
1873 Value.changeSign();
1874
1875 // Consume the numeric token.
1876 Lex();
1877
1878 // Emit the value as an integer.
1879 APInt AsInt = Value.bitcastToAPInt();
1880 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1881 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1882
1883 if (getLexer().is(AsmToken::EndOfStatement))
1884 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001885
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001886 if (getLexer().isNot(AsmToken::Comma))
1887 return TokError("unexpected token in directive");
1888 Lex();
1889 }
1890 }
1891
1892 Lex();
1893 return false;
1894}
1895
Daniel Dunbara0d14262009-06-24 23:30:00 +00001896/// ParseDirectiveSpace
1897/// ::= .space expression [ , expression ]
1898bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001899 CheckForValidSection();
1900
Daniel Dunbara0d14262009-06-24 23:30:00 +00001901 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001902 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001903 return true;
1904
1905 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001906 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1907 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001908 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001909 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001910
Daniel Dunbar475839e2009-06-29 20:37:27 +00001911 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001912 return true;
1913
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001914 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001915 return TokError("unexpected token in '.space' directive");
1916 }
1917
Sean Callanan79ed1a82010-01-19 20:22:31 +00001918 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001919
1920 if (NumBytes <= 0)
1921 return TokError("invalid number of bytes in '.space' directive");
1922
1923 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001924 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001925
1926 return false;
1927}
1928
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001929/// ParseDirectiveZero
1930/// ::= .zero expression
1931bool AsmParser::ParseDirectiveZero() {
1932 CheckForValidSection();
1933
1934 int64_t NumBytes;
1935 if (ParseAbsoluteExpression(NumBytes))
1936 return true;
1937
Rafael Espindolae452b172010-10-05 19:42:57 +00001938 int64_t Val = 0;
1939 if (getLexer().is(AsmToken::Comma)) {
1940 Lex();
1941 if (ParseAbsoluteExpression(Val))
1942 return true;
1943 }
1944
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001945 if (getLexer().isNot(AsmToken::EndOfStatement))
1946 return TokError("unexpected token in '.zero' directive");
1947
1948 Lex();
1949
Rafael Espindolae452b172010-10-05 19:42:57 +00001950 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001951
1952 return false;
1953}
1954
Daniel Dunbara0d14262009-06-24 23:30:00 +00001955/// ParseDirectiveFill
1956/// ::= .fill expression , expression , expression
1957bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001958 CheckForValidSection();
1959
Daniel Dunbara0d14262009-06-24 23:30:00 +00001960 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001961 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001962 return true;
1963
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001964 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001965 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001966 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001967
Daniel Dunbara0d14262009-06-24 23:30:00 +00001968 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001969 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001970 return true;
1971
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001972 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001973 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001974 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001975
Daniel Dunbara0d14262009-06-24 23:30:00 +00001976 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001977 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001978 return true;
1979
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001980 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001981 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001982
Sean Callanan79ed1a82010-01-19 20:22:31 +00001983 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001984
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00001985 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1986 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00001987
1988 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001989 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001990
1991 return false;
1992}
Daniel Dunbarc238b582009-06-25 22:44:51 +00001993
1994/// ParseDirectiveOrg
1995/// ::= .org expression [ , expression ]
1996bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001997 CheckForValidSection();
1998
Daniel Dunbar821e3332009-08-31 08:09:28 +00001999 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002000 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002001 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002002 return true;
2003
2004 // Parse optional fill expression.
2005 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002006 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2007 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002008 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002009 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002010
Daniel Dunbar475839e2009-06-29 20:37:27 +00002011 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002012 return true;
2013
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002014 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002015 return TokError("unexpected token in '.org' directive");
2016 }
2017
Sean Callanan79ed1a82010-01-19 20:22:31 +00002018 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002019
Jim Grosbachebd4c052012-01-27 00:37:08 +00002020 // Only limited forms of relocatable expressions are accepted here, it
2021 // has to be relative to the current section. The streamer will return
2022 // 'true' if the expression wasn't evaluatable.
2023 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2024 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002025
2026 return false;
2027}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002028
2029/// ParseDirectiveAlign
2030/// ::= {.align, ...} expression [ , expression [ , expression ]]
2031bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002032 CheckForValidSection();
2033
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002034 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002035 int64_t Alignment;
2036 if (ParseAbsoluteExpression(Alignment))
2037 return true;
2038
2039 SMLoc MaxBytesLoc;
2040 bool HasFillExpr = false;
2041 int64_t FillExpr = 0;
2042 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002043 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2044 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002045 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002046 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002047
2048 // The fill expression can be omitted while specifying a maximum number of
2049 // alignment bytes, e.g:
2050 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002051 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002052 HasFillExpr = true;
2053 if (ParseAbsoluteExpression(FillExpr))
2054 return true;
2055 }
2056
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002057 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2058 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002059 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002060 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002061
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002062 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002063 if (ParseAbsoluteExpression(MaxBytesToFill))
2064 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002065
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002066 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002067 return TokError("unexpected token in directive");
2068 }
2069 }
2070
Sean Callanan79ed1a82010-01-19 20:22:31 +00002071 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002072
Daniel Dunbar648ac512010-05-17 21:54:30 +00002073 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002074 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002075
2076 // Compute alignment in bytes.
2077 if (IsPow2) {
2078 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002079 if (Alignment >= 32) {
2080 Error(AlignmentLoc, "invalid alignment value");
2081 Alignment = 31;
2082 }
2083
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002084 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002085 }
2086
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002087 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002088 if (MaxBytesLoc.isValid()) {
2089 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002090 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2091 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002092 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002093 }
2094
2095 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002096 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2097 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002098 MaxBytesToFill = 0;
2099 }
2100 }
2101
Daniel Dunbar648ac512010-05-17 21:54:30 +00002102 // Check whether we should use optimal code alignment for this .align
2103 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002104 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002105 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2106 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002107 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002108 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002109 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002110 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2111 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002112 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002113
2114 return false;
2115}
2116
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002117/// ParseDirectiveSymbolAttribute
2118/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002119bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002120 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002121 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002122 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002123 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002124
2125 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002126 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002127
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002128 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002129
Jim Grosbach10ec6502011-09-15 17:56:49 +00002130 // Assembler local symbols don't make any sense here. Complain loudly.
2131 if (Sym->isTemporary())
2132 return Error(Loc, "non-local symbol required in directive");
2133
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002134 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002135
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002136 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002137 break;
2138
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002139 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002140 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002141 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002142 }
2143 }
2144
Sean Callanan79ed1a82010-01-19 20:22:31 +00002145 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002146 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002147}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002148
2149/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002150/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2151bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002152 CheckForValidSection();
2153
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002154 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002155 StringRef Name;
2156 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002157 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002158
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002159 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002160 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002161
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002162 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002163 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002164 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002165
2166 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002167 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002168 if (ParseAbsoluteExpression(Size))
2169 return true;
2170
2171 int64_t Pow2Alignment = 0;
2172 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002173 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002174 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002175 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002176 if (ParseAbsoluteExpression(Pow2Alignment))
2177 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002178
Chris Lattner258281d2010-01-19 06:22:22 +00002179 // If this target takes alignments in bytes (not log) validate and convert.
2180 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2181 if (!isPowerOf2_64(Pow2Alignment))
2182 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2183 Pow2Alignment = Log2_64(Pow2Alignment);
2184 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002185 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002186
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002187 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002188 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002189
Sean Callanan79ed1a82010-01-19 20:22:31 +00002190 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002191
Chris Lattner1fc3d752009-07-09 17:25:12 +00002192 // NOTE: a size of zero for a .comm should create a undefined symbol
2193 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002194 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002195 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2196 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002197
Eric Christopherc260a3e2010-05-14 01:38:54 +00002198 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002199 // may internally end up wanting an alignment in bytes.
2200 // FIXME: Diagnose overflow.
2201 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002202 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2203 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002204
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002205 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002206 return Error(IDLoc, "invalid symbol redefinition");
2207
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002208 // '.lcomm' is equivalent to '.zerofill'.
Chris Lattner1fc3d752009-07-09 17:25:12 +00002209 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002210 if (IsLocal) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002211 getStreamer().EmitZerofill(Ctx.getMachOSection(
2212 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2213 0, SectionKind::getBSS()),
2214 Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002215 return false;
2216 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002217
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002218 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002219 return false;
2220}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002221
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002222/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002223/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002224bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002225 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002226 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002227
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002228 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002229 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002230 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002231
Sean Callanan79ed1a82010-01-19 20:22:31 +00002232 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002233
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002234 if (Str.empty())
2235 Error(Loc, ".abort detected. Assembly stopping.");
2236 else
2237 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002238 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002239
2240 return false;
2241}
Kevin Enderby71148242009-07-14 21:35:03 +00002242
Kevin Enderby1f049b22009-07-14 23:21:55 +00002243/// ParseDirectiveInclude
2244/// ::= .include "filename"
2245bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002246 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002247 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002248
Sean Callanan18b83232010-01-19 21:44:56 +00002249 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002250 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002251 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002252
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002253 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002254 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002255
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002256 // Strip the quotes.
2257 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002258
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002259 // Attempt to switch the lexer to the included file before consuming the end
2260 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002261 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002262 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002263 return true;
2264 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002265
2266 return false;
2267}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002268
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002269/// ParseDirectiveIncbin
2270/// ::= .incbin "filename"
2271bool AsmParser::ParseDirectiveIncbin() {
2272 if (getLexer().isNot(AsmToken::String))
2273 return TokError("expected string in '.incbin' directive");
2274
2275 std::string Filename = getTok().getString();
2276 SMLoc IncbinLoc = getLexer().getLoc();
2277 Lex();
2278
2279 if (getLexer().isNot(AsmToken::EndOfStatement))
2280 return TokError("unexpected token in '.incbin' directive");
2281
2282 // Strip the quotes.
2283 Filename = Filename.substr(1, Filename.size()-2);
2284
2285 // Attempt to process the included file.
2286 if (ProcessIncbinFile(Filename)) {
2287 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2288 return true;
2289 }
2290
2291 return false;
2292}
2293
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002294/// ParseDirectiveIf
2295/// ::= .if expression
2296bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002297 TheCondStack.push_back(TheCondState);
2298 TheCondState.TheCond = AsmCond::IfCond;
2299 if(TheCondState.Ignore) {
2300 EatToEndOfStatement();
2301 }
2302 else {
2303 int64_t ExprValue;
2304 if (ParseAbsoluteExpression(ExprValue))
2305 return true;
2306
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002307 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002308 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002309
Sean Callanan79ed1a82010-01-19 20:22:31 +00002310 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002311
2312 TheCondState.CondMet = ExprValue;
2313 TheCondState.Ignore = !TheCondState.CondMet;
2314 }
2315
2316 return false;
2317}
2318
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002319bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2320 StringRef Name;
2321 TheCondStack.push_back(TheCondState);
2322 TheCondState.TheCond = AsmCond::IfCond;
2323
2324 if (TheCondState.Ignore) {
2325 EatToEndOfStatement();
2326 } else {
2327 if (ParseIdentifier(Name))
2328 return TokError("expected identifier after '.ifdef'");
2329
2330 Lex();
2331
2332 MCSymbol *Sym = getContext().LookupSymbol(Name);
2333
2334 if (expect_defined)
2335 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2336 else
2337 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2338 TheCondState.Ignore = !TheCondState.CondMet;
2339 }
2340
2341 return false;
2342}
2343
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002344/// ParseDirectiveElseIf
2345/// ::= .elseif expression
2346bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2347 if (TheCondState.TheCond != AsmCond::IfCond &&
2348 TheCondState.TheCond != AsmCond::ElseIfCond)
2349 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2350 " an .elseif");
2351 TheCondState.TheCond = AsmCond::ElseIfCond;
2352
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002353 bool LastIgnoreState = false;
2354 if (!TheCondStack.empty())
2355 LastIgnoreState = TheCondStack.back().Ignore;
2356 if (LastIgnoreState || TheCondState.CondMet) {
2357 TheCondState.Ignore = true;
2358 EatToEndOfStatement();
2359 }
2360 else {
2361 int64_t ExprValue;
2362 if (ParseAbsoluteExpression(ExprValue))
2363 return true;
2364
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002365 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002366 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002367
Sean Callanan79ed1a82010-01-19 20:22:31 +00002368 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002369 TheCondState.CondMet = ExprValue;
2370 TheCondState.Ignore = !TheCondState.CondMet;
2371 }
2372
2373 return false;
2374}
2375
2376/// ParseDirectiveElse
2377/// ::= .else
2378bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002379 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002380 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002381
Sean Callanan79ed1a82010-01-19 20:22:31 +00002382 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002383
2384 if (TheCondState.TheCond != AsmCond::IfCond &&
2385 TheCondState.TheCond != AsmCond::ElseIfCond)
2386 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2387 ".elseif");
2388 TheCondState.TheCond = AsmCond::ElseCond;
2389 bool LastIgnoreState = false;
2390 if (!TheCondStack.empty())
2391 LastIgnoreState = TheCondStack.back().Ignore;
2392 if (LastIgnoreState || TheCondState.CondMet)
2393 TheCondState.Ignore = true;
2394 else
2395 TheCondState.Ignore = false;
2396
2397 return false;
2398}
2399
2400/// ParseDirectiveEndIf
2401/// ::= .endif
2402bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002403 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002404 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002405
Sean Callanan79ed1a82010-01-19 20:22:31 +00002406 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002407
2408 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2409 TheCondStack.empty())
2410 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2411 ".else");
2412 if (!TheCondStack.empty()) {
2413 TheCondState = TheCondStack.back();
2414 TheCondStack.pop_back();
2415 }
2416
2417 return false;
2418}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002419
2420/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002421/// ::= .file [number] filename
2422/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002423bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002424 // FIXME: I'm not sure what this is.
2425 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002426 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002427 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002428 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002429 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002430
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002431 if (FileNumber < 1)
2432 return TokError("file number less than one");
2433 }
2434
Daniel Dunbareceec052010-07-12 17:45:27 +00002435 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002436 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002437
Nick Lewycky44d798d2011-10-17 23:05:28 +00002438 // Usually the directory and filename together, otherwise just the directory.
2439 StringRef Path = getTok().getString();
2440 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002441 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002442
Nick Lewycky44d798d2011-10-17 23:05:28 +00002443 StringRef Directory;
2444 StringRef Filename;
2445 if (getLexer().is(AsmToken::String)) {
2446 if (FileNumber == -1)
2447 return TokError("explicit path specified, but no file number");
2448 Filename = getTok().getString();
2449 Filename = Filename.substr(1, Filename.size()-2);
2450 Directory = Path;
2451 Lex();
2452 } else {
2453 Filename = Path;
2454 }
2455
Daniel Dunbareceec052010-07-12 17:45:27 +00002456 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002457 return TokError("unexpected token in '.file' directive");
2458
Chris Lattnerd32e8032010-01-25 19:02:58 +00002459 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002460 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002461 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002462 if (getContext().getGenDwarfForAssembly() == true)
2463 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2464 "used to generate dwarf debug info for assembly code");
2465
Nick Lewycky44d798d2011-10-17 23:05:28 +00002466 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002467 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002468 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002469
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002470 return false;
2471}
2472
2473/// ParseDirectiveLine
2474/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002475bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002476 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2477 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002478 return TokError("unexpected token in '.line' directive");
2479
Sean Callanan18b83232010-01-19 21:44:56 +00002480 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002481 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002482 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002483
2484 // FIXME: Do something with the .line.
2485 }
2486
Daniel Dunbareceec052010-07-12 17:45:27 +00002487 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002488 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002489
2490 return false;
2491}
2492
2493
2494/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002495/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002496/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2497/// The first number is a file number, must have been previously assigned with
2498/// a .file directive, the second number is the line number and optionally the
2499/// third number is a column position (zero if not specified). The remaining
2500/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002501bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002502
Daniel Dunbareceec052010-07-12 17:45:27 +00002503 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002504 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002505 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002506 if (FileNumber < 1)
2507 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002508 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002509 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002510 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002511
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002512 int64_t LineNumber = 0;
2513 if (getLexer().is(AsmToken::Integer)) {
2514 LineNumber = getTok().getIntVal();
2515 if (LineNumber < 1)
2516 return TokError("line number less than one in '.loc' directive");
2517 Lex();
2518 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002519
2520 int64_t ColumnPos = 0;
2521 if (getLexer().is(AsmToken::Integer)) {
2522 ColumnPos = getTok().getIntVal();
2523 if (ColumnPos < 0)
2524 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002525 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002526 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002527
Kevin Enderbyc0957932010-09-30 16:52:03 +00002528 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002529 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002530 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002531 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2532 for (;;) {
2533 if (getLexer().is(AsmToken::EndOfStatement))
2534 break;
2535
2536 StringRef Name;
2537 SMLoc Loc = getTok().getLoc();
2538 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002539 return TokError("unexpected token in '.loc' directive");
2540
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002541 if (Name == "basic_block")
2542 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2543 else if (Name == "prologue_end")
2544 Flags |= DWARF2_FLAG_PROLOGUE_END;
2545 else if (Name == "epilogue_begin")
2546 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2547 else if (Name == "is_stmt") {
2548 SMLoc Loc = getTok().getLoc();
2549 const MCExpr *Value;
2550 if (getParser().ParseExpression(Value))
2551 return true;
2552 // The expression must be the constant 0 or 1.
2553 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2554 int Value = MCE->getValue();
2555 if (Value == 0)
2556 Flags &= ~DWARF2_FLAG_IS_STMT;
2557 else if (Value == 1)
2558 Flags |= DWARF2_FLAG_IS_STMT;
2559 else
2560 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002561 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002562 else {
2563 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2564 }
2565 }
2566 else if (Name == "isa") {
2567 SMLoc Loc = getTok().getLoc();
2568 const MCExpr *Value;
2569 if (getParser().ParseExpression(Value))
2570 return true;
2571 // The expression must be a constant greater or equal to 0.
2572 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2573 int Value = MCE->getValue();
2574 if (Value < 0)
2575 return Error(Loc, "isa number less than zero");
2576 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002577 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002578 else {
2579 return Error(Loc, "isa number not a constant value");
2580 }
2581 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002582 else if (Name == "discriminator") {
2583 if (getParser().ParseAbsoluteExpression(Discriminator))
2584 return true;
2585 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002586 else {
2587 return Error(Loc, "unknown sub-directive in '.loc' directive");
2588 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002589
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002590 if (getLexer().is(AsmToken::EndOfStatement))
2591 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002592 }
2593 }
2594
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002595 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002596 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002597
2598 return false;
2599}
2600
Daniel Dunbar138abae2010-10-16 04:56:42 +00002601/// ParseDirectiveStabs
2602/// ::= .stabs string, number, number, number
2603bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2604 SMLoc DirectiveLoc) {
2605 return TokError("unsupported directive '" + Directive + "'");
2606}
2607
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002608/// ParseDirectiveCFISections
2609/// ::= .cfi_sections section [, section]
2610bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2611 SMLoc DirectiveLoc) {
2612 StringRef Name;
2613 bool EH = false;
2614 bool Debug = false;
2615
2616 if (getParser().ParseIdentifier(Name))
2617 return TokError("Expected an identifier");
2618
2619 if (Name == ".eh_frame")
2620 EH = true;
2621 else if (Name == ".debug_frame")
2622 Debug = true;
2623
2624 if (getLexer().is(AsmToken::Comma)) {
2625 Lex();
2626
2627 if (getParser().ParseIdentifier(Name))
2628 return TokError("Expected an identifier");
2629
2630 if (Name == ".eh_frame")
2631 EH = true;
2632 else if (Name == ".debug_frame")
2633 Debug = true;
2634 }
2635
2636 getStreamer().EmitCFISections(EH, Debug);
2637
2638 return false;
2639}
2640
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002641/// ParseDirectiveCFIStartProc
2642/// ::= .cfi_startproc
2643bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2644 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002645 getStreamer().EmitCFIStartProc();
2646 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002647}
2648
2649/// ParseDirectiveCFIEndProc
2650/// ::= .cfi_endproc
2651bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002652 getStreamer().EmitCFIEndProc();
2653 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002654}
2655
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002656/// ParseRegisterOrRegisterNumber - parse register name or number.
2657bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2658 SMLoc DirectiveLoc) {
2659 unsigned RegNo;
2660
Jim Grosbach6f888a82011-06-02 17:14:04 +00002661 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002662 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2663 DirectiveLoc))
2664 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00002665 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002666 } else
2667 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00002668
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002669 return false;
2670}
2671
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002672/// ParseDirectiveCFIDefCfa
2673/// ::= .cfi_def_cfa register, offset
2674bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2675 SMLoc DirectiveLoc) {
2676 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002677 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002678 return true;
2679
2680 if (getLexer().isNot(AsmToken::Comma))
2681 return TokError("unexpected token in directive");
2682 Lex();
2683
2684 int64_t Offset = 0;
2685 if (getParser().ParseAbsoluteExpression(Offset))
2686 return true;
2687
Rafael Espindola066c2f42011-04-12 23:59:07 +00002688 getStreamer().EmitCFIDefCfa(Register, Offset);
2689 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002690}
2691
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002692/// ParseDirectiveCFIDefCfaOffset
2693/// ::= .cfi_def_cfa_offset offset
2694bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2695 SMLoc DirectiveLoc) {
2696 int64_t Offset = 0;
2697 if (getParser().ParseAbsoluteExpression(Offset))
2698 return true;
2699
Rafael Espindola066c2f42011-04-12 23:59:07 +00002700 getStreamer().EmitCFIDefCfaOffset(Offset);
2701 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00002702}
2703
2704/// ParseDirectiveCFIAdjustCfaOffset
2705/// ::= .cfi_adjust_cfa_offset adjustment
2706bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2707 SMLoc DirectiveLoc) {
2708 int64_t Adjustment = 0;
2709 if (getParser().ParseAbsoluteExpression(Adjustment))
2710 return true;
2711
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00002712 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2713 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002714}
2715
2716/// ParseDirectiveCFIDefCfaRegister
2717/// ::= .cfi_def_cfa_register register
2718bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2719 SMLoc DirectiveLoc) {
2720 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002721 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002722 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002723
Rafael Espindola066c2f42011-04-12 23:59:07 +00002724 getStreamer().EmitCFIDefCfaRegister(Register);
2725 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002726}
2727
2728/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002729/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002730bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2731 int64_t Register = 0;
2732 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002733
2734 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002735 return true;
2736
2737 if (getLexer().isNot(AsmToken::Comma))
2738 return TokError("unexpected token in directive");
2739 Lex();
2740
2741 if (getParser().ParseAbsoluteExpression(Offset))
2742 return true;
2743
Rafael Espindola066c2f42011-04-12 23:59:07 +00002744 getStreamer().EmitCFIOffset(Register, Offset);
2745 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002746}
2747
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002748/// ParseDirectiveCFIRelOffset
2749/// ::= .cfi_rel_offset register, offset
2750bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2751 SMLoc DirectiveLoc) {
2752 int64_t Register = 0;
2753
2754 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2755 return true;
2756
2757 if (getLexer().isNot(AsmToken::Comma))
2758 return TokError("unexpected token in directive");
2759 Lex();
2760
2761 int64_t Offset = 0;
2762 if (getParser().ParseAbsoluteExpression(Offset))
2763 return true;
2764
Rafael Espindola25f492e2011-04-12 16:12:03 +00002765 getStreamer().EmitCFIRelOffset(Register, Offset);
2766 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002767}
2768
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002769static bool isValidEncoding(int64_t Encoding) {
2770 if (Encoding & ~0xff)
2771 return false;
2772
2773 if (Encoding == dwarf::DW_EH_PE_omit)
2774 return true;
2775
2776 const unsigned Format = Encoding & 0xf;
2777 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2778 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2779 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2780 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2781 return false;
2782
Rafael Espindolacaf11582010-12-29 04:31:26 +00002783 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002784 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00002785 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002786 return false;
2787
2788 return true;
2789}
2790
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002791/// ParseDirectiveCFIPersonalityOrLsda
2792/// ::= .cfi_personality encoding, [symbol_name]
2793/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002794bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002795 SMLoc DirectiveLoc) {
2796 int64_t Encoding = 0;
2797 if (getParser().ParseAbsoluteExpression(Encoding))
2798 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002799 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002800 return false;
2801
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002802 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002803 return TokError("unsupported encoding.");
2804
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002805 if (getLexer().isNot(AsmToken::Comma))
2806 return TokError("unexpected token in directive");
2807 Lex();
2808
2809 StringRef Name;
2810 if (getParser().ParseIdentifier(Name))
2811 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002812
2813 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2814
2815 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00002816 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002817 else {
2818 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00002819 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002820 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00002821 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002822}
2823
Rafael Espindolafe024d02010-12-28 18:36:23 +00002824/// ParseDirectiveCFIRememberState
2825/// ::= .cfi_remember_state
2826bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2827 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002828 getStreamer().EmitCFIRememberState();
2829 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00002830}
2831
2832/// ParseDirectiveCFIRestoreState
2833/// ::= .cfi_remember_state
2834bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2835 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002836 getStreamer().EmitCFIRestoreState();
2837 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00002838}
2839
Rafael Espindolac5754392011-04-12 15:31:05 +00002840/// ParseDirectiveCFISameValue
2841/// ::= .cfi_same_value register
2842bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2843 SMLoc DirectiveLoc) {
2844 int64_t Register = 0;
2845
2846 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2847 return true;
2848
2849 getStreamer().EmitCFISameValue(Register);
2850
2851 return false;
2852}
2853
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00002854/// ParseDirectiveCFIRestore
2855/// ::= .cfi_restore register
2856bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2857 SMLoc DirectiveLoc) {
2858 int64_t Register = 0;
2859 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2860 return true;
2861
2862 getStreamer().EmitCFIRestore(Register);
2863
2864 return false;
2865}
2866
Rafael Espindola6f0b1812011-12-29 20:24:47 +00002867/// ParseDirectiveCFIEscape
2868/// ::= .cfi_escape expression[,...]
2869bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2870 SMLoc DirectiveLoc) {
2871 std::string Values;
2872 int64_t CurrValue;
2873 if (getParser().ParseAbsoluteExpression(CurrValue))
2874 return true;
2875
2876 Values.push_back((uint8_t)CurrValue);
2877
2878 while (getLexer().is(AsmToken::Comma)) {
2879 Lex();
2880
2881 if (getParser().ParseAbsoluteExpression(CurrValue))
2882 return true;
2883
2884 Values.push_back((uint8_t)CurrValue);
2885 }
2886
2887 getStreamer().EmitCFIEscape(Values);
2888 return false;
2889}
2890
Rafael Espindola16d7d432012-01-23 21:51:52 +00002891/// ParseDirectiveCFISignalFrame
2892/// ::= .cfi_signal_frame
2893bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2894 SMLoc DirectiveLoc) {
2895 if (getLexer().isNot(AsmToken::EndOfStatement))
2896 return Error(getLexer().getLoc(),
2897 "unexpected token in '" + Directive + "' directive");
2898
2899 getStreamer().EmitCFISignalFrame();
2900
2901 return false;
2902}
2903
Daniel Dunbar3c802de2010-07-18 18:38:02 +00002904/// ParseDirectiveMacrosOnOff
2905/// ::= .macros_on
2906/// ::= .macros_off
2907bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2908 SMLoc DirectiveLoc) {
2909 if (getLexer().isNot(AsmToken::EndOfStatement))
2910 return Error(getLexer().getLoc(),
2911 "unexpected token in '" + Directive + "' directive");
2912
2913 getParser().MacrosEnabled = Directive == ".macros_on";
2914
2915 return false;
2916}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00002917
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002918/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00002919/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002920bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2921 SMLoc DirectiveLoc) {
2922 StringRef Name;
2923 if (getParser().ParseIdentifier(Name))
2924 return TokError("expected identifier in directive");
2925
Rafael Espindola65366442011-06-05 02:43:45 +00002926 std::vector<StringRef> Parameters;
2927 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2928 for(;;) {
2929 StringRef Parameter;
2930 if (getParser().ParseIdentifier(Parameter))
2931 return TokError("expected identifier in directive");
2932 Parameters.push_back(Parameter);
2933
2934 if (getLexer().isNot(AsmToken::Comma))
2935 break;
2936 Lex();
2937 }
2938 }
2939
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002940 if (getLexer().isNot(AsmToken::EndOfStatement))
2941 return TokError("unexpected token in '.macro' directive");
2942
2943 // Eat the end of statement.
2944 Lex();
2945
2946 AsmToken EndToken, StartToken = getTok();
2947
2948 // Lex the macro definition.
2949 for (;;) {
2950 // Check whether we have reached the end of the file.
2951 if (getLexer().is(AsmToken::Eof))
2952 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2953
2954 // Otherwise, check whether we have reach the .endmacro.
2955 if (getLexer().is(AsmToken::Identifier) &&
2956 (getTok().getIdentifier() == ".endm" ||
2957 getTok().getIdentifier() == ".endmacro")) {
2958 EndToken = getTok();
2959 Lex();
2960 if (getLexer().isNot(AsmToken::EndOfStatement))
2961 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2962 "' directive");
2963 break;
2964 }
2965
2966 // Otherwise, scan til the end of the statement.
2967 getParser().EatToEndOfStatement();
2968 }
2969
2970 if (getParser().MacroMap.lookup(Name)) {
2971 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2972 }
2973
2974 const char *BodyStart = StartToken.getLoc().getPointer();
2975 const char *BodyEnd = EndToken.getLoc().getPointer();
2976 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00002977 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002978 return false;
2979}
2980
2981/// ParseDirectiveEndMacro
2982/// ::= .endm
2983/// ::= .endmacro
2984bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2985 SMLoc DirectiveLoc) {
2986 if (getLexer().isNot(AsmToken::EndOfStatement))
2987 return TokError("unexpected token in '" + Directive + "' directive");
2988
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002989 // If we are inside a macro instantiation, terminate the current
2990 // instantiation.
2991 if (!getParser().ActiveMacros.empty()) {
2992 getParser().HandleMacroExit();
2993 return false;
2994 }
2995
2996 // Otherwise, this .endmacro is a stray entry in the file; well formed
2997 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002998 return TokError("unexpected '" + Directive + "' in file, "
2999 "no current macro definition");
3000}
3001
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003002bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003003 getParser().CheckForValidSection();
3004
3005 const MCExpr *Value;
3006
3007 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003008 return true;
3009
3010 if (getLexer().isNot(AsmToken::EndOfStatement))
3011 return TokError("unexpected token in directive");
3012
3013 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003014 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003015 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003016 getStreamer().EmitULEB128Value(Value);
3017
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003018 return false;
3019}
3020
3021
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003022/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003023MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003024 MCContext &C, MCStreamer &Out,
3025 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003026 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003027}