blob: aac020d17e88e7e21a4d0fe3531bee7d9c6bf9a5 [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"
Jim Grosbach254cf032011-06-29 16:05:14 +000033#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000035#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000036#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000037#include <cctype>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000039using namespace llvm;
40
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000041static cl::opt<bool>
42FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
44
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000045namespace {
46
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000047/// \brief Helper class for tracking macro definitions.
48struct Macro {
49 StringRef Name;
50 StringRef Body;
Rafael Espindola65366442011-06-05 02:43:45 +000051 std::vector<StringRef> Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000052
53public:
Rafael Espindola65366442011-06-05 02:43:45 +000054 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000056};
57
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000058/// \brief Helper class for storing information about an active macro
59/// instantiation.
60struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
63
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
66
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
69
70 /// The location where parsing should resume upon instantiation completion.
71 SMLoc ExitLoc;
72
73public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000074 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000075 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000076};
77
Daniel Dunbaraef87e32010-07-18 18:31:38 +000078/// \brief The concrete assembly parser instance.
79class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +000080 friend class GenericAsmParser;
81
Daniel Dunbaraef87e32010-07-18 18:31:38 +000082 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
84private:
85 AsmLexer Lexer;
86 MCContext &Ctx;
87 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +000088 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000089 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +000090 SourceMgr::DiagHandlerTy SavedDiagHandler;
91 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000092 MCAsmParserExtension *GenericParser;
93 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +000094
Daniel Dunbaraef87e32010-07-18 18:31:38 +000095 /// This is the current buffer index we're lexing from as managed by the
96 /// SourceMgr object.
97 int CurBuffer;
98
99 AsmCond TheCondState;
100 std::vector<AsmCond> TheCondStack;
101
102 /// DirectiveMap - This is a table handlers for directives. Each handler is
103 /// invoked after the directive identifier is read and is responsible for
104 /// parsing and validating the rest of the directive. The handler is passed
105 /// in the directive name and the location of the directive keyword.
106 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000107
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000108 /// MacroMap - Map of currently defined macros.
109 StringMap<Macro*> MacroMap;
110
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000111 /// ActiveMacros - Stack of active macro instantiations.
112 std::vector<MacroInstantiation*> ActiveMacros;
113
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000114 /// Boolean tracking whether macro substitution is enabled.
115 unsigned MacrosEnabled : 1;
116
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000117 /// Flag tracking whether any errors have been encountered.
118 unsigned HadError : 1;
119
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000120 /// The values from the last parsed cpp hash file line comment if any.
121 StringRef CppHashFilename;
122 int64_t CppHashLineNumber;
123 SMLoc CppHashLoc;
124
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000125public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000126 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000127 const MCAsmInfo &MAI);
128 ~AsmParser();
129
130 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
131
132 void AddDirectiveHandler(MCAsmParserExtension *Object,
133 StringRef Directive,
134 DirectiveHandler Handler) {
135 DirectiveMap[Directive] = std::make_pair(Object, Handler);
136 }
137
138public:
139 /// @name MCAsmParser Interface
140 /// {
141
142 virtual SourceMgr &getSourceManager() { return SrcMgr; }
143 virtual MCAsmLexer &getLexer() { return Lexer; }
144 virtual MCContext &getContext() { return Ctx; }
145 virtual MCStreamer &getStreamer() { return Out; }
146
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000147 virtual bool Warning(SMLoc L, const Twine &Msg,
148 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
149 virtual bool Error(SMLoc L, const Twine &Msg,
150 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000151
152 const AsmToken &Lex();
153
154 bool ParseExpression(const MCExpr *&Res);
155 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
156 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
157 virtual bool ParseAbsoluteExpression(int64_t &Res);
158
159 /// }
160
161private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000162 void CheckForValidSection();
163
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000164 bool ParseStatement();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000165 void EatToEndOfLine();
166 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000167
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000168 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola65366442011-06-05 02:43:45 +0000169 bool expandMacro(SmallString<256> &Buf, StringRef Body,
170 const std::vector<StringRef> &Parameters,
171 const std::vector<std::vector<AsmToken> > &A,
172 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000173 void HandleMacroExit();
174
175 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000176 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000177 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
178 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000179 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000180 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000181
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000182 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
183 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000184 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
185 /// This returns true on failure.
186 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000187
188 /// \brief Reset the current lexer position to that given by \arg Loc. The
189 /// current token is not set; clients should ensure Lex() is called
190 /// subsequently.
191 void JumpToLoc(SMLoc Loc);
192
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000193 void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000194
195 /// \brief Parse up to the end of statement and a return the contents from the
196 /// current token until the end of the statement; the current token on exit
197 /// will be either the EndOfStatement or EOF.
198 StringRef ParseStringToEndOfStatement();
199
Nico Weber4c4c7322011-01-28 03:04:41 +0000200 bool ParseAssignment(StringRef Name, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000201
202 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
203 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
204 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000205 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000206
207 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
208 /// and set \arg Res to the identifier contents.
209 bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000210
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000211 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000212
213 // ".ascii", ".asciiz", ".string"
214 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000215 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000216 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000217 bool ParseDirectiveFill(); // ".fill"
218 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000219 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000220 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000221 bool ParseDirectiveOrg(); // ".org"
222 // ".align{,32}", ".p2align{,w,l}"
223 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
224
225 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
226 /// accepts a single symbol (which should be a label or an external).
227 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000228
229 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
230
231 bool ParseDirectiveAbort(); // ".abort"
232 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000233 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000234
235 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000236 // ".ifdef" or ".ifndef", depending on expect_defined
237 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000238 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
239 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
240 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
241
242 /// ParseEscapedString - Parse the current token as a string which may include
243 /// escaped characters and return the string contents.
244 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000245
246 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
247 MCSymbolRefExpr::VariantKind Variant);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000248};
249
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000250/// \brief Generic implementations of directive handling, etc. which is shared
251/// (or the default, at least) for all assembler parser.
252class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000253 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
254 void AddDirectiveHandler(StringRef Directive) {
255 getParser().AddDirectiveHandler(this, Directive,
256 HandleDirective<GenericAsmParser, Handler>);
257 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000258public:
259 GenericAsmParser() {}
260
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000261 AsmParser &getParser() {
262 return (AsmParser&) this->MCAsmParserExtension::getParser();
263 }
264
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000265 virtual void Initialize(MCAsmParser &Parser) {
266 // Call the base implementation.
267 this->MCAsmParserExtension::Initialize(Parser);
268
269 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000274
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000275 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
277 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000278 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
279 ".cfi_startproc");
280 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
281 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000282 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
283 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
285 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
287 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000288 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
289 ".cfi_def_cfa_register");
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
291 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
293 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000294 AddDirectiveHandler<
295 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
296 AddDirectiveHandler<
297 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000298 AddDirectiveHandler<
299 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
300 AddDirectiveHandler<
301 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000302 AddDirectiveHandler<
303 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000304
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000305 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
307 ".macros_on");
308 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
309 ".macros_off");
310 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
311 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
312 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000313
314 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
315 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000316 }
317
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000318 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
319
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000320 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
321 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
322 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000323 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000324 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000325 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
326 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000327 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000328 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000329 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000330 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
331 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000332 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000333 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000334 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
335 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000336 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000337
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000338 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000339 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
340 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000341
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000342 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000343};
344
345}
346
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000347namespace llvm {
348
349extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000350extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000351extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000352
353}
354
Chris Lattneraaec2052010-01-19 19:46:13 +0000355enum { DEFAULT_ADDRSPACE = 0 };
356
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000357AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000358 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000359 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000360 GenericParser(new GenericAsmParser), PlatformParser(0),
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000361 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000362 // Save the old handler.
363 SavedDiagHandler = SrcMgr.getDiagHandler();
364 SavedDiagContext = SrcMgr.getDiagContext();
365 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000366 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000367 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000368
369 // Initialize the generic parser.
370 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000371
372 // Initialize the platform / file format parser.
373 //
374 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
375 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000376 if (_MAI.hasMicrosoftFastStdCallMangling()) {
377 PlatformParser = createCOFFAsmParser();
378 PlatformParser->Initialize(*this);
379 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000380 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000381 PlatformParser->Initialize(*this);
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000382 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000383 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000384 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000385 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000386}
387
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000388AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000389 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
390
391 // Destroy any macros.
392 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
393 ie = MacroMap.end(); it != ie; ++it)
394 delete it->getValue();
395
Daniel Dunbare4749702010-07-12 18:12:02 +0000396 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000397 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000398}
399
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000400void AsmParser::PrintMacroInstantiations() {
401 // Print the active macro instantiation stack.
402 for (std::vector<MacroInstantiation*>::const_reverse_iterator
403 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000404 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
405 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000406}
407
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000408bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000409 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000410 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000411 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000412 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000413 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000414}
415
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000416bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000417 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000418 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000419 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000420 return true;
421}
422
Sean Callananfd0b0282010-01-21 00:19:58 +0000423bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000424 std::string IncludedFile;
425 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000426 if (NewBuf == -1)
427 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000428
Sean Callananfd0b0282010-01-21 00:19:58 +0000429 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000430
Sean Callananfd0b0282010-01-21 00:19:58 +0000431 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000432
Sean Callananfd0b0282010-01-21 00:19:58 +0000433 return false;
434}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000435
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000436/// Process the specified .incbin file by seaching for it in the include paths
437/// then just emiting the byte contents of the file to the streamer. This
438/// returns true on failure.
439bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
440 std::string IncludedFile;
441 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
442 if (NewBuf == -1)
443 return true;
444
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000445 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000446 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
447 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000448 return false;
449}
450
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000451void AsmParser::JumpToLoc(SMLoc Loc) {
452 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
453 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
454}
455
Sean Callananfd0b0282010-01-21 00:19:58 +0000456const AsmToken &AsmParser::Lex() {
457 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000458
Sean Callananfd0b0282010-01-21 00:19:58 +0000459 if (tok->is(AsmToken::Eof)) {
460 // If this is the end of an included file, pop the parent file off the
461 // include stack.
462 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
463 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000464 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000465 tok = &Lexer.Lex();
466 }
467 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000468
Sean Callananfd0b0282010-01-21 00:19:58 +0000469 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000470 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000471
Sean Callananfd0b0282010-01-21 00:19:58 +0000472 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000473}
474
Chris Lattner79180e22010-04-05 23:15:42 +0000475bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000476 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000477 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000478 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000479
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000480 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000481 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000482
483 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000484 AsmCond StartingCondState = TheCondState;
485
Kevin Enderby613b7572011-11-01 22:27:22 +0000486 // If we are generating dwarf for assembly source files save the initial text
487 // section and generate a .file directive.
488 if (getContext().getGenDwarfForAssembly()) {
489 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000490 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
491 getStreamer().EmitLabel(SectionStartSym);
492 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000493 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
494 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
495 }
496
Chris Lattnerb717fb02009-07-02 21:53:43 +0000497 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000498 while (Lexer.isNot(AsmToken::Eof)) {
Chris Lattnerb717fb02009-07-02 21:53:43 +0000499 if (!ParseStatement()) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000500
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000501 // We had an error, validate that one was emitted and recover by skipping to
502 // the next line.
503 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000504 EatToEndOfStatement();
505 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000506
507 if (TheCondState.TheCond != StartingCondState.TheCond ||
508 TheCondState.Ignore != StartingCondState.Ignore)
509 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000510
511 // Check to see there are no empty DwarfFile slots.
512 const std::vector<MCDwarfFile *> &MCDwarfFiles =
513 getContext().getMCDwarfFiles();
514 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000515 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000516 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000517 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000518
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000519 // Check to see that all assembler local symbols were actually defined.
520 // Targets that don't do subsections via symbols may not want this, though,
521 // so conservatively exclude them. Only do this if we're finalizing, though,
522 // as otherwise we won't necessarilly have seen everything yet.
523 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
524 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
525 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
526 e = Symbols.end();
527 i != e; ++i) {
528 MCSymbol *Sym = i->getValue();
529 // Variable symbols may not be marked as defined, so check those
530 // explicitly. If we know it's a variable, we have a definition for
531 // the purposes of this check.
532 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
533 // FIXME: We would really like to refer back to where the symbol was
534 // first referenced for a source location. We need to add something
535 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000536 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
537 "assembler local symbol '" + Sym->getName() +
538 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000539 }
540 }
541
542
Chris Lattner79180e22010-04-05 23:15:42 +0000543 // Finalize the output stream if there are no errors and if the client wants
544 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000545 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000546 Out.Finish();
547
Chris Lattnerb717fb02009-07-02 21:53:43 +0000548 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000549}
550
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000551void AsmParser::CheckForValidSection() {
552 if (!getStreamer().getCurrentSection()) {
553 TokError("expected section directive before assembly directive");
554 Out.SwitchSection(Ctx.getMachOSection(
555 "__TEXT", "__text",
556 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
557 0, SectionKind::getText()));
558 }
559}
560
Chris Lattner2cf5f142009-06-22 01:29:09 +0000561/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
562void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000563 while (Lexer.isNot(AsmToken::EndOfStatement) &&
564 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000565 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000566
Chris Lattner2cf5f142009-06-22 01:29:09 +0000567 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000568 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000569 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000570}
571
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000572StringRef AsmParser::ParseStringToEndOfStatement() {
573 const char *Start = getTok().getLoc().getPointer();
574
575 while (Lexer.isNot(AsmToken::EndOfStatement) &&
576 Lexer.isNot(AsmToken::Eof))
577 Lex();
578
579 const char *End = getTok().getLoc().getPointer();
580 return StringRef(Start, End - Start);
581}
Chris Lattnerc4193832009-06-22 05:51:26 +0000582
Chris Lattner74ec1a32009-06-22 06:32:03 +0000583/// ParseParenExpr - Parse a paren expression and return it.
584/// NOTE: This assumes the leading '(' has already been consumed.
585///
586/// parenexpr ::= expr)
587///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000588bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000589 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000590 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000591 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000592 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000593 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000594 return false;
595}
Chris Lattnerc4193832009-06-22 05:51:26 +0000596
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000597/// ParseBracketExpr - Parse a bracket expression and return it.
598/// NOTE: This assumes the leading '[' has already been consumed.
599///
600/// bracketexpr ::= expr]
601///
602bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
603 if (ParseExpression(Res)) return true;
604 if (Lexer.isNot(AsmToken::RBrac))
605 return TokError("expected ']' in brackets expression");
606 EndLoc = Lexer.getLoc();
607 Lex();
608 return false;
609}
610
Chris Lattner74ec1a32009-06-22 06:32:03 +0000611/// ParsePrimaryExpr - Parse a primary expression and return it.
612/// primaryexpr ::= (parenexpr
613/// primaryexpr ::= symbol
614/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000615/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000616/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000617bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000618 switch (Lexer.getKind()) {
619 default:
620 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000621 // If we have an error assume that we've already handled it.
622 case AsmToken::Error:
623 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000624 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000625 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000626 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000627 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000628 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000629 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000630 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000631 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000632 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000633 EndLoc = Lexer.getLoc();
634
635 StringRef Identifier;
636 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000637 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000638
Daniel Dunbarfffff912009-10-16 01:34:54 +0000639 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000640 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000641 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000642
643 // Lookup the symbol variant if used.
644 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000645 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000646 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000647 if (Variant == MCSymbolRefExpr::VK_Invalid) {
648 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000649 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000650 }
651 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000652
Daniel Dunbarfffff912009-10-16 01:34:54 +0000653 // If this is an absolute variable reference, substitute it now to preserve
654 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000655 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000656 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000657 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000658
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000659 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000660 return false;
661 }
662
663 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000664 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000665 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000666 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000667 case AsmToken::Integer: {
668 SMLoc Loc = getTok().getLoc();
669 int64_t IntVal = getTok().getIntVal();
670 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000671 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000672 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000673 // Look for 'b' or 'f' following an Integer as a directional label
674 if (Lexer.getKind() == AsmToken::Identifier) {
675 StringRef IDVal = getTok().getString();
676 if (IDVal == "f" || IDVal == "b"){
677 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
678 IDVal == "f" ? 1 : 0);
679 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
680 getContext());
681 if(IDVal == "b" && Sym->isUndefined())
682 return Error(Loc, "invalid reference to undefined symbol");
683 EndLoc = Lexer.getLoc();
684 Lex(); // Eat identifier.
685 }
686 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000687 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000688 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000689 case AsmToken::Real: {
690 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000691 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000692 Res = MCConstantExpr::Create(IntVal, getContext());
693 Lex(); // Eat token.
694 return false;
695 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000696 case AsmToken::Dot: {
697 // This is a '.' reference, which references the current PC. Emit a
698 // temporary label to the streamer and refer to it.
699 MCSymbol *Sym = Ctx.CreateTempSymbol();
700 Out.EmitLabel(Sym);
701 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
702 EndLoc = Lexer.getLoc();
703 Lex(); // Eat identifier.
704 return false;
705 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000706 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000707 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000708 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000709 case AsmToken::LBrac:
710 if (!PlatformParser->HasBracketExpressions())
711 return TokError("brackets expression not supported on this target");
712 Lex(); // Eat the '['.
713 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000714 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000715 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000716 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000717 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000718 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000719 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000720 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000721 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000722 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000723 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000724 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000725 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000726 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000727 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000728 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000729 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000730 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000731 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000732 }
733}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000734
Chris Lattnerb4307b32010-01-15 19:28:38 +0000735bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000736 SMLoc EndLoc;
737 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000738}
739
Daniel Dunbarcceba832010-09-17 02:47:07 +0000740const MCExpr *
741AsmParser::ApplyModifierToExpr(const MCExpr *E,
742 MCSymbolRefExpr::VariantKind Variant) {
743 // Recurse over the given expression, rebuilding it to apply the given variant
744 // if there is exactly one symbol.
745 switch (E->getKind()) {
746 case MCExpr::Target:
747 case MCExpr::Constant:
748 return 0;
749
750 case MCExpr::SymbolRef: {
751 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
752
753 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
754 TokError("invalid variant on expression '" +
755 getTok().getIdentifier() + "' (already modified)");
756 return E;
757 }
758
759 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
760 }
761
762 case MCExpr::Unary: {
763 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
764 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
765 if (!Sub)
766 return 0;
767 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
768 }
769
770 case MCExpr::Binary: {
771 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
772 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
773 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
774
775 if (!LHS && !RHS)
776 return 0;
777
778 if (!LHS) LHS = BE->getLHS();
779 if (!RHS) RHS = BE->getRHS();
780
781 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
782 }
783 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000784
785 assert(0 && "Invalid expression kind!");
786 return 0;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000787}
788
Chris Lattner74ec1a32009-06-22 06:32:03 +0000789/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000790///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000791/// expr ::= expr &&,|| expr -> lowest.
792/// expr ::= expr |,^,&,! expr
793/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
794/// expr ::= expr <<,>> expr
795/// expr ::= expr +,- expr
796/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000797/// expr ::= primaryexpr
798///
Chris Lattner54482b42010-01-15 19:39:23 +0000799bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000800 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000801 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000802 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
803 return true;
804
Daniel Dunbarcceba832010-09-17 02:47:07 +0000805 // As a special case, we support 'a op b @ modifier' by rewriting the
806 // expression to include the modifier. This is inefficient, but in general we
807 // expect users to use 'a@modifier op b'.
808 if (Lexer.getKind() == AsmToken::At) {
809 Lex();
810
811 if (Lexer.isNot(AsmToken::Identifier))
812 return TokError("unexpected symbol modifier following '@'");
813
814 MCSymbolRefExpr::VariantKind Variant =
815 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
816 if (Variant == MCSymbolRefExpr::VK_Invalid)
817 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
818
819 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
820 if (!ModifiedRes) {
821 return TokError("invalid modifier '" + getTok().getIdentifier() +
822 "' (no symbols present)");
823 return true;
824 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000825
Daniel Dunbarcceba832010-09-17 02:47:07 +0000826 Res = ModifiedRes;
827 Lex();
828 }
829
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000830 // Try to constant fold it up front, if possible.
831 int64_t Value;
832 if (Res->EvaluateAsAbsolute(Value))
833 Res = MCConstantExpr::Create(Value, getContext());
834
835 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000836}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000837
Chris Lattnerb4307b32010-01-15 19:28:38 +0000838bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000839 Res = 0;
840 return ParseParenExpr(Res, EndLoc) ||
841 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000842}
843
Daniel Dunbar475839e2009-06-29 20:37:27 +0000844bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000845 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000846
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000847 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000848 if (ParseExpression(Expr))
849 return true;
850
Daniel Dunbare00b0112009-10-16 01:57:52 +0000851 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000852 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000853
854 return false;
855}
856
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000857static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000858 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000859 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000860 default:
861 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000862
Jim Grosbachfbe16812011-08-20 16:24:13 +0000863 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000864 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000865 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000866 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000867 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000868 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000869 return 1;
870
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000871
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000872 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000873 //
874 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000875 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000876 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000877 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000878 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000879 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000880 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000881 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000882 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000883 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000884
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000885 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000886 case AsmToken::EqualEqual:
887 Kind = MCBinaryExpr::EQ;
888 return 3;
889 case AsmToken::ExclaimEqual:
890 case AsmToken::LessGreater:
891 Kind = MCBinaryExpr::NE;
892 return 3;
893 case AsmToken::Less:
894 Kind = MCBinaryExpr::LT;
895 return 3;
896 case AsmToken::LessEqual:
897 Kind = MCBinaryExpr::LTE;
898 return 3;
899 case AsmToken::Greater:
900 Kind = MCBinaryExpr::GT;
901 return 3;
902 case AsmToken::GreaterEqual:
903 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000904 return 3;
905
Jim Grosbachfbe16812011-08-20 16:24:13 +0000906 // Intermediate Precedence: <<, >>
907 case AsmToken::LessLess:
908 Kind = MCBinaryExpr::Shl;
909 return 4;
910 case AsmToken::GreaterGreater:
911 Kind = MCBinaryExpr::Shr;
912 return 4;
913
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000914 // High Intermediate Precedence: +, -
915 case AsmToken::Plus:
916 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000917 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000918 case AsmToken::Minus:
919 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000920 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000921
Jim Grosbachfbe16812011-08-20 16:24:13 +0000922 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +0000923 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000924 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000925 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000926 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000927 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000928 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000929 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000930 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000931 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000932 }
933}
934
935
936/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
937/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000938bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
939 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000940 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000941 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000942 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000943
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000944 // If the next token is lower precedence than we are allowed to eat, return
945 // successfully with what we ate already.
946 if (TokPrec < Precedence)
947 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000948
Sean Callanan79ed1a82010-01-19 20:22:31 +0000949 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000950
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000951 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000952 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +0000953 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000954
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000955 // If BinOp binds less tightly with RHS than the operator after RHS, let
956 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000957 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000958 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000959 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +0000960 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000961 }
962
Daniel Dunbar475839e2009-06-29 20:37:27 +0000963 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000964 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000965 }
966}
967
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000968
969
970
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000971/// ParseStatement:
972/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +0000973/// ::= Label* Directive ...Operands... EndOfStatement
974/// ::= Label* Identifier OperandList* EndOfStatement
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000975bool AsmParser::ParseStatement() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000976 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +0000977 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000978 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000979 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000980 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000981
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +0000982 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +0000983 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +0000984 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000985 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000986 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +0000987 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000988 if (Lexer.is(AsmToken::Hash))
989 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +0000990
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +0000991 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000992 if (Lexer.is(AsmToken::Integer)) {
993 LocalLabelVal = getTok().getIntVal();
994 if (LocalLabelVal < 0) {
995 if (!TheCondState.Ignore)
996 return TokError("unexpected token at start of statement");
997 IDVal = "";
998 }
999 else {
1000 IDVal = getTok().getString();
1001 Lex(); // Consume the integer token to be used as an identifier token.
1002 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001003 if (!TheCondState.Ignore)
1004 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001005 }
1006 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001007
1008 } else if (Lexer.is(AsmToken::Dot)) {
1009 // Treat '.' as a valid identifier in this context.
1010 Lex();
1011 IDVal = ".";
1012
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001013 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001014 if (!TheCondState.Ignore)
1015 return TokError("unexpected token at start of statement");
1016 IDVal = "";
1017 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001018
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001019
Chris Lattner7834fac2010-04-17 18:14:27 +00001020 // Handle conditional assembly here before checking for skipping. We
1021 // have to do this so that .endif isn't skipped in a ".if 0" block for
1022 // example.
1023 if (IDVal == ".if")
1024 return ParseDirectiveIf(IDLoc);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001025 if (IDVal == ".ifdef")
1026 return ParseDirectiveIfdef(IDLoc, true);
1027 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1028 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001029 if (IDVal == ".elseif")
1030 return ParseDirectiveElseIf(IDLoc);
1031 if (IDVal == ".else")
1032 return ParseDirectiveElse(IDLoc);
1033 if (IDVal == ".endif")
1034 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001035
Chris Lattner7834fac2010-04-17 18:14:27 +00001036 // If we are in a ".if 0" block, ignore this statement.
1037 if (TheCondState.Ignore) {
1038 EatToEndOfStatement();
1039 return false;
1040 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001041
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001042 // FIXME: Recurse on local labels?
1043
1044 // See what kind of statement we have.
1045 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001046 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001047 CheckForValidSection();
1048
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001049 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001050 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001051
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001052 // Diagnose attempt to use '.' as a label.
1053 if (IDVal == ".")
1054 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1055
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001056 // Diagnose attempt to use a variable as a label.
1057 //
1058 // FIXME: Diagnostics. Note the location of the definition as a label.
1059 // FIXME: This doesn't diagnose assignment to a symbol which has been
1060 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001061 MCSymbol *Sym;
1062 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001063 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001064 else
1065 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001066 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001067 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001068
Daniel Dunbar959fd882009-08-26 22:13:22 +00001069 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001070 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001071
Kevin Enderby94c2e852011-12-09 18:09:40 +00001072 // If we are generating dwarf for assembly source files then gather the
1073 // info to make a dwarf subprogram entry for this label if needed.
1074 if (getContext().getGenDwarfForAssembly())
1075 MCGenDwarfSubprogramEntry::Make(Sym, &getStreamer(), getSourceManager(),
1076 IDLoc);
1077
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001078 // Consume any end of statement token, if present, to avoid spurious
1079 // AddBlankLine calls().
1080 if (Lexer.is(AsmToken::EndOfStatement)) {
1081 Lex();
1082 if (Lexer.is(AsmToken::Eof))
1083 return false;
1084 }
1085
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001086 return ParseStatement();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001087 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001088
Daniel Dunbar3f872332009-07-28 16:08:33 +00001089 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001090 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001091 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001092
Nico Weber4c4c7322011-01-28 03:04:41 +00001093 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001094
1095 default: // Normal instruction or directive.
1096 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001097 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001098
1099 // If macros are enabled, check to see if this is a macro instantiation.
1100 if (MacrosEnabled)
1101 if (const Macro *M = MacroMap.lookup(IDVal))
1102 return HandleMacroEntry(IDVal, IDLoc, M);
1103
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001104 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001105 if (IDVal[0] == '.' && IDVal != ".") {
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001106 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001107 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001108 return ParseDirectiveSet(IDVal, true);
1109 if (IDVal == ".equiv")
1110 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001111
Daniel Dunbara0d14262009-06-24 23:30:00 +00001112 // Data directives
1113
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001114 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001115 return ParseDirectiveAscii(IDVal, false);
1116 if (IDVal == ".asciz" || IDVal == ".string")
1117 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001118
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001119 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001120 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001121 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001122 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001123 if (IDVal == ".value")
1124 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001125 if (IDVal == ".2byte")
1126 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001127 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001128 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001129 if (IDVal == ".int")
1130 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001131 if (IDVal == ".4byte")
1132 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001133 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001134 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001135 if (IDVal == ".8byte")
1136 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001137 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001138 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1139 if (IDVal == ".double")
1140 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001141
Eli Friedman5d68ec22010-07-19 04:17:25 +00001142 if (IDVal == ".align") {
1143 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1144 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1145 }
1146 if (IDVal == ".align32") {
1147 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1148 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1149 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001150 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001151 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001152 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001153 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001154 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001155 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001156 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001157 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001158 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001159 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001160 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001161 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1162
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001163 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001164 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001165
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001166 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001167 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001168 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001169 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001170 if (IDVal == ".zero")
1171 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001172
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001173 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001174
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001175 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001176 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001177 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001178 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001179 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001180 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001181 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001182 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001183 if (IDVal == ".symbol_resolver")
1184 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001185 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001186 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001187 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001188 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001189 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001190 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001191 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001192 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001193 if (IDVal == ".weak_def_can_be_hidden")
1194 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001195
Hans Wennborg5cc64912011-06-18 13:51:54 +00001196 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001197 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001198 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001199 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001200
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001201 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001202 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001203 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001204 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001205 if (IDVal == ".incbin")
1206 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001207
Evan Chengbd27f5a2011-07-27 00:38:12 +00001208 if (IDVal == ".code16")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001209 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001210
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001211 // Look up the handler in the handler table.
1212 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1213 DirectiveMap.lookup(IDVal);
1214 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001215 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001216
Kevin Enderby9c656452009-09-10 20:51:44 +00001217 // Target hook for parsing target specific directives.
1218 if (!getTargetParser().ParseDirective(ID))
1219 return false;
1220
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +00001221 bool retval = Warning(IDLoc, "ignoring directive for now");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001222 EatToEndOfStatement();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +00001223 return retval;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001224 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001225
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001226 CheckForValidSection();
1227
Chris Lattnera7f13542010-05-19 23:34:33 +00001228 // Canonicalize the opcode to lower case.
1229 SmallString<128> Opcode;
1230 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1231 Opcode.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001232
Chris Lattner98986712010-01-14 22:21:20 +00001233 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
Chris Lattnera7f13542010-05-19 23:34:33 +00001234 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001235 ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001236
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001237 // Dump the parsed representation, if requested.
1238 if (getShowParsedOperands()) {
1239 SmallString<256> Str;
1240 raw_svector_ostream OS(Str);
1241 OS << "parsed instruction: [";
1242 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1243 if (i != 0)
1244 OS << ", ";
Jim Grosbachb7f689b2011-07-13 15:34:57 +00001245 ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001246 }
1247 OS << "]";
1248
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001249 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001250 }
1251
Kevin Enderby613b7572011-11-01 22:27:22 +00001252 // If we are generating dwarf for assembly source files and the current
1253 // section is the initial text section then generate a .loc directive for
1254 // the instruction.
1255 if (!HadError && getContext().getGenDwarfForAssembly() &&
1256 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1257 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1258 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1259 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001260 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001261 StringRef());
1262 }
1263
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001264 // If parsing succeeded, match the instruction.
Chris Lattner7036f8b2010-09-29 01:42:58 +00001265 if (!HadError)
1266 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1267 Out);
Chris Lattner98986712010-01-14 22:21:20 +00001268
Chris Lattner98986712010-01-14 22:21:20 +00001269 // Free any parsed operands.
1270 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1271 delete ParsedOperands[i];
1272
Chris Lattnercbf8a982010-09-11 16:18:25 +00001273 // Don't skip the rest of the line, the instruction parser is responsible for
1274 // that.
1275 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001276}
Chris Lattner9a023f72009-06-24 04:43:34 +00001277
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001278/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1279/// since they may not be able to be tokenized to get to the end of line token.
1280void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001281 if (!Lexer.is(AsmToken::EndOfStatement))
1282 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001283 // Eat EOL.
1284 Lex();
1285}
1286
1287/// ParseCppHashLineFilenameComment as this:
1288/// ::= # number "filename"
1289/// or just as a full line comment if it doesn't have a number and a string.
1290bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1291 Lex(); // Eat the hash token.
1292
1293 if (getLexer().isNot(AsmToken::Integer)) {
1294 // Consume the line since in cases it is not a well-formed line directive,
1295 // as if were simply a full line comment.
1296 EatToEndOfLine();
1297 return false;
1298 }
1299
1300 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001301 Lex();
1302
1303 if (getLexer().isNot(AsmToken::String)) {
1304 EatToEndOfLine();
1305 return false;
1306 }
1307
1308 StringRef Filename = getTok().getString();
1309 // Get rid of the enclosing quotes.
1310 Filename = Filename.substr(1, Filename.size()-2);
1311
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001312 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1313 CppHashLoc = L;
1314 CppHashFilename = Filename;
1315 CppHashLineNumber = LineNumber;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001316
1317 // Ignore any trailing characters, they're just comment.
1318 EatToEndOfLine();
1319 return false;
1320}
1321
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001322/// DiagHandler - will use the the last parsed cpp hash line filename comment
1323/// for the Filename and LineNo if any in the diagnostic.
1324void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1325 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1326 raw_ostream &OS = errs();
1327
1328 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1329 const SMLoc &DiagLoc = Diag.getLoc();
1330 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1331 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1332
1333 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1334 // before printing the message.
1335 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001336 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001337 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1338 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1339 }
1340
1341 // If we have not parsed a cpp hash line filename comment or the source
1342 // manager changed or buffer changed (like in a nested include) then just
1343 // print the normal diagnostic using its Filename and LineNo.
1344 if (!Parser->CppHashLineNumber ||
1345 &DiagSrcMgr != &Parser->SrcMgr ||
1346 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001347 if (Parser->SavedDiagHandler)
1348 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1349 else
1350 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001351 return;
1352 }
1353
1354 // Use the CppHashFilename and calculate a line number based on the
1355 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1356 // the diagnostic.
1357 const std::string Filename = Parser->CppHashFilename;
1358
1359 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1360 int CppHashLocLineNo =
1361 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1362 int LineNo = Parser->CppHashLineNumber - 1 +
1363 (DiagLocLineNo - CppHashLocLineNo);
1364
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001365 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1366 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001367 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001368 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001369
Benjamin Kramer04a04262011-10-16 10:48:29 +00001370 if (Parser->SavedDiagHandler)
1371 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1372 else
1373 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001374}
1375
Rafael Espindola65366442011-06-05 02:43:45 +00001376bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1377 const std::vector<StringRef> &Parameters,
1378 const std::vector<std::vector<AsmToken> > &A,
1379 const SMLoc &L) {
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001380 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001381 unsigned NParameters = Parameters.size();
1382 if (NParameters != 0 && NParameters != A.size())
1383 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001384
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001385 while (!Body.empty()) {
1386 // Scan for the next substitution.
1387 std::size_t End = Body.size(), Pos = 0;
1388 for (; Pos != End; ++Pos) {
1389 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001390 if (!NParameters) {
1391 // This macro has no parameters, look for $0, $1, etc.
1392 if (Body[Pos] != '$' || Pos + 1 == End)
1393 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001394
Rafael Espindola65366442011-06-05 02:43:45 +00001395 char Next = Body[Pos + 1];
1396 if (Next == '$' || Next == 'n' || isdigit(Next))
1397 break;
1398 } else {
1399 // This macro has parameters, look for \foo, \bar, etc.
1400 if (Body[Pos] == '\\' && Pos + 1 != End)
1401 break;
1402 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001403 }
1404
1405 // Add the prefix.
1406 OS << Body.slice(0, Pos);
1407
1408 // Check if we reached the end.
1409 if (Pos == End)
1410 break;
1411
Rafael Espindola65366442011-06-05 02:43:45 +00001412 if (!NParameters) {
1413 switch (Body[Pos+1]) {
1414 // $$ => $
1415 case '$':
1416 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001417 break;
1418
Rafael Espindola65366442011-06-05 02:43:45 +00001419 // $n => number of arguments
1420 case 'n':
1421 OS << A.size();
1422 break;
1423
1424 // $[0-9] => argument
1425 default: {
1426 // Missing arguments are ignored.
1427 unsigned Index = Body[Pos+1] - '0';
1428 if (Index >= A.size())
1429 break;
1430
1431 // Otherwise substitute with the token values, with spaces eliminated.
1432 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1433 ie = A[Index].end(); it != ie; ++it)
1434 OS << it->getString();
1435 break;
1436 }
1437 }
1438 Pos += 2;
1439 } else {
1440 unsigned I = Pos + 1;
1441 while (isalnum(Body[I]) && I + 1 != End)
1442 ++I;
1443
1444 const char *Begin = Body.data() + Pos +1;
1445 StringRef Argument(Begin, I - (Pos +1));
1446 unsigned Index = 0;
1447 for (; Index < NParameters; ++Index)
1448 if (Parameters[Index] == Argument)
1449 break;
1450
1451 // FIXME: We should error at the macro definition.
1452 if (Index == NParameters)
1453 return Error(L, "Parameter not found");
1454
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001455 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1456 ie = A[Index].end(); it != ie; ++it)
1457 OS << it->getString();
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001458
Rafael Espindola65366442011-06-05 02:43:45 +00001459 Pos += 1 + Argument.size();
1460 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001461 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001462 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001463 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001464
1465 // We include the .endmacro in the buffer as our queue to exit the macro
1466 // instantiation.
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001467 OS << ".endmacro\n";
Rafael Espindola65366442011-06-05 02:43:45 +00001468 return false;
1469}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001470
Rafael Espindola65366442011-06-05 02:43:45 +00001471MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1472 MemoryBuffer *I)
1473 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1474{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001475}
1476
1477bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1478 const Macro *M) {
1479 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1480 // this, although we should protect against infinite loops.
1481 if (ActiveMacros.size() == 20)
1482 return TokError("macros cannot be nested more than 20 levels deep");
1483
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001484 // Parse the macro instantiation arguments.
1485 std::vector<std::vector<AsmToken> > MacroArguments;
1486 MacroArguments.push_back(std::vector<AsmToken>());
1487 unsigned ParenLevel = 0;
1488 for (;;) {
1489 if (Lexer.is(AsmToken::Eof))
1490 return TokError("unexpected token in macro instantiation");
1491 if (Lexer.is(AsmToken::EndOfStatement))
1492 break;
1493
1494 // If we aren't inside parentheses and this is a comma, start a new token
1495 // list.
1496 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1497 MacroArguments.push_back(std::vector<AsmToken>());
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001498 } else {
Daniel Dunbare25c6b92010-08-10 17:38:52 +00001499 // Adjust the current parentheses level.
1500 if (Lexer.is(AsmToken::LParen))
1501 ++ParenLevel;
1502 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1503 --ParenLevel;
1504
1505 // Append the token to the current argument list.
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001506 MacroArguments.back().push_back(getTok());
1507 }
1508 Lex();
1509 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001510
Rafael Espindola65366442011-06-05 02:43:45 +00001511 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1512 // to hold the macro body with substitutions.
1513 SmallString<256> Buf;
1514 StringRef Body = M->Body;
1515
1516 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1517 return true;
1518
1519 MemoryBuffer *Instantiation =
1520 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1521
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001522 // Create the macro instantiation object and add to the current macro
1523 // instantiation stack.
1524 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001525 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001526 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001527 ActiveMacros.push_back(MI);
1528
1529 // Jump to the macro instantiation and prime the lexer.
1530 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1531 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1532 Lex();
1533
1534 return false;
1535}
1536
1537void AsmParser::HandleMacroExit() {
1538 // Jump to the EndOfStatement we should return to, and consume it.
1539 JumpToLoc(ActiveMacros.back()->ExitLoc);
1540 Lex();
1541
1542 // Pop the instantiation entry.
1543 delete ActiveMacros.back();
1544 ActiveMacros.pop_back();
1545}
1546
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001547static void MarkUsed(const MCExpr *Value) {
1548 switch (Value->getKind()) {
1549 case MCExpr::Binary:
1550 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1551 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1552 break;
1553 case MCExpr::Target:
1554 case MCExpr::Constant:
1555 break;
1556 case MCExpr::SymbolRef: {
1557 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1558 break;
1559 }
1560 case MCExpr::Unary:
1561 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1562 break;
1563 }
1564}
1565
Nico Weber4c4c7322011-01-28 03:04:41 +00001566bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001567 // FIXME: Use better location, we should use proper tokens.
1568 SMLoc EqualLoc = Lexer.getLoc();
1569
Daniel Dunbar821e3332009-08-31 08:09:28 +00001570 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001571 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001572 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001573
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001574 MarkUsed(Value);
1575
Daniel Dunbar3f872332009-07-28 16:08:33 +00001576 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001577 return TokError("unexpected token in assignment");
1578
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001579 // Error on assignment to '.'.
1580 if (Name == ".") {
1581 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1582 "(use '.space' or '.org').)"));
1583 }
1584
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001585 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001586 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001587
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001588 // Validate that the LHS is allowed to be a variable (either it has not been
1589 // used as a symbol, or it is an absolute symbol).
1590 MCSymbol *Sym = getContext().LookupSymbol(Name);
1591 if (Sym) {
1592 // Diagnose assignment to a label.
1593 //
1594 // FIXME: Diagnostics. Note the location of the definition as a label.
1595 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001596 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001597 ; // Allow redefinitions of undefined symbols only used in directives.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001598 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001599 return Error(EqualLoc, "redefinition of '" + Name + "'");
1600 else if (!Sym->isVariable())
1601 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001602 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001603 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1604 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001605
1606 // Don't count these checks as uses.
1607 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001608 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001609 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001610
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001611 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001612
1613 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001614 Out.EmitAssignment(Sym, Value);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001615
1616 return false;
1617}
1618
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001619/// ParseIdentifier:
1620/// ::= identifier
1621/// ::= string
1622bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001623 // The assembler has relaxed rules for accepting identifiers, in particular we
1624 // allow things like '.globl $foo', which would normally be separate
1625 // tokens. At this level, we have already lexed so we cannot (currently)
1626 // handle this as a context dependent token, instead we detect adjacent tokens
1627 // and return the combined identifier.
1628 if (Lexer.is(AsmToken::Dollar)) {
1629 SMLoc DollarLoc = getLexer().getLoc();
1630
1631 // Consume the dollar sign, and check for a following identifier.
1632 Lex();
1633 if (Lexer.isNot(AsmToken::Identifier))
1634 return true;
1635
1636 // We have a '$' followed by an identifier, make sure they are adjacent.
1637 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1638 return true;
1639
1640 // Construct the joined identifier and consume the token.
1641 Res = StringRef(DollarLoc.getPointer(),
1642 getTok().getIdentifier().size() + 1);
1643 Lex();
1644 return false;
1645 }
1646
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001647 if (Lexer.isNot(AsmToken::Identifier) &&
1648 Lexer.isNot(AsmToken::String))
1649 return true;
1650
Sean Callanan18b83232010-01-19 21:44:56 +00001651 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001652
Sean Callanan79ed1a82010-01-19 20:22:31 +00001653 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001654
1655 return false;
1656}
1657
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001658/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001659/// ::= .equ identifier ',' expression
1660/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001661/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001662bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001663 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001664
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001665 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001666 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001667
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001668 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001669 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001670 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001671
Nico Weber4c4c7322011-01-28 03:04:41 +00001672 return ParseAssignment(Name, allow_redef);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001673}
1674
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001675bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001676 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001677
1678 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00001679 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001680 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1681 if (Str[i] != '\\') {
1682 Data += Str[i];
1683 continue;
1684 }
1685
1686 // Recognize escaped characters. Note that this escape semantics currently
1687 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1688 ++i;
1689 if (i == e)
1690 return TokError("unexpected backslash at end of string");
1691
1692 // Recognize octal sequences.
1693 if ((unsigned) (Str[i] - '0') <= 7) {
1694 // Consume up to three octal characters.
1695 unsigned Value = Str[i] - '0';
1696
1697 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1698 ++i;
1699 Value = Value * 8 + (Str[i] - '0');
1700
1701 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1702 ++i;
1703 Value = Value * 8 + (Str[i] - '0');
1704 }
1705 }
1706
1707 if (Value > 255)
1708 return TokError("invalid octal escape sequence (out of range)");
1709
1710 Data += (unsigned char) Value;
1711 continue;
1712 }
1713
1714 // Otherwise recognize individual escapes.
1715 switch (Str[i]) {
1716 default:
1717 // Just reject invalid escape sequences for now.
1718 return TokError("invalid escape sequence (unrecognized character)");
1719
1720 case 'b': Data += '\b'; break;
1721 case 'f': Data += '\f'; break;
1722 case 'n': Data += '\n'; break;
1723 case 'r': Data += '\r'; break;
1724 case 't': Data += '\t'; break;
1725 case '"': Data += '"'; break;
1726 case '\\': Data += '\\'; break;
1727 }
1728 }
1729
1730 return false;
1731}
1732
Daniel Dunbara0d14262009-06-24 23:30:00 +00001733/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00001734/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1735bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001736 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001737 CheckForValidSection();
1738
Daniel Dunbara0d14262009-06-24 23:30:00 +00001739 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001740 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00001741 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001742
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001743 std::string Data;
1744 if (ParseEscapedString(Data))
1745 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001746
1747 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001748 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001749 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1750
Sean Callanan79ed1a82010-01-19 20:22:31 +00001751 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001752
1753 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001754 break;
1755
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001756 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00001757 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001758 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001759 }
1760 }
1761
Sean Callanan79ed1a82010-01-19 20:22:31 +00001762 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001763 return false;
1764}
1765
1766/// ParseDirectiveValue
1767/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1768bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001769 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001770 CheckForValidSection();
1771
Daniel Dunbara0d14262009-06-24 23:30:00 +00001772 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00001773 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00001774 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00001775 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001776 return true;
1777
Daniel Dunbar414c0c42010-05-23 18:36:38 +00001778 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00001779 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1780 assert(Size <= 8 && "Invalid size");
1781 uint64_t IntValue = MCE->getValue();
1782 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1783 return Error(ExprLoc, "literal value out of range for directive");
1784 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1785 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001786 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001787
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001788 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001789 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001790
Daniel Dunbara0d14262009-06-24 23:30:00 +00001791 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001792 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001793 return TokError("unexpected token in 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
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001802/// ParseDirectiveRealValue
1803/// ::= (.single | .double) [ expression (, expression)* ]
1804bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1805 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1806 CheckForValidSection();
1807
1808 for (;;) {
1809 // We don't truly support arithmetic on floating point expressions, so we
1810 // have to manually parse unary prefixes.
1811 bool IsNeg = false;
1812 if (getLexer().is(AsmToken::Minus)) {
1813 Lex();
1814 IsNeg = true;
1815 } else if (getLexer().is(AsmToken::Plus))
1816 Lex();
1817
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001818 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00001819 getLexer().isNot(AsmToken::Real) &&
1820 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001821 return TokError("unexpected token in directive");
1822
1823 // Convert to an APFloat.
1824 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00001825 StringRef IDVal = getTok().getString();
1826 if (getLexer().is(AsmToken::Identifier)) {
1827 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1828 Value = APFloat::getInf(Semantics);
1829 else if (!IDVal.compare_lower("nan"))
1830 Value = APFloat::getNaN(Semantics, false, ~0);
1831 else
1832 return TokError("invalid floating point literal");
1833 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001834 APFloat::opInvalidOp)
1835 return TokError("invalid floating point literal");
1836 if (IsNeg)
1837 Value.changeSign();
1838
1839 // Consume the numeric token.
1840 Lex();
1841
1842 // Emit the value as an integer.
1843 APInt AsInt = Value.bitcastToAPInt();
1844 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1845 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1846
1847 if (getLexer().is(AsmToken::EndOfStatement))
1848 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001849
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001850 if (getLexer().isNot(AsmToken::Comma))
1851 return TokError("unexpected token in directive");
1852 Lex();
1853 }
1854 }
1855
1856 Lex();
1857 return false;
1858}
1859
Daniel Dunbara0d14262009-06-24 23:30:00 +00001860/// ParseDirectiveSpace
1861/// ::= .space expression [ , expression ]
1862bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001863 CheckForValidSection();
1864
Daniel Dunbara0d14262009-06-24 23:30:00 +00001865 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001866 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001867 return true;
1868
1869 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001870 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1871 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001872 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001873 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001874
Daniel Dunbar475839e2009-06-29 20:37:27 +00001875 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001876 return true;
1877
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001878 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001879 return TokError("unexpected token in '.space' directive");
1880 }
1881
Sean Callanan79ed1a82010-01-19 20:22:31 +00001882 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001883
1884 if (NumBytes <= 0)
1885 return TokError("invalid number of bytes in '.space' directive");
1886
1887 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001888 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001889
1890 return false;
1891}
1892
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001893/// ParseDirectiveZero
1894/// ::= .zero expression
1895bool AsmParser::ParseDirectiveZero() {
1896 CheckForValidSection();
1897
1898 int64_t NumBytes;
1899 if (ParseAbsoluteExpression(NumBytes))
1900 return true;
1901
Rafael Espindolae452b172010-10-05 19:42:57 +00001902 int64_t Val = 0;
1903 if (getLexer().is(AsmToken::Comma)) {
1904 Lex();
1905 if (ParseAbsoluteExpression(Val))
1906 return true;
1907 }
1908
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001909 if (getLexer().isNot(AsmToken::EndOfStatement))
1910 return TokError("unexpected token in '.zero' directive");
1911
1912 Lex();
1913
Rafael Espindolae452b172010-10-05 19:42:57 +00001914 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001915
1916 return false;
1917}
1918
Daniel Dunbara0d14262009-06-24 23:30:00 +00001919/// ParseDirectiveFill
1920/// ::= .fill expression , expression , expression
1921bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001922 CheckForValidSection();
1923
Daniel Dunbara0d14262009-06-24 23:30:00 +00001924 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001925 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001926 return true;
1927
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001928 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001929 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001930 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001931
Daniel Dunbara0d14262009-06-24 23:30:00 +00001932 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001933 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001934 return true;
1935
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001936 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001937 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001938 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001939
Daniel Dunbara0d14262009-06-24 23:30:00 +00001940 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001941 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001942 return true;
1943
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001944 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001945 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001946
Sean Callanan79ed1a82010-01-19 20:22:31 +00001947 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001948
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00001949 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1950 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00001951
1952 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001953 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001954
1955 return false;
1956}
Daniel Dunbarc238b582009-06-25 22:44:51 +00001957
1958/// ParseDirectiveOrg
1959/// ::= .org expression [ , expression ]
1960bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001961 CheckForValidSection();
1962
Daniel Dunbar821e3332009-08-31 08:09:28 +00001963 const MCExpr *Offset;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001964 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001965 return true;
1966
1967 // Parse optional fill expression.
1968 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001969 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1970 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001971 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001972 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001973
Daniel Dunbar475839e2009-06-29 20:37:27 +00001974 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001975 return true;
1976
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001977 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001978 return TokError("unexpected token in '.org' directive");
1979 }
1980
Sean Callanan79ed1a82010-01-19 20:22:31 +00001981 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001982
1983 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1984 // has to be relative to the current section.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001985 getStreamer().EmitValueToOffset(Offset, FillExpr);
Daniel Dunbarc238b582009-06-25 22:44:51 +00001986
1987 return false;
1988}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001989
1990/// ParseDirectiveAlign
1991/// ::= {.align, ...} expression [ , expression [ , expression ]]
1992bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001993 CheckForValidSection();
1994
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001995 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001996 int64_t Alignment;
1997 if (ParseAbsoluteExpression(Alignment))
1998 return true;
1999
2000 SMLoc MaxBytesLoc;
2001 bool HasFillExpr = false;
2002 int64_t FillExpr = 0;
2003 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002004 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2005 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002006 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002007 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002008
2009 // The fill expression can be omitted while specifying a maximum number of
2010 // alignment bytes, e.g:
2011 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002012 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002013 HasFillExpr = true;
2014 if (ParseAbsoluteExpression(FillExpr))
2015 return true;
2016 }
2017
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002018 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2019 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002020 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002021 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002022
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002023 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002024 if (ParseAbsoluteExpression(MaxBytesToFill))
2025 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002026
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002027 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002028 return TokError("unexpected token in directive");
2029 }
2030 }
2031
Sean Callanan79ed1a82010-01-19 20:22:31 +00002032 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002033
Daniel Dunbar648ac512010-05-17 21:54:30 +00002034 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002035 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002036
2037 // Compute alignment in bytes.
2038 if (IsPow2) {
2039 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002040 if (Alignment >= 32) {
2041 Error(AlignmentLoc, "invalid alignment value");
2042 Alignment = 31;
2043 }
2044
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002045 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002046 }
2047
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002048 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002049 if (MaxBytesLoc.isValid()) {
2050 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002051 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2052 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002053 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002054 }
2055
2056 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002057 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2058 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002059 MaxBytesToFill = 0;
2060 }
2061 }
2062
Daniel Dunbar648ac512010-05-17 21:54:30 +00002063 // Check whether we should use optimal code alignment for this .align
2064 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002065 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002066 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2067 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002068 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002069 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002070 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002071 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2072 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002073 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002074
2075 return false;
2076}
2077
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002078/// ParseDirectiveSymbolAttribute
2079/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002080bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002081 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002082 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002083 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002084 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002085
2086 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002087 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002088
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002089 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002090
Jim Grosbach10ec6502011-09-15 17:56:49 +00002091 // Assembler local symbols don't make any sense here. Complain loudly.
2092 if (Sym->isTemporary())
2093 return Error(Loc, "non-local symbol required in directive");
2094
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002095 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002096
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002097 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002098 break;
2099
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002100 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002101 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002102 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002103 }
2104 }
2105
Sean Callanan79ed1a82010-01-19 20:22:31 +00002106 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002107 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002108}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002109
2110/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002111/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2112bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002113 CheckForValidSection();
2114
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002115 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002116 StringRef Name;
2117 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002118 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002119
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002120 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002121 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002122
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002123 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002124 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002125 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002126
2127 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002128 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002129 if (ParseAbsoluteExpression(Size))
2130 return true;
2131
2132 int64_t Pow2Alignment = 0;
2133 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002134 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002135 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002136 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002137 if (ParseAbsoluteExpression(Pow2Alignment))
2138 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002139
Chris Lattner258281d2010-01-19 06:22:22 +00002140 // If this target takes alignments in bytes (not log) validate and convert.
2141 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2142 if (!isPowerOf2_64(Pow2Alignment))
2143 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2144 Pow2Alignment = Log2_64(Pow2Alignment);
2145 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002146 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002147
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002148 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002149 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002150
Sean Callanan79ed1a82010-01-19 20:22:31 +00002151 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002152
Chris Lattner1fc3d752009-07-09 17:25:12 +00002153 // NOTE: a size of zero for a .comm should create a undefined symbol
2154 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002155 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002156 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2157 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002158
Eric Christopherc260a3e2010-05-14 01:38:54 +00002159 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002160 // may internally end up wanting an alignment in bytes.
2161 // FIXME: Diagnose overflow.
2162 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002163 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2164 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002165
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002166 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002167 return Error(IDLoc, "invalid symbol redefinition");
2168
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002169 // '.lcomm' is equivalent to '.zerofill'.
Chris Lattner1fc3d752009-07-09 17:25:12 +00002170 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002171 if (IsLocal) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002172 getStreamer().EmitZerofill(Ctx.getMachOSection(
2173 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2174 0, SectionKind::getBSS()),
2175 Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002176 return false;
2177 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002178
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002179 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002180 return false;
2181}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002182
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002183/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002184/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002185bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002186 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002187 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002188
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002189 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002190 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002191 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002192
Sean Callanan79ed1a82010-01-19 20:22:31 +00002193 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002194
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002195 if (Str.empty())
2196 Error(Loc, ".abort detected. Assembly stopping.");
2197 else
2198 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002199 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002200
2201 return false;
2202}
Kevin Enderby71148242009-07-14 21:35:03 +00002203
Kevin Enderby1f049b22009-07-14 23:21:55 +00002204/// ParseDirectiveInclude
2205/// ::= .include "filename"
2206bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002207 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002208 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002209
Sean Callanan18b83232010-01-19 21:44:56 +00002210 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002211 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002212 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002213
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002214 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002215 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002216
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002217 // Strip the quotes.
2218 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002219
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002220 // Attempt to switch the lexer to the included file before consuming the end
2221 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002222 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002223 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002224 return true;
2225 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002226
2227 return false;
2228}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002229
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002230/// ParseDirectiveIncbin
2231/// ::= .incbin "filename"
2232bool AsmParser::ParseDirectiveIncbin() {
2233 if (getLexer().isNot(AsmToken::String))
2234 return TokError("expected string in '.incbin' directive");
2235
2236 std::string Filename = getTok().getString();
2237 SMLoc IncbinLoc = getLexer().getLoc();
2238 Lex();
2239
2240 if (getLexer().isNot(AsmToken::EndOfStatement))
2241 return TokError("unexpected token in '.incbin' directive");
2242
2243 // Strip the quotes.
2244 Filename = Filename.substr(1, Filename.size()-2);
2245
2246 // Attempt to process the included file.
2247 if (ProcessIncbinFile(Filename)) {
2248 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2249 return true;
2250 }
2251
2252 return false;
2253}
2254
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002255/// ParseDirectiveIf
2256/// ::= .if expression
2257bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002258 TheCondStack.push_back(TheCondState);
2259 TheCondState.TheCond = AsmCond::IfCond;
2260 if(TheCondState.Ignore) {
2261 EatToEndOfStatement();
2262 }
2263 else {
2264 int64_t ExprValue;
2265 if (ParseAbsoluteExpression(ExprValue))
2266 return true;
2267
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002268 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002269 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002270
Sean Callanan79ed1a82010-01-19 20:22:31 +00002271 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002272
2273 TheCondState.CondMet = ExprValue;
2274 TheCondState.Ignore = !TheCondState.CondMet;
2275 }
2276
2277 return false;
2278}
2279
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002280bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2281 StringRef Name;
2282 TheCondStack.push_back(TheCondState);
2283 TheCondState.TheCond = AsmCond::IfCond;
2284
2285 if (TheCondState.Ignore) {
2286 EatToEndOfStatement();
2287 } else {
2288 if (ParseIdentifier(Name))
2289 return TokError("expected identifier after '.ifdef'");
2290
2291 Lex();
2292
2293 MCSymbol *Sym = getContext().LookupSymbol(Name);
2294
2295 if (expect_defined)
2296 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2297 else
2298 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2299 TheCondState.Ignore = !TheCondState.CondMet;
2300 }
2301
2302 return false;
2303}
2304
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002305/// ParseDirectiveElseIf
2306/// ::= .elseif expression
2307bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2308 if (TheCondState.TheCond != AsmCond::IfCond &&
2309 TheCondState.TheCond != AsmCond::ElseIfCond)
2310 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2311 " an .elseif");
2312 TheCondState.TheCond = AsmCond::ElseIfCond;
2313
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002314 bool LastIgnoreState = false;
2315 if (!TheCondStack.empty())
2316 LastIgnoreState = TheCondStack.back().Ignore;
2317 if (LastIgnoreState || TheCondState.CondMet) {
2318 TheCondState.Ignore = true;
2319 EatToEndOfStatement();
2320 }
2321 else {
2322 int64_t ExprValue;
2323 if (ParseAbsoluteExpression(ExprValue))
2324 return true;
2325
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002326 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002327 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002328
Sean Callanan79ed1a82010-01-19 20:22:31 +00002329 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002330 TheCondState.CondMet = ExprValue;
2331 TheCondState.Ignore = !TheCondState.CondMet;
2332 }
2333
2334 return false;
2335}
2336
2337/// ParseDirectiveElse
2338/// ::= .else
2339bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002340 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002341 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002342
Sean Callanan79ed1a82010-01-19 20:22:31 +00002343 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002344
2345 if (TheCondState.TheCond != AsmCond::IfCond &&
2346 TheCondState.TheCond != AsmCond::ElseIfCond)
2347 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2348 ".elseif");
2349 TheCondState.TheCond = AsmCond::ElseCond;
2350 bool LastIgnoreState = false;
2351 if (!TheCondStack.empty())
2352 LastIgnoreState = TheCondStack.back().Ignore;
2353 if (LastIgnoreState || TheCondState.CondMet)
2354 TheCondState.Ignore = true;
2355 else
2356 TheCondState.Ignore = false;
2357
2358 return false;
2359}
2360
2361/// ParseDirectiveEndIf
2362/// ::= .endif
2363bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002364 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002365 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002366
Sean Callanan79ed1a82010-01-19 20:22:31 +00002367 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002368
2369 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2370 TheCondStack.empty())
2371 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2372 ".else");
2373 if (!TheCondStack.empty()) {
2374 TheCondState = TheCondStack.back();
2375 TheCondStack.pop_back();
2376 }
2377
2378 return false;
2379}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002380
2381/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002382/// ::= .file [number] filename
2383/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002384bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002385 // FIXME: I'm not sure what this is.
2386 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002387 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002388 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002389 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002390 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002391
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002392 if (FileNumber < 1)
2393 return TokError("file number less than one");
2394 }
2395
Daniel Dunbareceec052010-07-12 17:45:27 +00002396 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002397 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002398
Nick Lewycky44d798d2011-10-17 23:05:28 +00002399 // Usually the directory and filename together, otherwise just the directory.
2400 StringRef Path = getTok().getString();
2401 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002402 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002403
Nick Lewycky44d798d2011-10-17 23:05:28 +00002404 StringRef Directory;
2405 StringRef Filename;
2406 if (getLexer().is(AsmToken::String)) {
2407 if (FileNumber == -1)
2408 return TokError("explicit path specified, but no file number");
2409 Filename = getTok().getString();
2410 Filename = Filename.substr(1, Filename.size()-2);
2411 Directory = Path;
2412 Lex();
2413 } else {
2414 Filename = Path;
2415 }
2416
Daniel Dunbareceec052010-07-12 17:45:27 +00002417 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002418 return TokError("unexpected token in '.file' directive");
2419
Kevin Enderby613b7572011-11-01 22:27:22 +00002420 if (getContext().getGenDwarfForAssembly() == true)
2421 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2422 "used to generate dwarf debug info for assembly code");
2423
Chris Lattnerd32e8032010-01-25 19:02:58 +00002424 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002425 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002426 else {
Nick Lewycky44d798d2011-10-17 23:05:28 +00002427 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002428 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002429 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002430
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002431 return false;
2432}
2433
2434/// ParseDirectiveLine
2435/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002436bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002437 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2438 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002439 return TokError("unexpected token in '.line' directive");
2440
Sean Callanan18b83232010-01-19 21:44:56 +00002441 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002442 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002443 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002444
2445 // FIXME: Do something with the .line.
2446 }
2447
Daniel Dunbareceec052010-07-12 17:45:27 +00002448 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002449 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002450
2451 return false;
2452}
2453
2454
2455/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002456/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002457/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2458/// The first number is a file number, must have been previously assigned with
2459/// a .file directive, the second number is the line number and optionally the
2460/// third number is a column position (zero if not specified). The remaining
2461/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002462bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002463
Daniel Dunbareceec052010-07-12 17:45:27 +00002464 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002465 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002466 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002467 if (FileNumber < 1)
2468 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002469 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002470 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002471 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002472
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002473 int64_t LineNumber = 0;
2474 if (getLexer().is(AsmToken::Integer)) {
2475 LineNumber = getTok().getIntVal();
2476 if (LineNumber < 1)
2477 return TokError("line number less than one in '.loc' directive");
2478 Lex();
2479 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002480
2481 int64_t ColumnPos = 0;
2482 if (getLexer().is(AsmToken::Integer)) {
2483 ColumnPos = getTok().getIntVal();
2484 if (ColumnPos < 0)
2485 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002486 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002487 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002488
Kevin Enderbyc0957932010-09-30 16:52:03 +00002489 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002490 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002491 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002492 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2493 for (;;) {
2494 if (getLexer().is(AsmToken::EndOfStatement))
2495 break;
2496
2497 StringRef Name;
2498 SMLoc Loc = getTok().getLoc();
2499 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002500 return TokError("unexpected token in '.loc' directive");
2501
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002502 if (Name == "basic_block")
2503 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2504 else if (Name == "prologue_end")
2505 Flags |= DWARF2_FLAG_PROLOGUE_END;
2506 else if (Name == "epilogue_begin")
2507 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2508 else if (Name == "is_stmt") {
2509 SMLoc Loc = getTok().getLoc();
2510 const MCExpr *Value;
2511 if (getParser().ParseExpression(Value))
2512 return true;
2513 // The expression must be the constant 0 or 1.
2514 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2515 int Value = MCE->getValue();
2516 if (Value == 0)
2517 Flags &= ~DWARF2_FLAG_IS_STMT;
2518 else if (Value == 1)
2519 Flags |= DWARF2_FLAG_IS_STMT;
2520 else
2521 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002522 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002523 else {
2524 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2525 }
2526 }
2527 else if (Name == "isa") {
2528 SMLoc Loc = getTok().getLoc();
2529 const MCExpr *Value;
2530 if (getParser().ParseExpression(Value))
2531 return true;
2532 // The expression must be a constant greater or equal to 0.
2533 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2534 int Value = MCE->getValue();
2535 if (Value < 0)
2536 return Error(Loc, "isa number less than zero");
2537 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002538 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002539 else {
2540 return Error(Loc, "isa number not a constant value");
2541 }
2542 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002543 else if (Name == "discriminator") {
2544 if (getParser().ParseAbsoluteExpression(Discriminator))
2545 return true;
2546 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002547 else {
2548 return Error(Loc, "unknown sub-directive in '.loc' directive");
2549 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002550
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002551 if (getLexer().is(AsmToken::EndOfStatement))
2552 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002553 }
2554 }
2555
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002556 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002557 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002558
2559 return false;
2560}
2561
Daniel Dunbar138abae2010-10-16 04:56:42 +00002562/// ParseDirectiveStabs
2563/// ::= .stabs string, number, number, number
2564bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2565 SMLoc DirectiveLoc) {
2566 return TokError("unsupported directive '" + Directive + "'");
2567}
2568
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002569/// ParseDirectiveCFISections
2570/// ::= .cfi_sections section [, section]
2571bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2572 SMLoc DirectiveLoc) {
2573 StringRef Name;
2574 bool EH = false;
2575 bool Debug = false;
2576
2577 if (getParser().ParseIdentifier(Name))
2578 return TokError("Expected an identifier");
2579
2580 if (Name == ".eh_frame")
2581 EH = true;
2582 else if (Name == ".debug_frame")
2583 Debug = true;
2584
2585 if (getLexer().is(AsmToken::Comma)) {
2586 Lex();
2587
2588 if (getParser().ParseIdentifier(Name))
2589 return TokError("Expected an identifier");
2590
2591 if (Name == ".eh_frame")
2592 EH = true;
2593 else if (Name == ".debug_frame")
2594 Debug = true;
2595 }
2596
2597 getStreamer().EmitCFISections(EH, Debug);
2598
2599 return false;
2600}
2601
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002602/// ParseDirectiveCFIStartProc
2603/// ::= .cfi_startproc
2604bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2605 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002606 getStreamer().EmitCFIStartProc();
2607 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002608}
2609
2610/// ParseDirectiveCFIEndProc
2611/// ::= .cfi_endproc
2612bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002613 getStreamer().EmitCFIEndProc();
2614 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002615}
2616
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002617/// ParseRegisterOrRegisterNumber - parse register name or number.
2618bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2619 SMLoc DirectiveLoc) {
2620 unsigned RegNo;
2621
Jim Grosbach6f888a82011-06-02 17:14:04 +00002622 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002623 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2624 DirectiveLoc))
2625 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00002626 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002627 } else
2628 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00002629
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002630 return false;
2631}
2632
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002633/// ParseDirectiveCFIDefCfa
2634/// ::= .cfi_def_cfa register, offset
2635bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2636 SMLoc DirectiveLoc) {
2637 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002638 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002639 return true;
2640
2641 if (getLexer().isNot(AsmToken::Comma))
2642 return TokError("unexpected token in directive");
2643 Lex();
2644
2645 int64_t Offset = 0;
2646 if (getParser().ParseAbsoluteExpression(Offset))
2647 return true;
2648
Rafael Espindola066c2f42011-04-12 23:59:07 +00002649 getStreamer().EmitCFIDefCfa(Register, Offset);
2650 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002651}
2652
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002653/// ParseDirectiveCFIDefCfaOffset
2654/// ::= .cfi_def_cfa_offset offset
2655bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2656 SMLoc DirectiveLoc) {
2657 int64_t Offset = 0;
2658 if (getParser().ParseAbsoluteExpression(Offset))
2659 return true;
2660
Rafael Espindola066c2f42011-04-12 23:59:07 +00002661 getStreamer().EmitCFIDefCfaOffset(Offset);
2662 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00002663}
2664
2665/// ParseDirectiveCFIAdjustCfaOffset
2666/// ::= .cfi_adjust_cfa_offset adjustment
2667bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2668 SMLoc DirectiveLoc) {
2669 int64_t Adjustment = 0;
2670 if (getParser().ParseAbsoluteExpression(Adjustment))
2671 return true;
2672
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00002673 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2674 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002675}
2676
2677/// ParseDirectiveCFIDefCfaRegister
2678/// ::= .cfi_def_cfa_register register
2679bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2680 SMLoc DirectiveLoc) {
2681 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002682 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002683 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002684
Rafael Espindola066c2f42011-04-12 23:59:07 +00002685 getStreamer().EmitCFIDefCfaRegister(Register);
2686 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002687}
2688
2689/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002690/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002691bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2692 int64_t Register = 0;
2693 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002694
2695 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002696 return true;
2697
2698 if (getLexer().isNot(AsmToken::Comma))
2699 return TokError("unexpected token in directive");
2700 Lex();
2701
2702 if (getParser().ParseAbsoluteExpression(Offset))
2703 return true;
2704
Rafael Espindola066c2f42011-04-12 23:59:07 +00002705 getStreamer().EmitCFIOffset(Register, Offset);
2706 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002707}
2708
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002709/// ParseDirectiveCFIRelOffset
2710/// ::= .cfi_rel_offset register, offset
2711bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2712 SMLoc DirectiveLoc) {
2713 int64_t Register = 0;
2714
2715 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2716 return true;
2717
2718 if (getLexer().isNot(AsmToken::Comma))
2719 return TokError("unexpected token in directive");
2720 Lex();
2721
2722 int64_t Offset = 0;
2723 if (getParser().ParseAbsoluteExpression(Offset))
2724 return true;
2725
Rafael Espindola25f492e2011-04-12 16:12:03 +00002726 getStreamer().EmitCFIRelOffset(Register, Offset);
2727 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002728}
2729
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002730static bool isValidEncoding(int64_t Encoding) {
2731 if (Encoding & ~0xff)
2732 return false;
2733
2734 if (Encoding == dwarf::DW_EH_PE_omit)
2735 return true;
2736
2737 const unsigned Format = Encoding & 0xf;
2738 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2739 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2740 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2741 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2742 return false;
2743
Rafael Espindolacaf11582010-12-29 04:31:26 +00002744 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002745 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00002746 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002747 return false;
2748
2749 return true;
2750}
2751
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002752/// ParseDirectiveCFIPersonalityOrLsda
2753/// ::= .cfi_personality encoding, [symbol_name]
2754/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002755bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002756 SMLoc DirectiveLoc) {
2757 int64_t Encoding = 0;
2758 if (getParser().ParseAbsoluteExpression(Encoding))
2759 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002760 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002761 return false;
2762
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002763 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002764 return TokError("unsupported encoding.");
2765
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002766 if (getLexer().isNot(AsmToken::Comma))
2767 return TokError("unexpected token in directive");
2768 Lex();
2769
2770 StringRef Name;
2771 if (getParser().ParseIdentifier(Name))
2772 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002773
2774 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2775
2776 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00002777 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002778 else {
2779 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00002780 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002781 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00002782 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002783}
2784
Rafael Espindolafe024d02010-12-28 18:36:23 +00002785/// ParseDirectiveCFIRememberState
2786/// ::= .cfi_remember_state
2787bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2788 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002789 getStreamer().EmitCFIRememberState();
2790 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00002791}
2792
2793/// ParseDirectiveCFIRestoreState
2794/// ::= .cfi_remember_state
2795bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2796 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002797 getStreamer().EmitCFIRestoreState();
2798 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00002799}
2800
Rafael Espindolac5754392011-04-12 15:31:05 +00002801/// ParseDirectiveCFISameValue
2802/// ::= .cfi_same_value register
2803bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2804 SMLoc DirectiveLoc) {
2805 int64_t Register = 0;
2806
2807 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2808 return true;
2809
2810 getStreamer().EmitCFISameValue(Register);
2811
2812 return false;
2813}
2814
Daniel Dunbar3c802de2010-07-18 18:38:02 +00002815/// ParseDirectiveMacrosOnOff
2816/// ::= .macros_on
2817/// ::= .macros_off
2818bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2819 SMLoc DirectiveLoc) {
2820 if (getLexer().isNot(AsmToken::EndOfStatement))
2821 return Error(getLexer().getLoc(),
2822 "unexpected token in '" + Directive + "' directive");
2823
2824 getParser().MacrosEnabled = Directive == ".macros_on";
2825
2826 return false;
2827}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00002828
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002829/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00002830/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002831bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2832 SMLoc DirectiveLoc) {
2833 StringRef Name;
2834 if (getParser().ParseIdentifier(Name))
2835 return TokError("expected identifier in directive");
2836
Rafael Espindola65366442011-06-05 02:43:45 +00002837 std::vector<StringRef> Parameters;
2838 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2839 for(;;) {
2840 StringRef Parameter;
2841 if (getParser().ParseIdentifier(Parameter))
2842 return TokError("expected identifier in directive");
2843 Parameters.push_back(Parameter);
2844
2845 if (getLexer().isNot(AsmToken::Comma))
2846 break;
2847 Lex();
2848 }
2849 }
2850
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002851 if (getLexer().isNot(AsmToken::EndOfStatement))
2852 return TokError("unexpected token in '.macro' directive");
2853
2854 // Eat the end of statement.
2855 Lex();
2856
2857 AsmToken EndToken, StartToken = getTok();
2858
2859 // Lex the macro definition.
2860 for (;;) {
2861 // Check whether we have reached the end of the file.
2862 if (getLexer().is(AsmToken::Eof))
2863 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2864
2865 // Otherwise, check whether we have reach the .endmacro.
2866 if (getLexer().is(AsmToken::Identifier) &&
2867 (getTok().getIdentifier() == ".endm" ||
2868 getTok().getIdentifier() == ".endmacro")) {
2869 EndToken = getTok();
2870 Lex();
2871 if (getLexer().isNot(AsmToken::EndOfStatement))
2872 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2873 "' directive");
2874 break;
2875 }
2876
2877 // Otherwise, scan til the end of the statement.
2878 getParser().EatToEndOfStatement();
2879 }
2880
2881 if (getParser().MacroMap.lookup(Name)) {
2882 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2883 }
2884
2885 const char *BodyStart = StartToken.getLoc().getPointer();
2886 const char *BodyEnd = EndToken.getLoc().getPointer();
2887 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00002888 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002889 return false;
2890}
2891
2892/// ParseDirectiveEndMacro
2893/// ::= .endm
2894/// ::= .endmacro
2895bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2896 SMLoc DirectiveLoc) {
2897 if (getLexer().isNot(AsmToken::EndOfStatement))
2898 return TokError("unexpected token in '" + Directive + "' directive");
2899
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002900 // If we are inside a macro instantiation, terminate the current
2901 // instantiation.
2902 if (!getParser().ActiveMacros.empty()) {
2903 getParser().HandleMacroExit();
2904 return false;
2905 }
2906
2907 // Otherwise, this .endmacro is a stray entry in the file; well formed
2908 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002909 return TokError("unexpected '" + Directive + "' in file, "
2910 "no current macro definition");
2911}
2912
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00002913bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00002914 getParser().CheckForValidSection();
2915
2916 const MCExpr *Value;
2917
2918 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00002919 return true;
2920
2921 if (getLexer().isNot(AsmToken::EndOfStatement))
2922 return TokError("unexpected token in directive");
2923
2924 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00002925 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00002926 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00002927 getStreamer().EmitULEB128Value(Value);
2928
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00002929 return false;
2930}
2931
2932
Daniel Dunbard1e3b442010-07-17 02:26:10 +00002933/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00002934MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00002935 MCContext &C, MCStreamer &Out,
2936 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00002937 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00002938}