blob: 78a877baa0bd8600accaced479ce46ef873184c9 [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000016#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000017#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000018#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000019#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000020#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000021#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000022#include "llvm/MC/MCInstPrinter.h"
23#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000024#include "llvm/MC/MCParser/AsmCond.h"
25#include "llvm/MC/MCParser/AsmLexer.h"
26#include "llvm/MC/MCParser/MCAsmParser.h"
27#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000028#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000029#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000030#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000031#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000032#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000033#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000034#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000035#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000037#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000038#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000039#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000040#include <set>
41#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000042#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000043using namespace llvm;
44
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000045static cl::opt<bool>
46FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
48
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000049namespace {
50
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000051/// \brief Helper class for tracking macro definitions.
Rafael Espindola28c1f6662012-06-03 22:41:23 +000052typedef std::vector<AsmToken> MacroArgument;
Rafael Espindola8a403d32012-08-08 14:51:03 +000053typedef std::vector<MacroArgument> MacroArguments;
Preston Gurd6c9176a2012-09-19 20:29:04 +000054typedef std::pair<StringRef, MacroArgument> MacroParameter;
Rafael Espindola8a403d32012-08-08 14:51:03 +000055typedef std::vector<MacroParameter> MacroParameters;
Rafael Espindola28c1f6662012-06-03 22:41:23 +000056
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000057struct Macro {
58 StringRef Name;
59 StringRef Body;
Rafael Espindola8a403d32012-08-08 14:51:03 +000060 MacroParameters Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000061
62public:
Rafael Espindola8a403d32012-08-08 14:51:03 +000063 Macro(StringRef N, StringRef B, const MacroParameters &P) :
Rafael Espindola65366442011-06-05 02:43:45 +000064 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000065};
66
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000067/// \brief Helper class for storing information about an active macro
68/// instantiation.
69struct MacroInstantiation {
70 /// The macro being instantiated.
71 const Macro *TheMacro;
72
73 /// The macro instantiation with substitutions.
74 MemoryBuffer *Instantiation;
75
76 /// The location of the instantiation.
77 SMLoc InstantiationLoc;
78
79 /// The location where parsing should resume upon instantiation completion.
80 SMLoc ExitLoc;
81
82public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000083 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000084 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000085};
86
Daniel Dunbaraef87e32010-07-18 18:31:38 +000087/// \brief The concrete assembly parser instance.
88class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +000089 friend class GenericAsmParser;
90
Craig Topper85aadc02012-09-15 16:23:52 +000091 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
92 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000093private:
94 AsmLexer Lexer;
95 MCContext &Ctx;
96 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +000097 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000098 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +000099 SourceMgr::DiagHandlerTy SavedDiagHandler;
100 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000101 MCAsmParserExtension *GenericParser;
102 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000103
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000104 /// This is the current buffer index we're lexing from as managed by the
105 /// SourceMgr object.
106 int CurBuffer;
107
108 AsmCond TheCondState;
109 std::vector<AsmCond> TheCondStack;
110
111 /// DirectiveMap - This is a table handlers for directives. Each handler is
112 /// invoked after the directive identifier is read and is responsible for
113 /// parsing and validating the rest of the directive. The handler is passed
114 /// in the directive name and the location of the directive keyword.
115 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000116
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000117 /// MacroMap - Map of currently defined macros.
118 StringMap<Macro*> MacroMap;
119
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000120 /// ActiveMacros - Stack of active macro instantiations.
121 std::vector<MacroInstantiation*> ActiveMacros;
122
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000123 /// Boolean tracking whether macro substitution is enabled.
124 unsigned MacrosEnabled : 1;
125
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000126 /// Flag tracking whether any errors have been encountered.
127 unsigned HadError : 1;
128
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000129 /// The values from the last parsed cpp hash file line comment if any.
130 StringRef CppHashFilename;
131 int64_t CppHashLineNumber;
132 SMLoc CppHashLoc;
133
Devang Patel0db58bf2012-01-31 18:14:05 +0000134 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
135 unsigned AssemblerDialect;
136
Preston Gurd7b6f2032012-09-19 20:36:12 +0000137 /// IsDarwin - is Darwin compatibility enabled?
138 bool IsDarwin;
139
Chad Rosier8f138d12012-10-15 17:19:13 +0000140 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000141 bool ParsingInlineAsm;
142
Chad Rosier8f138d12012-10-15 17:19:13 +0000143 /// ParsedOperands - The parsed operands from the last parsed statement.
144 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
145
Chad Rosierb1f8c132012-10-18 15:49:34 +0000146 /// Opcode - The opcode from the last parsed instruction. This is MS-style
147 /// inline asm specific.
Chad Rosier8f138d12012-10-15 17:19:13 +0000148 unsigned Opcode;
149
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000150public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000151 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000152 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000153 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000154
155 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
156
Craig Topper345d16d2012-08-29 05:48:09 +0000157 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
158 StringRef Directive,
159 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000160 DirectiveMap[Directive] = std::make_pair(Object, Handler);
161 }
162
163public:
164 /// @name MCAsmParser Interface
165 /// {
166
167 virtual SourceMgr &getSourceManager() { return SrcMgr; }
168 virtual MCAsmLexer &getLexer() { return Lexer; }
169 virtual MCContext &getContext() { return Ctx; }
170 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000171 virtual unsigned getAssemblerDialect() {
172 if (AssemblerDialect == ~0U)
173 return MAI.getAssemblerDialect();
174 else
175 return AssemblerDialect;
176 }
177 virtual void setAssemblerDialect(unsigned i) {
178 AssemblerDialect = i;
179 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000180
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000181 virtual bool Warning(SMLoc L, const Twine &Msg,
182 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
183 virtual bool Error(SMLoc L, const Twine &Msg,
184 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000185
Craig Topper345d16d2012-08-29 05:48:09 +0000186 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000187
Chad Rosier84125ca2012-10-13 00:26:04 +0000188 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000189 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000190
191 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
192 unsigned &NumOutputs, unsigned &NumInputs,
193 SmallVectorImpl<void *> &Names,
194 SmallVectorImpl<std::string> &Constraints,
195 SmallVectorImpl<void *> &Exprs,
196 SmallVectorImpl<std::string> &Clobbers,
197 const MCInstrInfo *MII,
198 const MCInstPrinter *IP,
199 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000200
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000201 bool ParseExpression(const MCExpr *&Res);
202 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
203 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
204 virtual bool ParseAbsoluteExpression(int64_t &Res);
205
206 /// }
207
208private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000209 void CheckForValidSection();
210
Chad Rosierb1f8c132012-10-18 15:49:34 +0000211 bool ParseStatement();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000212 void EatToEndOfLine();
213 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000214
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000215 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000216 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000217 const MacroParameters &Parameters,
218 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000219 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000220 void HandleMacroExit();
221
222 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000223 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000224 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
225 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000226 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000227 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000228
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000229 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
230 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000231 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
232 /// This returns true on failure.
233 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000234
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000235 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000236 /// current token is not set; clients should ensure Lex() is called
237 /// subsequently.
238 void JumpToLoc(SMLoc Loc);
239
Craig Topper345d16d2012-08-29 05:48:09 +0000240 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000241
Preston Gurd7b6f2032012-09-19 20:36:12 +0000242 bool ParseMacroArgument(MacroArgument &MA,
243 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000244 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000245
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000246 /// \brief Parse up to the end of statement and a return the contents from the
247 /// current token until the end of the statement; the current token on exit
248 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000249 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000250
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000251 /// \brief Parse until the end of a statement or a comma is encountered,
252 /// return the contents from the current token up to the end or comma.
253 StringRef ParseStringToComma();
254
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000255 bool ParseAssignment(StringRef Name, bool allow_redef,
256 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000257
258 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
259 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
260 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000261 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000262
263 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000264 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000265 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000266
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000267 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000268
269 // ".ascii", ".asciiz", ".string"
270 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000271 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000272 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000273 bool ParseDirectiveFill(); // ".fill"
274 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000275 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000276 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000277 bool ParseDirectiveOrg(); // ".org"
278 // ".align{,32}", ".p2align{,w,l}"
279 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
280
281 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
282 /// accepts a single symbol (which should be a label or an external).
283 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000284
285 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
286
287 bool ParseDirectiveAbort(); // ".abort"
288 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000289 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000290
291 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000292 // ".ifb" or ".ifnb", depending on ExpectBlank.
293 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000294 // ".ifc" or ".ifnc", depending on ExpectEqual.
295 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000296 // ".ifdef" or ".ifndef", depending on expect_defined
297 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000298 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
299 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
300 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
301
302 /// ParseEscapedString - Parse the current token as a string which may include
303 /// escaped characters and return the string contents.
304 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000305
306 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
307 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000308
Rafael Espindola761cb062012-06-03 23:57:14 +0000309 // Macro-like directives
310 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
311 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
312 raw_svector_ostream &OS);
313 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000314 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000315 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000316 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000317
318 // MS-style inline assembly parsing.
319 bool isInstruction() { return Opcode != (unsigned)~0x0; }
320 unsigned getOpcode() { return Opcode; }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000321};
322
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000323/// \brief Generic implementations of directive handling, etc. which is shared
324/// (or the default, at least) for all assembler parser.
325class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000326 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
327 void AddDirectiveHandler(StringRef Directive) {
328 getParser().AddDirectiveHandler(this, Directive,
329 HandleDirective<GenericAsmParser, Handler>);
330 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000331public:
332 GenericAsmParser() {}
333
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000334 AsmParser &getParser() {
335 return (AsmParser&) this->MCAsmParserExtension::getParser();
336 }
337
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000338 virtual void Initialize(MCAsmParser &Parser) {
339 // Call the base implementation.
340 this->MCAsmParserExtension::Initialize(Parser);
341
342 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000343 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
344 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
345 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000346 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000347
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000348 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000349 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
350 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000351 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
352 ".cfi_startproc");
353 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
354 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000355 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
356 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000357 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
358 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000359 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
360 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000361 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
362 ".cfi_def_cfa_register");
363 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
364 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000365 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
366 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000367 AddDirectiveHandler<
368 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
369 AddDirectiveHandler<
370 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000371 AddDirectiveHandler<
372 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
373 AddDirectiveHandler<
374 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000375 AddDirectiveHandler<
376 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000377 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000378 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
379 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000380 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000381 AddDirectiveHandler<
382 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000383
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000384 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000385 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
386 ".macros_on");
387 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
388 ".macros_off");
389 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
391 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000392 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000393
394 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
395 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000396 }
397
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000398 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
399
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000400 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
401 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
402 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000403 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000404 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000405 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
406 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000407 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000408 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000409 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000410 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
411 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000412 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000413 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000414 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
415 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000416 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000417 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000418 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000419 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000420
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000421 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000422 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
423 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000424 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000425
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000426 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000427};
428
429}
430
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000431namespace llvm {
432
433extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000434extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000435extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000436
437}
438
Chris Lattneraaec2052010-01-19 19:46:13 +0000439enum { DEFAULT_ADDRSPACE = 0 };
440
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000441AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000442 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000443 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000444 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000445 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Chad Rosier8f138d12012-10-15 17:19:13 +0000446 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false),
Chad Rosier127f5ed2012-10-15 19:08:18 +0000447 Opcode(~0x0) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000448 // Save the old handler.
449 SavedDiagHandler = SrcMgr.getDiagHandler();
450 SavedDiagContext = SrcMgr.getDiagContext();
451 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000452 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000453 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000454
455 // Initialize the generic parser.
456 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000457
458 // Initialize the platform / file format parser.
459 //
460 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
461 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000462 if (_MAI.hasMicrosoftFastStdCallMangling()) {
463 PlatformParser = createCOFFAsmParser();
464 PlatformParser->Initialize(*this);
465 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000466 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000467 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000468 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000469 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000470 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000471 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000472 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000473}
474
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000475AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000476 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
477
478 // Destroy any macros.
479 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
480 ie = MacroMap.end(); it != ie; ++it)
481 delete it->getValue();
482
Daniel Dunbare4749702010-07-12 18:12:02 +0000483 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000484 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000485}
486
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000487void AsmParser::PrintMacroInstantiations() {
488 // Print the active macro instantiation stack.
489 for (std::vector<MacroInstantiation*>::const_reverse_iterator
490 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000491 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
492 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000493}
494
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000495bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000496 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000497 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000498 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000499 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000500 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000501}
502
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000503bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000504 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000505 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000506 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000507 return true;
508}
509
Sean Callananfd0b0282010-01-21 00:19:58 +0000510bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000511 std::string IncludedFile;
512 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000513 if (NewBuf == -1)
514 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000515
Sean Callananfd0b0282010-01-21 00:19:58 +0000516 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000517
Sean Callananfd0b0282010-01-21 00:19:58 +0000518 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000519
Sean Callananfd0b0282010-01-21 00:19:58 +0000520 return false;
521}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000522
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000523/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000524/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000525/// returns true on failure.
526bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
527 std::string IncludedFile;
528 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
529 if (NewBuf == -1)
530 return true;
531
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000532 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000533 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
534 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000535 return false;
536}
537
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000538void AsmParser::JumpToLoc(SMLoc Loc) {
539 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
540 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
541}
542
Sean Callananfd0b0282010-01-21 00:19:58 +0000543const AsmToken &AsmParser::Lex() {
544 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000545
Sean Callananfd0b0282010-01-21 00:19:58 +0000546 if (tok->is(AsmToken::Eof)) {
547 // If this is the end of an included file, pop the parent file off the
548 // include stack.
549 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
550 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000551 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000552 tok = &Lexer.Lex();
553 }
554 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000555
Sean Callananfd0b0282010-01-21 00:19:58 +0000556 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000557 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000558
Sean Callananfd0b0282010-01-21 00:19:58 +0000559 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000560}
561
Chris Lattner79180e22010-04-05 23:15:42 +0000562bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000563 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000564 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000565 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000566
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000567 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000568 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000569
570 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000571 AsmCond StartingCondState = TheCondState;
572
Kevin Enderby613b7572011-11-01 22:27:22 +0000573 // If we are generating dwarf for assembly source files save the initial text
574 // section and generate a .file directive.
575 if (getContext().getGenDwarfForAssembly()) {
576 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000577 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
578 getStreamer().EmitLabel(SectionStartSym);
579 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000580 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
581 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
582 }
583
Chris Lattnerb717fb02009-07-02 21:53:43 +0000584 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000585 while (Lexer.isNot(AsmToken::Eof)) {
Chris Lattnerb717fb02009-07-02 21:53:43 +0000586 if (!ParseStatement()) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000587
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000588 // We had an error, validate that one was emitted and recover by skipping to
589 // the next line.
590 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000591 EatToEndOfStatement();
592 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000593
594 if (TheCondState.TheCond != StartingCondState.TheCond ||
595 TheCondState.Ignore != StartingCondState.Ignore)
596 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000597
598 // Check to see there are no empty DwarfFile slots.
599 const std::vector<MCDwarfFile *> &MCDwarfFiles =
600 getContext().getMCDwarfFiles();
601 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000602 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000603 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000604 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000605
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000606 // Check to see that all assembler local symbols were actually defined.
607 // Targets that don't do subsections via symbols may not want this, though,
608 // so conservatively exclude them. Only do this if we're finalizing, though,
609 // as otherwise we won't necessarilly have seen everything yet.
610 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
611 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
612 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
613 e = Symbols.end();
614 i != e; ++i) {
615 MCSymbol *Sym = i->getValue();
616 // Variable symbols may not be marked as defined, so check those
617 // explicitly. If we know it's a variable, we have a definition for
618 // the purposes of this check.
619 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
620 // FIXME: We would really like to refer back to where the symbol was
621 // first referenced for a source location. We need to add something
622 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000623 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
624 "assembler local symbol '" + Sym->getName() +
625 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000626 }
627 }
628
629
Chris Lattner79180e22010-04-05 23:15:42 +0000630 // Finalize the output stream if there are no errors and if the client wants
631 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000632 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000633 Out.Finish();
634
Chris Lattnerb717fb02009-07-02 21:53:43 +0000635 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000636}
637
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000638void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000639 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000640 TokError("expected section directive before assembly directive");
641 Out.SwitchSection(Ctx.getMachOSection(
642 "__TEXT", "__text",
643 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
644 0, SectionKind::getText()));
645 }
646}
647
Chris Lattner2cf5f142009-06-22 01:29:09 +0000648/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
649void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000650 while (Lexer.isNot(AsmToken::EndOfStatement) &&
651 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000652 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000653
Chris Lattner2cf5f142009-06-22 01:29:09 +0000654 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000655 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000656 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000657}
658
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000659StringRef AsmParser::ParseStringToEndOfStatement() {
660 const char *Start = getTok().getLoc().getPointer();
661
662 while (Lexer.isNot(AsmToken::EndOfStatement) &&
663 Lexer.isNot(AsmToken::Eof))
664 Lex();
665
666 const char *End = getTok().getLoc().getPointer();
667 return StringRef(Start, End - Start);
668}
Chris Lattnerc4193832009-06-22 05:51:26 +0000669
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000670StringRef AsmParser::ParseStringToComma() {
671 const char *Start = getTok().getLoc().getPointer();
672
673 while (Lexer.isNot(AsmToken::EndOfStatement) &&
674 Lexer.isNot(AsmToken::Comma) &&
675 Lexer.isNot(AsmToken::Eof))
676 Lex();
677
678 const char *End = getTok().getLoc().getPointer();
679 return StringRef(Start, End - Start);
680}
681
Chris Lattner74ec1a32009-06-22 06:32:03 +0000682/// ParseParenExpr - Parse a paren expression and return it.
683/// NOTE: This assumes the leading '(' has already been consumed.
684///
685/// parenexpr ::= expr)
686///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000687bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000688 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000689 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000690 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000691 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000692 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000693 return false;
694}
Chris Lattnerc4193832009-06-22 05:51:26 +0000695
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000696/// ParseBracketExpr - Parse a bracket expression and return it.
697/// NOTE: This assumes the leading '[' has already been consumed.
698///
699/// bracketexpr ::= expr]
700///
701bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
702 if (ParseExpression(Res)) return true;
703 if (Lexer.isNot(AsmToken::RBrac))
704 return TokError("expected ']' in brackets expression");
705 EndLoc = Lexer.getLoc();
706 Lex();
707 return false;
708}
709
Chris Lattner74ec1a32009-06-22 06:32:03 +0000710/// ParsePrimaryExpr - Parse a primary expression and return it.
711/// primaryexpr ::= (parenexpr
712/// primaryexpr ::= symbol
713/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000714/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000715/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000716bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000717 switch (Lexer.getKind()) {
718 default:
719 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000720 // If we have an error assume that we've already handled it.
721 case AsmToken::Error:
722 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000723 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000724 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000725 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000726 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000727 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000728 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000729 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000730 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000731 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000732 EndLoc = Lexer.getLoc();
733
734 StringRef Identifier;
735 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000736 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000737
Daniel Dunbarfffff912009-10-16 01:34:54 +0000738 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000739 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000740 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000741
742 // Lookup the symbol variant if used.
743 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000744 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000745 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000746 if (Variant == MCSymbolRefExpr::VK_Invalid) {
747 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000748 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000749 }
750 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000751
Daniel Dunbarfffff912009-10-16 01:34:54 +0000752 // If this is an absolute variable reference, substitute it now to preserve
753 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000754 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000755 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000756 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000757
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000758 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000759 return false;
760 }
761
762 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000763 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000764 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000765 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000766 case AsmToken::Integer: {
767 SMLoc Loc = getTok().getLoc();
768 int64_t IntVal = getTok().getIntVal();
769 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000770 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000771 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000772 // Look for 'b' or 'f' following an Integer as a directional label
773 if (Lexer.getKind() == AsmToken::Identifier) {
774 StringRef IDVal = getTok().getString();
775 if (IDVal == "f" || IDVal == "b"){
776 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
777 IDVal == "f" ? 1 : 0);
778 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
779 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000780 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000781 return Error(Loc, "invalid reference to undefined symbol");
782 EndLoc = Lexer.getLoc();
783 Lex(); // Eat identifier.
784 }
785 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000786 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000787 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000788 case AsmToken::Real: {
789 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000790 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000791 Res = MCConstantExpr::Create(IntVal, getContext());
792 Lex(); // Eat token.
793 return false;
794 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000795 case AsmToken::Dot: {
796 // This is a '.' reference, which references the current PC. Emit a
797 // temporary label to the streamer and refer to it.
798 MCSymbol *Sym = Ctx.CreateTempSymbol();
799 Out.EmitLabel(Sym);
800 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
801 EndLoc = Lexer.getLoc();
802 Lex(); // Eat identifier.
803 return false;
804 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000805 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000806 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000807 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000808 case AsmToken::LBrac:
809 if (!PlatformParser->HasBracketExpressions())
810 return TokError("brackets expression not supported on this target");
811 Lex(); // Eat the '['.
812 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000813 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000814 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000815 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000816 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000817 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000818 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000819 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000820 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000821 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000822 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000823 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000824 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000825 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000826 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000827 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000828 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000829 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000830 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000831 }
832}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000833
Chris Lattnerb4307b32010-01-15 19:28:38 +0000834bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000835 SMLoc EndLoc;
836 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000837}
838
Daniel Dunbarcceba832010-09-17 02:47:07 +0000839const MCExpr *
840AsmParser::ApplyModifierToExpr(const MCExpr *E,
841 MCSymbolRefExpr::VariantKind Variant) {
842 // Recurse over the given expression, rebuilding it to apply the given variant
843 // if there is exactly one symbol.
844 switch (E->getKind()) {
845 case MCExpr::Target:
846 case MCExpr::Constant:
847 return 0;
848
849 case MCExpr::SymbolRef: {
850 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
851
852 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
853 TokError("invalid variant on expression '" +
854 getTok().getIdentifier() + "' (already modified)");
855 return E;
856 }
857
858 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
859 }
860
861 case MCExpr::Unary: {
862 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
863 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
864 if (!Sub)
865 return 0;
866 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
867 }
868
869 case MCExpr::Binary: {
870 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
871 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
872 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
873
874 if (!LHS && !RHS)
875 return 0;
876
877 if (!LHS) LHS = BE->getLHS();
878 if (!RHS) RHS = BE->getRHS();
879
880 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
881 }
882 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000883
Craig Topper85814382012-02-07 05:05:23 +0000884 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000885}
886
Chris Lattner74ec1a32009-06-22 06:32:03 +0000887/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000888///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000889/// expr ::= expr &&,|| expr -> lowest.
890/// expr ::= expr |,^,&,! expr
891/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
892/// expr ::= expr <<,>> expr
893/// expr ::= expr +,- expr
894/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000895/// expr ::= primaryexpr
896///
Chris Lattner54482b42010-01-15 19:39:23 +0000897bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000898 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000899 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000900 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
901 return true;
902
Daniel Dunbarcceba832010-09-17 02:47:07 +0000903 // As a special case, we support 'a op b @ modifier' by rewriting the
904 // expression to include the modifier. This is inefficient, but in general we
905 // expect users to use 'a@modifier op b'.
906 if (Lexer.getKind() == AsmToken::At) {
907 Lex();
908
909 if (Lexer.isNot(AsmToken::Identifier))
910 return TokError("unexpected symbol modifier following '@'");
911
912 MCSymbolRefExpr::VariantKind Variant =
913 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
914 if (Variant == MCSymbolRefExpr::VK_Invalid)
915 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
916
917 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
918 if (!ModifiedRes) {
919 return TokError("invalid modifier '" + getTok().getIdentifier() +
920 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000921 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000922
Daniel Dunbarcceba832010-09-17 02:47:07 +0000923 Res = ModifiedRes;
924 Lex();
925 }
926
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000927 // Try to constant fold it up front, if possible.
928 int64_t Value;
929 if (Res->EvaluateAsAbsolute(Value))
930 Res = MCConstantExpr::Create(Value, getContext());
931
932 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000933}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000934
Chris Lattnerb4307b32010-01-15 19:28:38 +0000935bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000936 Res = 0;
937 return ParseParenExpr(Res, EndLoc) ||
938 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000939}
940
Daniel Dunbar475839e2009-06-29 20:37:27 +0000941bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000942 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000943
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000944 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000945 if (ParseExpression(Expr))
946 return true;
947
Daniel Dunbare00b0112009-10-16 01:57:52 +0000948 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000949 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000950
951 return false;
952}
953
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000954static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000955 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000956 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000957 default:
958 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000959
Jim Grosbachfbe16812011-08-20 16:24:13 +0000960 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000961 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000962 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000963 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000964 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000965 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000966 return 1;
967
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000968
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000969 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000970 //
971 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000972 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000973 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000974 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000975 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000976 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000977 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000978 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000979 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000980 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000981
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000982 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000983 case AsmToken::EqualEqual:
984 Kind = MCBinaryExpr::EQ;
985 return 3;
986 case AsmToken::ExclaimEqual:
987 case AsmToken::LessGreater:
988 Kind = MCBinaryExpr::NE;
989 return 3;
990 case AsmToken::Less:
991 Kind = MCBinaryExpr::LT;
992 return 3;
993 case AsmToken::LessEqual:
994 Kind = MCBinaryExpr::LTE;
995 return 3;
996 case AsmToken::Greater:
997 Kind = MCBinaryExpr::GT;
998 return 3;
999 case AsmToken::GreaterEqual:
1000 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001001 return 3;
1002
Jim Grosbachfbe16812011-08-20 16:24:13 +00001003 // Intermediate Precedence: <<, >>
1004 case AsmToken::LessLess:
1005 Kind = MCBinaryExpr::Shl;
1006 return 4;
1007 case AsmToken::GreaterGreater:
1008 Kind = MCBinaryExpr::Shr;
1009 return 4;
1010
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001011 // High Intermediate Precedence: +, -
1012 case AsmToken::Plus:
1013 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001014 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001015 case AsmToken::Minus:
1016 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001017 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001018
Jim Grosbachfbe16812011-08-20 16:24:13 +00001019 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001020 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001021 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001022 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001023 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001024 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001025 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001026 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001027 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001028 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001029 }
1030}
1031
1032
1033/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1034/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001035bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1036 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001037 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001038 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001039 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001040
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001041 // If the next token is lower precedence than we are allowed to eat, return
1042 // successfully with what we ate already.
1043 if (TokPrec < Precedence)
1044 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001045
Sean Callanan79ed1a82010-01-19 20:22:31 +00001046 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001047
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001048 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001049 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001050 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001051
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001052 // If BinOp binds less tightly with RHS than the operator after RHS, let
1053 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001054 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001055 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001056 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001057 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001058 }
1059
Daniel Dunbar475839e2009-06-29 20:37:27 +00001060 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001061 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001062 }
1063}
1064
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001065/// ParseStatement:
1066/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001067/// ::= Label* Directive ...Operands... EndOfStatement
1068/// ::= Label* Identifier OperandList* EndOfStatement
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001069bool AsmParser::ParseStatement() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001070 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001071 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001072 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001073 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001074 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001075
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001076 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001077 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001078 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001079 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001080 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001081 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001082 if (Lexer.is(AsmToken::Hash))
1083 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001084
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001085 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001086 if (Lexer.is(AsmToken::Integer)) {
1087 LocalLabelVal = getTok().getIntVal();
1088 if (LocalLabelVal < 0) {
1089 if (!TheCondState.Ignore)
1090 return TokError("unexpected token at start of statement");
1091 IDVal = "";
1092 }
1093 else {
1094 IDVal = getTok().getString();
1095 Lex(); // Consume the integer token to be used as an identifier token.
1096 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001097 if (!TheCondState.Ignore)
1098 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001099 }
1100 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001101
1102 } else if (Lexer.is(AsmToken::Dot)) {
1103 // Treat '.' as a valid identifier in this context.
1104 Lex();
1105 IDVal = ".";
1106
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001107 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001108 if (!TheCondState.Ignore)
1109 return TokError("unexpected token at start of statement");
1110 IDVal = "";
1111 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001112
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001113
Chris Lattner7834fac2010-04-17 18:14:27 +00001114 // Handle conditional assembly here before checking for skipping. We
1115 // have to do this so that .endif isn't skipped in a ".if 0" block for
1116 // example.
1117 if (IDVal == ".if")
1118 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001119 if (IDVal == ".ifb")
1120 return ParseDirectiveIfb(IDLoc, true);
1121 if (IDVal == ".ifnb")
1122 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001123 if (IDVal == ".ifc")
1124 return ParseDirectiveIfc(IDLoc, true);
1125 if (IDVal == ".ifnc")
1126 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001127 if (IDVal == ".ifdef")
1128 return ParseDirectiveIfdef(IDLoc, true);
1129 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1130 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001131 if (IDVal == ".elseif")
1132 return ParseDirectiveElseIf(IDLoc);
1133 if (IDVal == ".else")
1134 return ParseDirectiveElse(IDLoc);
1135 if (IDVal == ".endif")
1136 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001137
Chris Lattner7834fac2010-04-17 18:14:27 +00001138 // If we are in a ".if 0" block, ignore this statement.
1139 if (TheCondState.Ignore) {
1140 EatToEndOfStatement();
1141 return false;
1142 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001143
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001144 // FIXME: Recurse on local labels?
1145
1146 // See what kind of statement we have.
1147 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001148 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001149 CheckForValidSection();
1150
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001151 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001152 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001153
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001154 // Diagnose attempt to use '.' as a label.
1155 if (IDVal == ".")
1156 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1157
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001158 // Diagnose attempt to use a variable as a label.
1159 //
1160 // FIXME: Diagnostics. Note the location of the definition as a label.
1161 // FIXME: This doesn't diagnose assignment to a symbol which has been
1162 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001163 MCSymbol *Sym;
1164 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001165 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001166 else
1167 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001168 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001169 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001170
Daniel Dunbar959fd882009-08-26 22:13:22 +00001171 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001172 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001173
Kevin Enderby94c2e852011-12-09 18:09:40 +00001174 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001175 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001176 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001177 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1178 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001179
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001180 // Consume any end of statement token, if present, to avoid spurious
1181 // AddBlankLine calls().
1182 if (Lexer.is(AsmToken::EndOfStatement)) {
1183 Lex();
1184 if (Lexer.is(AsmToken::Eof))
1185 return false;
1186 }
1187
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001188 return ParseStatement();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001189 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001190
Daniel Dunbar3f872332009-07-28 16:08:33 +00001191 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001192 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001193 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001194
Nico Weber4c4c7322011-01-28 03:04:41 +00001195 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001196
1197 default: // Normal instruction or directive.
1198 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001199 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001200
1201 // If macros are enabled, check to see if this is a macro instantiation.
1202 if (MacrosEnabled)
1203 if (const Macro *M = MacroMap.lookup(IDVal))
1204 return HandleMacroEntry(IDVal, IDLoc, M);
1205
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001206 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001207 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001208
1209 // Target hook for parsing target specific directives.
1210 if (!getTargetParser().ParseDirective(ID))
1211 return false;
1212
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001213 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001214 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001215 return ParseDirectiveSet(IDVal, true);
1216 if (IDVal == ".equiv")
1217 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001218
Daniel Dunbara0d14262009-06-24 23:30:00 +00001219 // Data directives
1220
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001221 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001222 return ParseDirectiveAscii(IDVal, false);
1223 if (IDVal == ".asciz" || IDVal == ".string")
1224 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001225
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001226 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001227 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001228 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001229 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001230 if (IDVal == ".value")
1231 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001232 if (IDVal == ".2byte")
1233 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001234 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001235 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001236 if (IDVal == ".int")
1237 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001238 if (IDVal == ".4byte")
1239 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001240 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001241 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001242 if (IDVal == ".8byte")
1243 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001244 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001245 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1246 if (IDVal == ".double")
1247 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001248
Eli Friedman5d68ec22010-07-19 04:17:25 +00001249 if (IDVal == ".align") {
1250 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1251 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1252 }
1253 if (IDVal == ".align32") {
1254 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1255 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1256 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001257 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001258 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001259 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001260 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001261 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001262 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001263 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001264 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001265 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001266 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001267 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001268 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1269
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001270 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001271 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001272
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001273 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001274 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001275 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001276 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001277 if (IDVal == ".zero")
1278 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001279
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001280 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001281
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001282 if (IDVal == ".extern") {
1283 EatToEndOfStatement(); // .extern is the default, ignore it.
1284 return false;
1285 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001286 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001287 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001288 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001289 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001290 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001291 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001292 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001293 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001294 if (IDVal == ".symbol_resolver")
1295 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001296 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001297 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001298 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001299 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001300 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001301 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001302 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001303 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001304 if (IDVal == ".weak_def_can_be_hidden")
1305 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001306
Hans Wennborg5cc64912011-06-18 13:51:54 +00001307 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001308 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001309 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001310 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001311
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001312 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001313 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001314 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001315 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001316 if (IDVal == ".incbin")
1317 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001318
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001319 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001320 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001321
Rafael Espindola761cb062012-06-03 23:57:14 +00001322 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001323 if (IDVal == ".rept")
1324 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001325 if (IDVal == ".irp")
1326 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001327 if (IDVal == ".irpc")
1328 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001329 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001330 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001331
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001332 // Look up the handler in the handler table.
1333 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1334 DirectiveMap.lookup(IDVal);
1335 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001336 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001337
Kevin Enderby9c656452009-09-10 20:51:44 +00001338
Jim Grosbach686c0182012-05-01 18:38:27 +00001339 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001340 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001341
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001342 CheckForValidSection();
1343
Chris Lattnera7f13542010-05-19 23:34:33 +00001344 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001345 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001346 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001347 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001348
Chad Rosier8f138d12012-10-15 17:19:13 +00001349 bool HadError = getTargetParser().ParseInstruction(OpcodeStr.str(), IDLoc,
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001350 ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001351
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001352 // Dump the parsed representation, if requested.
1353 if (getShowParsedOperands()) {
1354 SmallString<256> Str;
1355 raw_svector_ostream OS(Str);
1356 OS << "parsed instruction: [";
1357 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1358 if (i != 0)
1359 OS << ", ";
Jim Grosbachb7f689b2011-07-13 15:34:57 +00001360 ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001361 }
1362 OS << "]";
1363
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001364 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001365 }
1366
Kevin Enderby613b7572011-11-01 22:27:22 +00001367 // If we are generating dwarf for assembly source files and the current
1368 // section is the initial text section then generate a .loc directive for
1369 // the instruction.
1370 if (!HadError && getContext().getGenDwarfForAssembly() &&
1371 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1372 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1373 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1374 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001375 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001376 StringRef());
1377 }
1378
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001379 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001380 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001381 unsigned ErrorInfo;
1382 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Opcode,
Chad Rosier8f138d12012-10-15 17:19:13 +00001383 ParsedOperands, Out,
1384 ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001385 ParsingInlineAsm);
1386 }
Chris Lattner98986712010-01-14 22:21:20 +00001387
Chad Rosierb1f8c132012-10-18 15:49:34 +00001388 // Free any parsed operands. If parsing ms-style inline assembly the operands
1389 // will be freed by the ParseMSInlineAsm() function.
1390 if (!ParsingInlineAsm) {
1391 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1392 delete ParsedOperands[i];
1393 ParsedOperands.clear();
1394 }
Chris Lattner98986712010-01-14 22:21:20 +00001395
Chris Lattnercbf8a982010-09-11 16:18:25 +00001396 // Don't skip the rest of the line, the instruction parser is responsible for
1397 // that.
1398 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001399}
Chris Lattner9a023f72009-06-24 04:43:34 +00001400
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001401/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1402/// since they may not be able to be tokenized to get to the end of line token.
1403void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001404 if (!Lexer.is(AsmToken::EndOfStatement))
1405 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001406 // Eat EOL.
1407 Lex();
1408}
1409
1410/// ParseCppHashLineFilenameComment as this:
1411/// ::= # number "filename"
1412/// or just as a full line comment if it doesn't have a number and a string.
1413bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1414 Lex(); // Eat the hash token.
1415
1416 if (getLexer().isNot(AsmToken::Integer)) {
1417 // Consume the line since in cases it is not a well-formed line directive,
1418 // as if were simply a full line comment.
1419 EatToEndOfLine();
1420 return false;
1421 }
1422
1423 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001424 Lex();
1425
1426 if (getLexer().isNot(AsmToken::String)) {
1427 EatToEndOfLine();
1428 return false;
1429 }
1430
1431 StringRef Filename = getTok().getString();
1432 // Get rid of the enclosing quotes.
1433 Filename = Filename.substr(1, Filename.size()-2);
1434
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001435 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1436 CppHashLoc = L;
1437 CppHashFilename = Filename;
1438 CppHashLineNumber = LineNumber;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001439
1440 // Ignore any trailing characters, they're just comment.
1441 EatToEndOfLine();
1442 return false;
1443}
1444
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001445/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001446/// for the Filename and LineNo if any in the diagnostic.
1447void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1448 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1449 raw_ostream &OS = errs();
1450
1451 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1452 const SMLoc &DiagLoc = Diag.getLoc();
1453 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1454 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1455
1456 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1457 // before printing the message.
1458 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001459 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001460 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1461 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1462 }
1463
1464 // If we have not parsed a cpp hash line filename comment or the source
1465 // manager changed or buffer changed (like in a nested include) then just
1466 // print the normal diagnostic using its Filename and LineNo.
1467 if (!Parser->CppHashLineNumber ||
1468 &DiagSrcMgr != &Parser->SrcMgr ||
1469 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001470 if (Parser->SavedDiagHandler)
1471 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1472 else
1473 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001474 return;
1475 }
1476
1477 // Use the CppHashFilename and calculate a line number based on the
1478 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1479 // the diagnostic.
1480 const std::string Filename = Parser->CppHashFilename;
1481
1482 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1483 int CppHashLocLineNo =
1484 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1485 int LineNo = Parser->CppHashLineNumber - 1 +
1486 (DiagLocLineNo - CppHashLocLineNo);
1487
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001488 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1489 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001490 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001491 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001492
Benjamin Kramer04a04262011-10-16 10:48:29 +00001493 if (Parser->SavedDiagHandler)
1494 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1495 else
1496 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001497}
1498
Rafael Espindola799aacf2012-08-21 18:29:30 +00001499// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1500// difference being that that function accepts '@' as part of identifiers and
1501// we can't do that. AsmLexer.cpp should probably be changed to handle
1502// '@' as a special case when needed.
1503static bool isIdentifierChar(char c) {
1504 return isalnum(c) || c == '_' || c == '$' || c == '.';
1505}
1506
Rafael Espindola761cb062012-06-03 23:57:14 +00001507bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001508 const MacroParameters &Parameters,
1509 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001510 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001511 unsigned NParameters = Parameters.size();
1512 if (NParameters != 0 && NParameters != A.size())
1513 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001514
Preston Gurd7b6f2032012-09-19 20:36:12 +00001515 // A macro without parameters is handled differently on Darwin:
1516 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001517 while (!Body.empty()) {
1518 // Scan for the next substitution.
1519 std::size_t End = Body.size(), Pos = 0;
1520 for (; Pos != End; ++Pos) {
1521 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001522 if (!NParameters) {
1523 // This macro has no parameters, look for $0, $1, etc.
1524 if (Body[Pos] != '$' || Pos + 1 == End)
1525 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001526
Rafael Espindola65366442011-06-05 02:43:45 +00001527 char Next = Body[Pos + 1];
1528 if (Next == '$' || Next == 'n' || isdigit(Next))
1529 break;
1530 } else {
1531 // This macro has parameters, look for \foo, \bar, etc.
1532 if (Body[Pos] == '\\' && Pos + 1 != End)
1533 break;
1534 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001535 }
1536
1537 // Add the prefix.
1538 OS << Body.slice(0, Pos);
1539
1540 // Check if we reached the end.
1541 if (Pos == End)
1542 break;
1543
Rafael Espindola65366442011-06-05 02:43:45 +00001544 if (!NParameters) {
1545 switch (Body[Pos+1]) {
1546 // $$ => $
1547 case '$':
1548 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001549 break;
1550
Rafael Espindola65366442011-06-05 02:43:45 +00001551 // $n => number of arguments
1552 case 'n':
1553 OS << A.size();
1554 break;
1555
1556 // $[0-9] => argument
1557 default: {
1558 // Missing arguments are ignored.
1559 unsigned Index = Body[Pos+1] - '0';
1560 if (Index >= A.size())
1561 break;
1562
1563 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001564 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001565 ie = A[Index].end(); it != ie; ++it)
1566 OS << it->getString();
1567 break;
1568 }
1569 }
1570 Pos += 2;
1571 } else {
1572 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001573 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001574 ++I;
1575
1576 const char *Begin = Body.data() + Pos +1;
1577 StringRef Argument(Begin, I - (Pos +1));
1578 unsigned Index = 0;
1579 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001580 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001581 break;
1582
Preston Gurd7b6f2032012-09-19 20:36:12 +00001583 if (Index == NParameters) {
1584 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1585 Pos += 3;
1586 else {
1587 OS << '\\' << Argument;
1588 Pos = I;
1589 }
1590 } else {
1591 for (MacroArgument::const_iterator it = A[Index].begin(),
1592 ie = A[Index].end(); it != ie; ++it)
1593 if (it->getKind() == AsmToken::String)
1594 OS << it->getStringContents();
1595 else
1596 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001597
Preston Gurd7b6f2032012-09-19 20:36:12 +00001598 Pos += 1 + Argument.size();
1599 }
Rafael Espindola65366442011-06-05 02:43:45 +00001600 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001601 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001602 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001603 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001604
Rafael Espindola65366442011-06-05 02:43:45 +00001605 return false;
1606}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001607
Rafael Espindola65366442011-06-05 02:43:45 +00001608MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1609 MemoryBuffer *I)
1610 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1611{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001612}
1613
Preston Gurd7b6f2032012-09-19 20:36:12 +00001614static bool IsOperator(AsmToken::TokenKind kind)
1615{
1616 switch (kind)
1617 {
1618 default:
1619 return false;
1620 case AsmToken::Plus:
1621 case AsmToken::Minus:
1622 case AsmToken::Tilde:
1623 case AsmToken::Slash:
1624 case AsmToken::Star:
1625 case AsmToken::Dot:
1626 case AsmToken::Equal:
1627 case AsmToken::EqualEqual:
1628 case AsmToken::Pipe:
1629 case AsmToken::PipePipe:
1630 case AsmToken::Caret:
1631 case AsmToken::Amp:
1632 case AsmToken::AmpAmp:
1633 case AsmToken::Exclaim:
1634 case AsmToken::ExclaimEqual:
1635 case AsmToken::Percent:
1636 case AsmToken::Less:
1637 case AsmToken::LessEqual:
1638 case AsmToken::LessLess:
1639 case AsmToken::LessGreater:
1640 case AsmToken::Greater:
1641 case AsmToken::GreaterEqual:
1642 case AsmToken::GreaterGreater:
1643 return true;
1644 }
1645}
1646
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001647/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1648/// This is used for both default macro parameter values and the
1649/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001650bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1651 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001652 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001653 unsigned AddTokens = 0;
1654
1655 // gas accepts arguments separated by whitespace, except on Darwin
1656 if (!IsDarwin)
1657 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001658
1659 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001660 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1661 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001662 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001663 }
1664
1665 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1666 // Spaces and commas cannot be mixed to delimit parameters
1667 if (ArgumentDelimiter == AsmToken::Eof)
1668 ArgumentDelimiter = AsmToken::Comma;
1669 else if (ArgumentDelimiter != AsmToken::Comma) {
1670 Lexer.setSkipSpace(true);
1671 return TokError("expected ' ' for macro argument separator");
1672 }
1673 break;
1674 }
1675
1676 if (Lexer.is(AsmToken::Space)) {
1677 Lex(); // Eat spaces
1678
1679 // Spaces can delimit parameters, but could also be part an expression.
1680 // If the token after a space is an operator, add the token and the next
1681 // one into this argument
1682 if (ArgumentDelimiter == AsmToken::Space ||
1683 ArgumentDelimiter == AsmToken::Eof) {
1684 if (IsOperator(Lexer.getKind())) {
1685 // Check to see whether the token is used as an operator,
1686 // or part of an identifier
1687 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1688 if (*NextChar == ' ')
1689 AddTokens = 2;
1690 }
1691
1692 if (!AddTokens && ParenLevel == 0) {
1693 if (ArgumentDelimiter == AsmToken::Eof &&
1694 !IsOperator(Lexer.getKind()))
1695 ArgumentDelimiter = AsmToken::Space;
1696 break;
1697 }
1698 }
1699 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001700
1701 // HandleMacroEntry relies on not advancing the lexer here
1702 // to be able to fill in the remaining default parameter values
1703 if (Lexer.is(AsmToken::EndOfStatement))
1704 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001705
1706 // Adjust the current parentheses level.
1707 if (Lexer.is(AsmToken::LParen))
1708 ++ParenLevel;
1709 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1710 --ParenLevel;
1711
1712 // Append the token to the current argument list.
1713 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001714 if (AddTokens)
1715 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001716 Lex();
1717 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001718
1719 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001720 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001721 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001722 return false;
1723}
1724
1725// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001726bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001727 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001728 // Argument delimiter is initially unknown. It will be set by
1729 // ParseMacroArgument()
1730 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001731
1732 // Parse two kinds of macro invocations:
1733 // - macros defined without any parameters accept an arbitrary number of them
1734 // - macros defined with parameters accept at most that many of them
1735 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1736 ++Parameter) {
1737 MacroArgument MA;
1738
Preston Gurd7b6f2032012-09-19 20:36:12 +00001739 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001740 return true;
1741
Preston Gurd6c9176a2012-09-19 20:29:04 +00001742 if (!MA.empty() || !NParameters)
1743 A.push_back(MA);
1744 else if (NParameters) {
1745 if (!M->Parameters[Parameter].second.empty())
1746 A.push_back(M->Parameters[Parameter].second);
1747 }
Jim Grosbach97146442012-07-30 22:44:17 +00001748
Preston Gurd6c9176a2012-09-19 20:29:04 +00001749 // At the end of the statement, fill in remaining arguments that have
1750 // default values. If there aren't any, then the next argument is
1751 // required but missing
1752 if (Lexer.is(AsmToken::EndOfStatement)) {
1753 if (NParameters && Parameter < NParameters - 1) {
1754 if (M->Parameters[Parameter + 1].second.empty())
1755 return TokError("macro argument '" +
1756 Twine(M->Parameters[Parameter + 1].first) +
1757 "' is missing");
1758 else
1759 continue;
1760 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001761 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001762 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001763
1764 if (Lexer.is(AsmToken::Comma))
1765 Lex();
1766 }
1767 return TokError("Too many arguments");
1768}
1769
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001770bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1771 const Macro *M) {
1772 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1773 // this, although we should protect against infinite loops.
1774 if (ActiveMacros.size() == 20)
1775 return TokError("macros cannot be nested more than 20 levels deep");
1776
Rafael Espindola8a403d32012-08-08 14:51:03 +00001777 MacroArguments A;
1778 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001779 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001780
Jim Grosbach97146442012-07-30 22:44:17 +00001781 // Remove any trailing empty arguments. Do this after-the-fact as we have
1782 // to keep empty arguments in the middle of the list or positionality
1783 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001784 while (!A.empty() && A.back().empty())
1785 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001786
Rafael Espindola65366442011-06-05 02:43:45 +00001787 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1788 // to hold the macro body with substitutions.
1789 SmallString<256> Buf;
1790 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001791 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001792
Rafael Espindola8a403d32012-08-08 14:51:03 +00001793 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001794 return true;
1795
Rafael Espindola761cb062012-06-03 23:57:14 +00001796 // We include the .endmacro in the buffer as our queue to exit the macro
1797 // instantiation.
1798 OS << ".endmacro\n";
1799
Rafael Espindola65366442011-06-05 02:43:45 +00001800 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001801 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001802
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001803 // Create the macro instantiation object and add to the current macro
1804 // instantiation stack.
1805 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001806 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001807 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001808 ActiveMacros.push_back(MI);
1809
1810 // Jump to the macro instantiation and prime the lexer.
1811 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1812 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1813 Lex();
1814
1815 return false;
1816}
1817
1818void AsmParser::HandleMacroExit() {
1819 // Jump to the EndOfStatement we should return to, and consume it.
1820 JumpToLoc(ActiveMacros.back()->ExitLoc);
1821 Lex();
1822
1823 // Pop the instantiation entry.
1824 delete ActiveMacros.back();
1825 ActiveMacros.pop_back();
1826}
1827
Rafael Espindolae71cc862012-01-28 05:57:00 +00001828static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001829 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001830 case MCExpr::Binary: {
1831 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1832 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001833 break;
1834 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001835 case MCExpr::Target:
1836 case MCExpr::Constant:
1837 return false;
1838 case MCExpr::SymbolRef: {
1839 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001840 if (S.isVariable())
1841 return IsUsedIn(Sym, S.getVariableValue());
1842 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001843 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001844 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001845 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001846 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001847
1848 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001849}
1850
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001851bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1852 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001853 // FIXME: Use better location, we should use proper tokens.
1854 SMLoc EqualLoc = Lexer.getLoc();
1855
Daniel Dunbar821e3332009-08-31 08:09:28 +00001856 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001857 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001858 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001859
Rafael Espindolae71cc862012-01-28 05:57:00 +00001860 // Note: we don't count b as used in "a = b". This is to allow
1861 // a = b
1862 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001863
Daniel Dunbar3f872332009-07-28 16:08:33 +00001864 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001865 return TokError("unexpected token in assignment");
1866
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001867 // Error on assignment to '.'.
1868 if (Name == ".") {
1869 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1870 "(use '.space' or '.org').)"));
1871 }
1872
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001873 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001874 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001875
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001876 // Validate that the LHS is allowed to be a variable (either it has not been
1877 // used as a symbol, or it is an absolute symbol).
1878 MCSymbol *Sym = getContext().LookupSymbol(Name);
1879 if (Sym) {
1880 // Diagnose assignment to a label.
1881 //
1882 // FIXME: Diagnostics. Note the location of the definition as a label.
1883 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001884 if (IsUsedIn(Sym, Value))
1885 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1886 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001887 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001888 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1889 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001890 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001891 return Error(EqualLoc, "redefinition of '" + Name + "'");
1892 else if (!Sym->isVariable())
1893 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001894 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001895 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1896 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001897
1898 // Don't count these checks as uses.
1899 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001900 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001901 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001902
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001903 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001904
1905 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001906 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001907 if (NoDeadStrip)
1908 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1909
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001910
1911 return false;
1912}
1913
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001914/// ParseIdentifier:
1915/// ::= identifier
1916/// ::= string
1917bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001918 // The assembler has relaxed rules for accepting identifiers, in particular we
1919 // allow things like '.globl $foo', which would normally be separate
1920 // tokens. At this level, we have already lexed so we cannot (currently)
1921 // handle this as a context dependent token, instead we detect adjacent tokens
1922 // and return the combined identifier.
1923 if (Lexer.is(AsmToken::Dollar)) {
1924 SMLoc DollarLoc = getLexer().getLoc();
1925
1926 // Consume the dollar sign, and check for a following identifier.
1927 Lex();
1928 if (Lexer.isNot(AsmToken::Identifier))
1929 return true;
1930
1931 // We have a '$' followed by an identifier, make sure they are adjacent.
1932 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1933 return true;
1934
1935 // Construct the joined identifier and consume the token.
1936 Res = StringRef(DollarLoc.getPointer(),
1937 getTok().getIdentifier().size() + 1);
1938 Lex();
1939 return false;
1940 }
1941
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001942 if (Lexer.isNot(AsmToken::Identifier) &&
1943 Lexer.isNot(AsmToken::String))
1944 return true;
1945
Sean Callanan18b83232010-01-19 21:44:56 +00001946 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001947
Sean Callanan79ed1a82010-01-19 20:22:31 +00001948 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001949
1950 return false;
1951}
1952
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001953/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001954/// ::= .equ identifier ',' expression
1955/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001956/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001957bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001958 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001959
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001960 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001961 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001962
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001963 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001964 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001965 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001966
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001967 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001968}
1969
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001970bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001971 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001972
1973 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00001974 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001975 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1976 if (Str[i] != '\\') {
1977 Data += Str[i];
1978 continue;
1979 }
1980
1981 // Recognize escaped characters. Note that this escape semantics currently
1982 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1983 ++i;
1984 if (i == e)
1985 return TokError("unexpected backslash at end of string");
1986
1987 // Recognize octal sequences.
1988 if ((unsigned) (Str[i] - '0') <= 7) {
1989 // Consume up to three octal characters.
1990 unsigned Value = Str[i] - '0';
1991
1992 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1993 ++i;
1994 Value = Value * 8 + (Str[i] - '0');
1995
1996 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1997 ++i;
1998 Value = Value * 8 + (Str[i] - '0');
1999 }
2000 }
2001
2002 if (Value > 255)
2003 return TokError("invalid octal escape sequence (out of range)");
2004
2005 Data += (unsigned char) Value;
2006 continue;
2007 }
2008
2009 // Otherwise recognize individual escapes.
2010 switch (Str[i]) {
2011 default:
2012 // Just reject invalid escape sequences for now.
2013 return TokError("invalid escape sequence (unrecognized character)");
2014
2015 case 'b': Data += '\b'; break;
2016 case 'f': Data += '\f'; break;
2017 case 'n': Data += '\n'; break;
2018 case 'r': Data += '\r'; break;
2019 case 't': Data += '\t'; break;
2020 case '"': Data += '"'; break;
2021 case '\\': Data += '\\'; break;
2022 }
2023 }
2024
2025 return false;
2026}
2027
Daniel Dunbara0d14262009-06-24 23:30:00 +00002028/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002029/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2030bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002031 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002032 CheckForValidSection();
2033
Daniel Dunbara0d14262009-06-24 23:30:00 +00002034 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002035 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002036 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002037
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002038 std::string Data;
2039 if (ParseEscapedString(Data))
2040 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002041
2042 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002043 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002044 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2045
Sean Callanan79ed1a82010-01-19 20:22:31 +00002046 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002047
2048 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002049 break;
2050
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002051 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002052 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002053 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002054 }
2055 }
2056
Sean Callanan79ed1a82010-01-19 20:22:31 +00002057 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002058 return false;
2059}
2060
2061/// ParseDirectiveValue
2062/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2063bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002064 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002065 CheckForValidSection();
2066
Daniel Dunbara0d14262009-06-24 23:30:00 +00002067 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002068 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002069 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002070 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002071 return true;
2072
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002073 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002074 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2075 assert(Size <= 8 && "Invalid size");
2076 uint64_t IntValue = MCE->getValue();
2077 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2078 return Error(ExprLoc, "literal value out of range for directive");
2079 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2080 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002081 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002082
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002083 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002084 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002085
Daniel Dunbara0d14262009-06-24 23:30:00 +00002086 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002087 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002088 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002089 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002090 }
2091 }
2092
Sean Callanan79ed1a82010-01-19 20:22:31 +00002093 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002094 return false;
2095}
2096
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002097/// ParseDirectiveRealValue
2098/// ::= (.single | .double) [ expression (, expression)* ]
2099bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2100 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2101 CheckForValidSection();
2102
2103 for (;;) {
2104 // We don't truly support arithmetic on floating point expressions, so we
2105 // have to manually parse unary prefixes.
2106 bool IsNeg = false;
2107 if (getLexer().is(AsmToken::Minus)) {
2108 Lex();
2109 IsNeg = true;
2110 } else if (getLexer().is(AsmToken::Plus))
2111 Lex();
2112
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002113 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002114 getLexer().isNot(AsmToken::Real) &&
2115 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002116 return TokError("unexpected token in directive");
2117
2118 // Convert to an APFloat.
2119 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002120 StringRef IDVal = getTok().getString();
2121 if (getLexer().is(AsmToken::Identifier)) {
2122 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2123 Value = APFloat::getInf(Semantics);
2124 else if (!IDVal.compare_lower("nan"))
2125 Value = APFloat::getNaN(Semantics, false, ~0);
2126 else
2127 return TokError("invalid floating point literal");
2128 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002129 APFloat::opInvalidOp)
2130 return TokError("invalid floating point literal");
2131 if (IsNeg)
2132 Value.changeSign();
2133
2134 // Consume the numeric token.
2135 Lex();
2136
2137 // Emit the value as an integer.
2138 APInt AsInt = Value.bitcastToAPInt();
2139 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2140 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2141
2142 if (getLexer().is(AsmToken::EndOfStatement))
2143 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002144
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002145 if (getLexer().isNot(AsmToken::Comma))
2146 return TokError("unexpected token in directive");
2147 Lex();
2148 }
2149 }
2150
2151 Lex();
2152 return false;
2153}
2154
Daniel Dunbara0d14262009-06-24 23:30:00 +00002155/// ParseDirectiveSpace
2156/// ::= .space expression [ , expression ]
2157bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002158 CheckForValidSection();
2159
Daniel Dunbara0d14262009-06-24 23:30:00 +00002160 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002161 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002162 return true;
2163
2164 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002165 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2166 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002167 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002168 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002169
Daniel Dunbar475839e2009-06-29 20:37:27 +00002170 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002171 return true;
2172
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002173 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002174 return TokError("unexpected token in '.space' directive");
2175 }
2176
Sean Callanan79ed1a82010-01-19 20:22:31 +00002177 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002178
2179 if (NumBytes <= 0)
2180 return TokError("invalid number of bytes in '.space' directive");
2181
2182 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002183 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002184
2185 return false;
2186}
2187
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002188/// ParseDirectiveZero
2189/// ::= .zero expression
2190bool AsmParser::ParseDirectiveZero() {
2191 CheckForValidSection();
2192
2193 int64_t NumBytes;
2194 if (ParseAbsoluteExpression(NumBytes))
2195 return true;
2196
Rafael Espindolae452b172010-10-05 19:42:57 +00002197 int64_t Val = 0;
2198 if (getLexer().is(AsmToken::Comma)) {
2199 Lex();
2200 if (ParseAbsoluteExpression(Val))
2201 return true;
2202 }
2203
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002204 if (getLexer().isNot(AsmToken::EndOfStatement))
2205 return TokError("unexpected token in '.zero' directive");
2206
2207 Lex();
2208
Rafael Espindolae452b172010-10-05 19:42:57 +00002209 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002210
2211 return false;
2212}
2213
Daniel Dunbara0d14262009-06-24 23:30:00 +00002214/// ParseDirectiveFill
2215/// ::= .fill expression , expression , expression
2216bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002217 CheckForValidSection();
2218
Daniel Dunbara0d14262009-06-24 23:30:00 +00002219 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002220 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002221 return true;
2222
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002223 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002224 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002225 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002226
Daniel Dunbara0d14262009-06-24 23:30:00 +00002227 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002228 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002229 return true;
2230
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002231 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002232 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002233 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002234
Daniel Dunbara0d14262009-06-24 23:30:00 +00002235 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002236 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002237 return true;
2238
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002239 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002240 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002241
Sean Callanan79ed1a82010-01-19 20:22:31 +00002242 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002243
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002244 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2245 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002246
2247 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002248 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002249
2250 return false;
2251}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002252
2253/// ParseDirectiveOrg
2254/// ::= .org expression [ , expression ]
2255bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002256 CheckForValidSection();
2257
Daniel Dunbar821e3332009-08-31 08:09:28 +00002258 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002259 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002260 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002261 return true;
2262
2263 // Parse optional fill expression.
2264 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002265 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2266 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002267 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002268 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002269
Daniel Dunbar475839e2009-06-29 20:37:27 +00002270 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002271 return true;
2272
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002273 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002274 return TokError("unexpected token in '.org' directive");
2275 }
2276
Sean Callanan79ed1a82010-01-19 20:22:31 +00002277 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002278
Jim Grosbachebd4c052012-01-27 00:37:08 +00002279 // Only limited forms of relocatable expressions are accepted here, it
2280 // has to be relative to the current section. The streamer will return
2281 // 'true' if the expression wasn't evaluatable.
2282 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2283 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002284
2285 return false;
2286}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002287
2288/// ParseDirectiveAlign
2289/// ::= {.align, ...} expression [ , expression [ , expression ]]
2290bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002291 CheckForValidSection();
2292
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002293 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002294 int64_t Alignment;
2295 if (ParseAbsoluteExpression(Alignment))
2296 return true;
2297
2298 SMLoc MaxBytesLoc;
2299 bool HasFillExpr = false;
2300 int64_t FillExpr = 0;
2301 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002302 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2303 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002304 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002305 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002306
2307 // The fill expression can be omitted while specifying a maximum number of
2308 // alignment bytes, e.g:
2309 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002310 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002311 HasFillExpr = true;
2312 if (ParseAbsoluteExpression(FillExpr))
2313 return true;
2314 }
2315
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002316 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2317 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002318 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002319 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002320
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002321 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002322 if (ParseAbsoluteExpression(MaxBytesToFill))
2323 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002324
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002325 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002326 return TokError("unexpected token in directive");
2327 }
2328 }
2329
Sean Callanan79ed1a82010-01-19 20:22:31 +00002330 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002331
Daniel Dunbar648ac512010-05-17 21:54:30 +00002332 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002333 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002334
2335 // Compute alignment in bytes.
2336 if (IsPow2) {
2337 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002338 if (Alignment >= 32) {
2339 Error(AlignmentLoc, "invalid alignment value");
2340 Alignment = 31;
2341 }
2342
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002343 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002344 }
2345
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002346 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002347 if (MaxBytesLoc.isValid()) {
2348 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002349 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2350 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002351 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002352 }
2353
2354 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002355 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2356 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002357 MaxBytesToFill = 0;
2358 }
2359 }
2360
Daniel Dunbar648ac512010-05-17 21:54:30 +00002361 // Check whether we should use optimal code alignment for this .align
2362 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002363 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002364 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2365 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002366 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002367 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002368 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002369 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2370 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002371 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002372
2373 return false;
2374}
2375
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002376/// ParseDirectiveSymbolAttribute
2377/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002378bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002379 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002380 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002381 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002382 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002383
2384 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002385 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002386
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002387 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002388
Jim Grosbach10ec6502011-09-15 17:56:49 +00002389 // Assembler local symbols don't make any sense here. Complain loudly.
2390 if (Sym->isTemporary())
2391 return Error(Loc, "non-local symbol required in directive");
2392
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002393 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002394
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002395 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002396 break;
2397
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002398 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002399 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002400 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002401 }
2402 }
2403
Sean Callanan79ed1a82010-01-19 20:22:31 +00002404 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002405 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002406}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002407
2408/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002409/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2410bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002411 CheckForValidSection();
2412
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002413 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002414 StringRef Name;
2415 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002416 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002417
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002418 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002419 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002420
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002421 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002422 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002423 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002424
2425 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002426 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002427 if (ParseAbsoluteExpression(Size))
2428 return true;
2429
2430 int64_t Pow2Alignment = 0;
2431 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002432 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002433 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002434 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002435 if (ParseAbsoluteExpression(Pow2Alignment))
2436 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002437
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002438 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2439 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002440 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2441
Chris Lattner258281d2010-01-19 06:22:22 +00002442 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002443 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2444 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002445 if (!isPowerOf2_64(Pow2Alignment))
2446 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2447 Pow2Alignment = Log2_64(Pow2Alignment);
2448 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002449 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002450
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002451 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002452 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002453
Sean Callanan79ed1a82010-01-19 20:22:31 +00002454 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002455
Chris Lattner1fc3d752009-07-09 17:25:12 +00002456 // NOTE: a size of zero for a .comm should create a undefined symbol
2457 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002458 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002459 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2460 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002461
Eric Christopherc260a3e2010-05-14 01:38:54 +00002462 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002463 // may internally end up wanting an alignment in bytes.
2464 // FIXME: Diagnose overflow.
2465 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002466 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2467 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002468
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002469 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002470 return Error(IDLoc, "invalid symbol redefinition");
2471
Chris Lattner1fc3d752009-07-09 17:25:12 +00002472 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002473 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002474 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002475 return false;
2476 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002477
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002478 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002479 return false;
2480}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002481
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002482/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002483/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002484bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002485 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002486 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002487
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002488 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002489 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002490 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002491
Sean Callanan79ed1a82010-01-19 20:22:31 +00002492 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002493
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002494 if (Str.empty())
2495 Error(Loc, ".abort detected. Assembly stopping.");
2496 else
2497 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002498 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002499
2500 return false;
2501}
Kevin Enderby71148242009-07-14 21:35:03 +00002502
Kevin Enderby1f049b22009-07-14 23:21:55 +00002503/// ParseDirectiveInclude
2504/// ::= .include "filename"
2505bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002506 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002507 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002508
Sean Callanan18b83232010-01-19 21:44:56 +00002509 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002510 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002511 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002512
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002513 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002514 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002515
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002516 // Strip the quotes.
2517 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002518
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002519 // Attempt to switch the lexer to the included file before consuming the end
2520 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002521 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002522 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002523 return true;
2524 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002525
2526 return false;
2527}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002528
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002529/// ParseDirectiveIncbin
2530/// ::= .incbin "filename"
2531bool AsmParser::ParseDirectiveIncbin() {
2532 if (getLexer().isNot(AsmToken::String))
2533 return TokError("expected string in '.incbin' directive");
2534
2535 std::string Filename = getTok().getString();
2536 SMLoc IncbinLoc = getLexer().getLoc();
2537 Lex();
2538
2539 if (getLexer().isNot(AsmToken::EndOfStatement))
2540 return TokError("unexpected token in '.incbin' directive");
2541
2542 // Strip the quotes.
2543 Filename = Filename.substr(1, Filename.size()-2);
2544
2545 // Attempt to process the included file.
2546 if (ProcessIncbinFile(Filename)) {
2547 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2548 return true;
2549 }
2550
2551 return false;
2552}
2553
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002554/// ParseDirectiveIf
2555/// ::= .if expression
2556bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002557 TheCondStack.push_back(TheCondState);
2558 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002559 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002560 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002561 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002562 int64_t ExprValue;
2563 if (ParseAbsoluteExpression(ExprValue))
2564 return true;
2565
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002566 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002567 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002568
Sean Callanan79ed1a82010-01-19 20:22:31 +00002569 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002570
2571 TheCondState.CondMet = ExprValue;
2572 TheCondState.Ignore = !TheCondState.CondMet;
2573 }
2574
2575 return false;
2576}
2577
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002578/// ParseDirectiveIfb
2579/// ::= .ifb string
2580bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2581 TheCondStack.push_back(TheCondState);
2582 TheCondState.TheCond = AsmCond::IfCond;
2583
Benjamin Kramer29739e72012-05-12 16:52:21 +00002584 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002585 EatToEndOfStatement();
2586 } else {
2587 StringRef Str = ParseStringToEndOfStatement();
2588
2589 if (getLexer().isNot(AsmToken::EndOfStatement))
2590 return TokError("unexpected token in '.ifb' directive");
2591
2592 Lex();
2593
2594 TheCondState.CondMet = ExpectBlank == Str.empty();
2595 TheCondState.Ignore = !TheCondState.CondMet;
2596 }
2597
2598 return false;
2599}
2600
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002601/// ParseDirectiveIfc
2602/// ::= .ifc string1, string2
2603bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2604 TheCondStack.push_back(TheCondState);
2605 TheCondState.TheCond = AsmCond::IfCond;
2606
Benjamin Kramer29739e72012-05-12 16:52:21 +00002607 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002608 EatToEndOfStatement();
2609 } else {
2610 StringRef Str1 = ParseStringToComma();
2611
2612 if (getLexer().isNot(AsmToken::Comma))
2613 return TokError("unexpected token in '.ifc' directive");
2614
2615 Lex();
2616
2617 StringRef Str2 = ParseStringToEndOfStatement();
2618
2619 if (getLexer().isNot(AsmToken::EndOfStatement))
2620 return TokError("unexpected token in '.ifc' directive");
2621
2622 Lex();
2623
2624 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2625 TheCondState.Ignore = !TheCondState.CondMet;
2626 }
2627
2628 return false;
2629}
2630
2631/// ParseDirectiveIfdef
2632/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002633bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2634 StringRef Name;
2635 TheCondStack.push_back(TheCondState);
2636 TheCondState.TheCond = AsmCond::IfCond;
2637
2638 if (TheCondState.Ignore) {
2639 EatToEndOfStatement();
2640 } else {
2641 if (ParseIdentifier(Name))
2642 return TokError("expected identifier after '.ifdef'");
2643
2644 Lex();
2645
2646 MCSymbol *Sym = getContext().LookupSymbol(Name);
2647
2648 if (expect_defined)
2649 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2650 else
2651 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2652 TheCondState.Ignore = !TheCondState.CondMet;
2653 }
2654
2655 return false;
2656}
2657
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002658/// ParseDirectiveElseIf
2659/// ::= .elseif expression
2660bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2661 if (TheCondState.TheCond != AsmCond::IfCond &&
2662 TheCondState.TheCond != AsmCond::ElseIfCond)
2663 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2664 " an .elseif");
2665 TheCondState.TheCond = AsmCond::ElseIfCond;
2666
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002667 bool LastIgnoreState = false;
2668 if (!TheCondStack.empty())
2669 LastIgnoreState = TheCondStack.back().Ignore;
2670 if (LastIgnoreState || TheCondState.CondMet) {
2671 TheCondState.Ignore = true;
2672 EatToEndOfStatement();
2673 }
2674 else {
2675 int64_t ExprValue;
2676 if (ParseAbsoluteExpression(ExprValue))
2677 return true;
2678
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002679 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002680 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002681
Sean Callanan79ed1a82010-01-19 20:22:31 +00002682 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002683 TheCondState.CondMet = ExprValue;
2684 TheCondState.Ignore = !TheCondState.CondMet;
2685 }
2686
2687 return false;
2688}
2689
2690/// ParseDirectiveElse
2691/// ::= .else
2692bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002693 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002694 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002695
Sean Callanan79ed1a82010-01-19 20:22:31 +00002696 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002697
2698 if (TheCondState.TheCond != AsmCond::IfCond &&
2699 TheCondState.TheCond != AsmCond::ElseIfCond)
2700 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2701 ".elseif");
2702 TheCondState.TheCond = AsmCond::ElseCond;
2703 bool LastIgnoreState = false;
2704 if (!TheCondStack.empty())
2705 LastIgnoreState = TheCondStack.back().Ignore;
2706 if (LastIgnoreState || TheCondState.CondMet)
2707 TheCondState.Ignore = true;
2708 else
2709 TheCondState.Ignore = false;
2710
2711 return false;
2712}
2713
2714/// ParseDirectiveEndIf
2715/// ::= .endif
2716bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002717 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002718 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002719
Sean Callanan79ed1a82010-01-19 20:22:31 +00002720 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002721
2722 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2723 TheCondStack.empty())
2724 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2725 ".else");
2726 if (!TheCondStack.empty()) {
2727 TheCondState = TheCondStack.back();
2728 TheCondStack.pop_back();
2729 }
2730
2731 return false;
2732}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002733
2734/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002735/// ::= .file [number] filename
2736/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002737bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002738 // FIXME: I'm not sure what this is.
2739 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002740 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002741 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002742 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002743 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002744
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002745 if (FileNumber < 1)
2746 return TokError("file number less than one");
2747 }
2748
Daniel Dunbareceec052010-07-12 17:45:27 +00002749 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002750 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002751
Nick Lewycky44d798d2011-10-17 23:05:28 +00002752 // Usually the directory and filename together, otherwise just the directory.
2753 StringRef Path = getTok().getString();
2754 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002755 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002756
Nick Lewycky44d798d2011-10-17 23:05:28 +00002757 StringRef Directory;
2758 StringRef Filename;
2759 if (getLexer().is(AsmToken::String)) {
2760 if (FileNumber == -1)
2761 return TokError("explicit path specified, but no file number");
2762 Filename = getTok().getString();
2763 Filename = Filename.substr(1, Filename.size()-2);
2764 Directory = Path;
2765 Lex();
2766 } else {
2767 Filename = Path;
2768 }
2769
Daniel Dunbareceec052010-07-12 17:45:27 +00002770 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002771 return TokError("unexpected token in '.file' directive");
2772
Chris Lattnerd32e8032010-01-25 19:02:58 +00002773 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002774 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002775 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002776 if (getContext().getGenDwarfForAssembly() == true)
2777 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2778 "used to generate dwarf debug info for assembly code");
2779
Nick Lewycky44d798d2011-10-17 23:05:28 +00002780 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002781 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002782 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002783
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002784 return false;
2785}
2786
2787/// ParseDirectiveLine
2788/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002789bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002790 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2791 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002792 return TokError("unexpected token in '.line' directive");
2793
Sean Callanan18b83232010-01-19 21:44:56 +00002794 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002795 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002796 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002797
2798 // FIXME: Do something with the .line.
2799 }
2800
Daniel Dunbareceec052010-07-12 17:45:27 +00002801 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002802 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002803
2804 return false;
2805}
2806
2807
2808/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002809/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002810/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2811/// The first number is a file number, must have been previously assigned with
2812/// a .file directive, the second number is the line number and optionally the
2813/// third number is a column position (zero if not specified). The remaining
2814/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002815bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002816
Daniel Dunbareceec052010-07-12 17:45:27 +00002817 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002818 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002819 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002820 if (FileNumber < 1)
2821 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002822 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002823 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002824 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002825
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002826 int64_t LineNumber = 0;
2827 if (getLexer().is(AsmToken::Integer)) {
2828 LineNumber = getTok().getIntVal();
2829 if (LineNumber < 1)
2830 return TokError("line number less than one in '.loc' directive");
2831 Lex();
2832 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002833
2834 int64_t ColumnPos = 0;
2835 if (getLexer().is(AsmToken::Integer)) {
2836 ColumnPos = getTok().getIntVal();
2837 if (ColumnPos < 0)
2838 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002839 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002840 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002841
Kevin Enderbyc0957932010-09-30 16:52:03 +00002842 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002843 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002844 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002845 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2846 for (;;) {
2847 if (getLexer().is(AsmToken::EndOfStatement))
2848 break;
2849
2850 StringRef Name;
2851 SMLoc Loc = getTok().getLoc();
2852 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002853 return TokError("unexpected token in '.loc' directive");
2854
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002855 if (Name == "basic_block")
2856 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2857 else if (Name == "prologue_end")
2858 Flags |= DWARF2_FLAG_PROLOGUE_END;
2859 else if (Name == "epilogue_begin")
2860 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2861 else if (Name == "is_stmt") {
2862 SMLoc Loc = getTok().getLoc();
2863 const MCExpr *Value;
2864 if (getParser().ParseExpression(Value))
2865 return true;
2866 // The expression must be the constant 0 or 1.
2867 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2868 int Value = MCE->getValue();
2869 if (Value == 0)
2870 Flags &= ~DWARF2_FLAG_IS_STMT;
2871 else if (Value == 1)
2872 Flags |= DWARF2_FLAG_IS_STMT;
2873 else
2874 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002875 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002876 else {
2877 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2878 }
2879 }
2880 else if (Name == "isa") {
2881 SMLoc Loc = getTok().getLoc();
2882 const MCExpr *Value;
2883 if (getParser().ParseExpression(Value))
2884 return true;
2885 // The expression must be a constant greater or equal to 0.
2886 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2887 int Value = MCE->getValue();
2888 if (Value < 0)
2889 return Error(Loc, "isa number less than zero");
2890 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002891 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002892 else {
2893 return Error(Loc, "isa number not a constant value");
2894 }
2895 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002896 else if (Name == "discriminator") {
2897 if (getParser().ParseAbsoluteExpression(Discriminator))
2898 return true;
2899 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002900 else {
2901 return Error(Loc, "unknown sub-directive in '.loc' directive");
2902 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002903
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002904 if (getLexer().is(AsmToken::EndOfStatement))
2905 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002906 }
2907 }
2908
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002909 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002910 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002911
2912 return false;
2913}
2914
Daniel Dunbar138abae2010-10-16 04:56:42 +00002915/// ParseDirectiveStabs
2916/// ::= .stabs string, number, number, number
2917bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2918 SMLoc DirectiveLoc) {
2919 return TokError("unsupported directive '" + Directive + "'");
2920}
2921
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002922/// ParseDirectiveCFISections
2923/// ::= .cfi_sections section [, section]
2924bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2925 SMLoc DirectiveLoc) {
2926 StringRef Name;
2927 bool EH = false;
2928 bool Debug = false;
2929
2930 if (getParser().ParseIdentifier(Name))
2931 return TokError("Expected an identifier");
2932
2933 if (Name == ".eh_frame")
2934 EH = true;
2935 else if (Name == ".debug_frame")
2936 Debug = true;
2937
2938 if (getLexer().is(AsmToken::Comma)) {
2939 Lex();
2940
2941 if (getParser().ParseIdentifier(Name))
2942 return TokError("Expected an identifier");
2943
2944 if (Name == ".eh_frame")
2945 EH = true;
2946 else if (Name == ".debug_frame")
2947 Debug = true;
2948 }
2949
2950 getStreamer().EmitCFISections(EH, Debug);
2951
2952 return false;
2953}
2954
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002955/// ParseDirectiveCFIStartProc
2956/// ::= .cfi_startproc
2957bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2958 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002959 getStreamer().EmitCFIStartProc();
2960 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002961}
2962
2963/// ParseDirectiveCFIEndProc
2964/// ::= .cfi_endproc
2965bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002966 getStreamer().EmitCFIEndProc();
2967 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002968}
2969
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002970/// ParseRegisterOrRegisterNumber - parse register name or number.
2971bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2972 SMLoc DirectiveLoc) {
2973 unsigned RegNo;
2974
Jim Grosbach6f888a82011-06-02 17:14:04 +00002975 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002976 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2977 DirectiveLoc))
2978 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00002979 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002980 } else
2981 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00002982
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002983 return false;
2984}
2985
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002986/// ParseDirectiveCFIDefCfa
2987/// ::= .cfi_def_cfa register, offset
2988bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2989 SMLoc DirectiveLoc) {
2990 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002991 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002992 return true;
2993
2994 if (getLexer().isNot(AsmToken::Comma))
2995 return TokError("unexpected token in directive");
2996 Lex();
2997
2998 int64_t Offset = 0;
2999 if (getParser().ParseAbsoluteExpression(Offset))
3000 return true;
3001
Rafael Espindola066c2f42011-04-12 23:59:07 +00003002 getStreamer().EmitCFIDefCfa(Register, Offset);
3003 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003004}
3005
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003006/// ParseDirectiveCFIDefCfaOffset
3007/// ::= .cfi_def_cfa_offset offset
3008bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3009 SMLoc DirectiveLoc) {
3010 int64_t Offset = 0;
3011 if (getParser().ParseAbsoluteExpression(Offset))
3012 return true;
3013
Rafael Espindola066c2f42011-04-12 23:59:07 +00003014 getStreamer().EmitCFIDefCfaOffset(Offset);
3015 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003016}
3017
3018/// ParseDirectiveCFIAdjustCfaOffset
3019/// ::= .cfi_adjust_cfa_offset adjustment
3020bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3021 SMLoc DirectiveLoc) {
3022 int64_t Adjustment = 0;
3023 if (getParser().ParseAbsoluteExpression(Adjustment))
3024 return true;
3025
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003026 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3027 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003028}
3029
3030/// ParseDirectiveCFIDefCfaRegister
3031/// ::= .cfi_def_cfa_register register
3032bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3033 SMLoc DirectiveLoc) {
3034 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003035 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003036 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003037
Rafael Espindola066c2f42011-04-12 23:59:07 +00003038 getStreamer().EmitCFIDefCfaRegister(Register);
3039 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003040}
3041
3042/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003043/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003044bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3045 int64_t Register = 0;
3046 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003047
3048 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003049 return true;
3050
3051 if (getLexer().isNot(AsmToken::Comma))
3052 return TokError("unexpected token in directive");
3053 Lex();
3054
3055 if (getParser().ParseAbsoluteExpression(Offset))
3056 return true;
3057
Rafael Espindola066c2f42011-04-12 23:59:07 +00003058 getStreamer().EmitCFIOffset(Register, Offset);
3059 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003060}
3061
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003062/// ParseDirectiveCFIRelOffset
3063/// ::= .cfi_rel_offset register, offset
3064bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3065 SMLoc DirectiveLoc) {
3066 int64_t Register = 0;
3067
3068 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3069 return true;
3070
3071 if (getLexer().isNot(AsmToken::Comma))
3072 return TokError("unexpected token in directive");
3073 Lex();
3074
3075 int64_t Offset = 0;
3076 if (getParser().ParseAbsoluteExpression(Offset))
3077 return true;
3078
Rafael Espindola25f492e2011-04-12 16:12:03 +00003079 getStreamer().EmitCFIRelOffset(Register, Offset);
3080 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003081}
3082
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003083static bool isValidEncoding(int64_t Encoding) {
3084 if (Encoding & ~0xff)
3085 return false;
3086
3087 if (Encoding == dwarf::DW_EH_PE_omit)
3088 return true;
3089
3090 const unsigned Format = Encoding & 0xf;
3091 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3092 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3093 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3094 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3095 return false;
3096
Rafael Espindolacaf11582010-12-29 04:31:26 +00003097 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003098 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003099 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003100 return false;
3101
3102 return true;
3103}
3104
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003105/// ParseDirectiveCFIPersonalityOrLsda
3106/// ::= .cfi_personality encoding, [symbol_name]
3107/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003108bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003109 SMLoc DirectiveLoc) {
3110 int64_t Encoding = 0;
3111 if (getParser().ParseAbsoluteExpression(Encoding))
3112 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003113 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003114 return false;
3115
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003116 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003117 return TokError("unsupported encoding.");
3118
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003119 if (getLexer().isNot(AsmToken::Comma))
3120 return TokError("unexpected token in directive");
3121 Lex();
3122
3123 StringRef Name;
3124 if (getParser().ParseIdentifier(Name))
3125 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003126
3127 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3128
3129 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003130 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003131 else {
3132 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003133 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003134 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003135 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003136}
3137
Rafael Espindolafe024d02010-12-28 18:36:23 +00003138/// ParseDirectiveCFIRememberState
3139/// ::= .cfi_remember_state
3140bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3141 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003142 getStreamer().EmitCFIRememberState();
3143 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003144}
3145
3146/// ParseDirectiveCFIRestoreState
3147/// ::= .cfi_remember_state
3148bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3149 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003150 getStreamer().EmitCFIRestoreState();
3151 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003152}
3153
Rafael Espindolac5754392011-04-12 15:31:05 +00003154/// ParseDirectiveCFISameValue
3155/// ::= .cfi_same_value register
3156bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3157 SMLoc DirectiveLoc) {
3158 int64_t Register = 0;
3159
3160 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3161 return true;
3162
3163 getStreamer().EmitCFISameValue(Register);
3164
3165 return false;
3166}
3167
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003168/// ParseDirectiveCFIRestore
3169/// ::= .cfi_restore register
3170bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003171 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003172 int64_t Register = 0;
3173 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3174 return true;
3175
3176 getStreamer().EmitCFIRestore(Register);
3177
3178 return false;
3179}
3180
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003181/// ParseDirectiveCFIEscape
3182/// ::= .cfi_escape expression[,...]
3183bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003184 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003185 std::string Values;
3186 int64_t CurrValue;
3187 if (getParser().ParseAbsoluteExpression(CurrValue))
3188 return true;
3189
3190 Values.push_back((uint8_t)CurrValue);
3191
3192 while (getLexer().is(AsmToken::Comma)) {
3193 Lex();
3194
3195 if (getParser().ParseAbsoluteExpression(CurrValue))
3196 return true;
3197
3198 Values.push_back((uint8_t)CurrValue);
3199 }
3200
3201 getStreamer().EmitCFIEscape(Values);
3202 return false;
3203}
3204
Rafael Espindola16d7d432012-01-23 21:51:52 +00003205/// ParseDirectiveCFISignalFrame
3206/// ::= .cfi_signal_frame
3207bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3208 SMLoc DirectiveLoc) {
3209 if (getLexer().isNot(AsmToken::EndOfStatement))
3210 return Error(getLexer().getLoc(),
3211 "unexpected token in '" + Directive + "' directive");
3212
3213 getStreamer().EmitCFISignalFrame();
3214
3215 return false;
3216}
3217
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003218/// ParseDirectiveMacrosOnOff
3219/// ::= .macros_on
3220/// ::= .macros_off
3221bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3222 SMLoc DirectiveLoc) {
3223 if (getLexer().isNot(AsmToken::EndOfStatement))
3224 return Error(getLexer().getLoc(),
3225 "unexpected token in '" + Directive + "' directive");
3226
3227 getParser().MacrosEnabled = Directive == ".macros_on";
3228
3229 return false;
3230}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003231
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003232/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003233/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003234bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3235 SMLoc DirectiveLoc) {
3236 StringRef Name;
3237 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003238 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003239
Rafael Espindola8a403d32012-08-08 14:51:03 +00003240 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003241 // Argument delimiter is initially unknown. It will be set by
3242 // ParseMacroArgument()
3243 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003244 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003245 for (;;) {
3246 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003247 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003248 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003249
3250 if (getLexer().is(AsmToken::Equal)) {
3251 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003252 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003253 return true;
3254 }
3255
Rafael Espindola65366442011-06-05 02:43:45 +00003256 Parameters.push_back(Parameter);
3257
Preston Gurd7b6f2032012-09-19 20:36:12 +00003258 if (getLexer().is(AsmToken::Comma))
3259 Lex();
3260 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003261 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003262 }
3263 }
3264
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003265 // Eat the end of statement.
3266 Lex();
3267
3268 AsmToken EndToken, StartToken = getTok();
3269
3270 // Lex the macro definition.
3271 for (;;) {
3272 // Check whether we have reached the end of the file.
3273 if (getLexer().is(AsmToken::Eof))
3274 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3275
3276 // Otherwise, check whether we have reach the .endmacro.
3277 if (getLexer().is(AsmToken::Identifier) &&
3278 (getTok().getIdentifier() == ".endm" ||
3279 getTok().getIdentifier() == ".endmacro")) {
3280 EndToken = getTok();
3281 Lex();
3282 if (getLexer().isNot(AsmToken::EndOfStatement))
3283 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3284 "' directive");
3285 break;
3286 }
3287
3288 // Otherwise, scan til the end of the statement.
3289 getParser().EatToEndOfStatement();
3290 }
3291
3292 if (getParser().MacroMap.lookup(Name)) {
3293 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3294 }
3295
3296 const char *BodyStart = StartToken.getLoc().getPointer();
3297 const char *BodyEnd = EndToken.getLoc().getPointer();
3298 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003299 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003300 return false;
3301}
3302
3303/// ParseDirectiveEndMacro
3304/// ::= .endm
3305/// ::= .endmacro
3306bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003307 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003308 if (getLexer().isNot(AsmToken::EndOfStatement))
3309 return TokError("unexpected token in '" + Directive + "' directive");
3310
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003311 // If we are inside a macro instantiation, terminate the current
3312 // instantiation.
3313 if (!getParser().ActiveMacros.empty()) {
3314 getParser().HandleMacroExit();
3315 return false;
3316 }
3317
3318 // Otherwise, this .endmacro is a stray entry in the file; well formed
3319 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003320 return TokError("unexpected '" + Directive + "' in file, "
3321 "no current macro definition");
3322}
3323
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003324/// ParseDirectivePurgeMacro
3325/// ::= .purgem
3326bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3327 SMLoc DirectiveLoc) {
3328 StringRef Name;
3329 if (getParser().ParseIdentifier(Name))
3330 return TokError("expected identifier in '.purgem' directive");
3331
3332 if (getLexer().isNot(AsmToken::EndOfStatement))
3333 return TokError("unexpected token in '.purgem' directive");
3334
3335 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3336 if (I == getParser().MacroMap.end())
3337 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3338
3339 // Undefine the macro.
3340 delete I->getValue();
3341 getParser().MacroMap.erase(I);
3342 return false;
3343}
3344
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003345bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003346 getParser().CheckForValidSection();
3347
3348 const MCExpr *Value;
3349
3350 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003351 return true;
3352
3353 if (getLexer().isNot(AsmToken::EndOfStatement))
3354 return TokError("unexpected token in directive");
3355
3356 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003357 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003358 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003359 getStreamer().EmitULEB128Value(Value);
3360
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003361 return false;
3362}
3363
Rafael Espindola761cb062012-06-03 23:57:14 +00003364Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003365 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003366
Rafael Espindola761cb062012-06-03 23:57:14 +00003367 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003368 for (;;) {
3369 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003370 if (getLexer().is(AsmToken::Eof)) {
3371 Error(DirectiveLoc, "no matching '.endr' in definition");
3372 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003373 }
3374
Rafael Espindola761cb062012-06-03 23:57:14 +00003375 if (Lexer.is(AsmToken::Identifier) &&
3376 (getTok().getIdentifier() == ".rept")) {
3377 ++NestLevel;
3378 }
3379
3380 // Otherwise, check whether we have reached the .endr.
3381 if (Lexer.is(AsmToken::Identifier) &&
3382 getTok().getIdentifier() == ".endr") {
3383 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003384 EndToken = getTok();
3385 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003386 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3387 TokError("unexpected token in '.endr' directive");
3388 return 0;
3389 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003390 break;
3391 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003392 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003393 }
3394
Rafael Espindola761cb062012-06-03 23:57:14 +00003395 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003396 EatToEndOfStatement();
3397 }
3398
3399 const char *BodyStart = StartToken.getLoc().getPointer();
3400 const char *BodyEnd = EndToken.getLoc().getPointer();
3401 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3402
Rafael Espindola761cb062012-06-03 23:57:14 +00003403 // We Are Anonymous.
3404 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003405 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003406 return new Macro(Name, Body, Parameters);
3407}
3408
3409void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3410 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003411 OS << ".endr\n";
3412
3413 MemoryBuffer *Instantiation =
3414 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3415
Rafael Espindola761cb062012-06-03 23:57:14 +00003416 // Create the macro instantiation object and add to the current macro
3417 // instantiation stack.
3418 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3419 getTok().getLoc(),
3420 Instantiation);
3421 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003422
Rafael Espindola761cb062012-06-03 23:57:14 +00003423 // Jump to the macro instantiation and prime the lexer.
3424 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3425 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3426 Lex();
3427}
3428
3429bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3430 int64_t Count;
3431 if (ParseAbsoluteExpression(Count))
3432 return TokError("unexpected token in '.rept' directive");
3433
3434 if (Count < 0)
3435 return TokError("Count is negative");
3436
3437 if (Lexer.isNot(AsmToken::EndOfStatement))
3438 return TokError("unexpected token in '.rept' directive");
3439
3440 // Eat the end of statement.
3441 Lex();
3442
3443 // Lex the rept definition.
3444 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3445 if (!M)
3446 return true;
3447
3448 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3449 // to hold the macro body with substitutions.
3450 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003451 MacroParameters Parameters;
3452 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003453 raw_svector_ostream OS(Buf);
3454 while (Count--) {
3455 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3456 return true;
3457 }
3458 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003459
3460 return false;
3461}
3462
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003463/// ParseDirectiveIrp
3464/// ::= .irp symbol,values
3465bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003466 MacroParameters Parameters;
3467 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003468
Preston Gurd6c9176a2012-09-19 20:29:04 +00003469 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003470 return TokError("expected identifier in '.irp' directive");
3471
3472 Parameters.push_back(Parameter);
3473
3474 if (Lexer.isNot(AsmToken::Comma))
3475 return TokError("expected comma in '.irp' directive");
3476
3477 Lex();
3478
Rafael Espindola8a403d32012-08-08 14:51:03 +00003479 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003480 if (ParseMacroArguments(0, A))
3481 return true;
3482
3483 // Eat the end of statement.
3484 Lex();
3485
3486 // Lex the irp definition.
3487 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3488 if (!M)
3489 return true;
3490
3491 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3492 // to hold the macro body with substitutions.
3493 SmallString<256> Buf;
3494 raw_svector_ostream OS(Buf);
3495
Rafael Espindola7996d042012-08-21 16:06:48 +00003496 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3497 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003498 Args.push_back(*i);
3499
3500 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3501 return true;
3502 }
3503
3504 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3505
3506 return false;
3507}
3508
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003509/// ParseDirectiveIrpc
3510/// ::= .irpc symbol,values
3511bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003512 MacroParameters Parameters;
3513 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003514
Preston Gurd6c9176a2012-09-19 20:29:04 +00003515 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003516 return TokError("expected identifier in '.irpc' directive");
3517
3518 Parameters.push_back(Parameter);
3519
3520 if (Lexer.isNot(AsmToken::Comma))
3521 return TokError("expected comma in '.irpc' directive");
3522
3523 Lex();
3524
Rafael Espindola8a403d32012-08-08 14:51:03 +00003525 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003526 if (ParseMacroArguments(0, A))
3527 return true;
3528
3529 if (A.size() != 1 || A.front().size() != 1)
3530 return TokError("unexpected token in '.irpc' directive");
3531
3532 // Eat the end of statement.
3533 Lex();
3534
3535 // Lex the irpc definition.
3536 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3537 if (!M)
3538 return true;
3539
3540 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3541 // to hold the macro body with substitutions.
3542 SmallString<256> Buf;
3543 raw_svector_ostream OS(Buf);
3544
3545 StringRef Values = A.front().front().getString();
3546 std::size_t I, End = Values.size();
3547 for (I = 0; I < End; ++I) {
3548 MacroArgument Arg;
3549 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3550
Rafael Espindola8a403d32012-08-08 14:51:03 +00003551 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003552 Args.push_back(Arg);
3553
3554 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3555 return true;
3556 }
3557
3558 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3559
3560 return false;
3561}
3562
Rafael Espindola761cb062012-06-03 23:57:14 +00003563bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3564 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003565 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003566
3567 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003568 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003569 assert(getLexer().is(AsmToken::EndOfStatement));
3570
Rafael Espindola761cb062012-06-03 23:57:14 +00003571 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003572 return false;
3573}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003574
Chad Rosierb1f8c132012-10-18 15:49:34 +00003575namespace {
3576enum AsmOpRewriteKind {
3577 AOK_Imm,
3578 AOK_Input,
3579 AOK_Output
3580};
3581
3582struct AsmOpRewrite {
3583 AsmOpRewriteKind Kind;
3584 SMLoc Loc;
3585 unsigned Len;
3586
3587public:
3588 AsmOpRewrite(AsmOpRewriteKind kind, SMLoc loc, unsigned len)
3589 : Kind(kind), Loc(loc), Len(len) { }
3590};
3591}
3592
3593bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3594 unsigned &NumOutputs, unsigned &NumInputs,
3595 SmallVectorImpl<void *> &Names,
3596 SmallVectorImpl<std::string> &Constraints,
3597 SmallVectorImpl<void *> &Exprs,
3598 SmallVectorImpl<std::string> &Clobbers,
3599 const MCInstrInfo *MII,
3600 const MCInstPrinter *IP,
3601 MCAsmParserSemaCallback &SI) {
3602 SmallVector<void*, 4> Inputs;
3603 SmallVector<void*, 4> Outputs;
3604 SmallVector<std::string, 4> InputConstraints;
3605 SmallVector<std::string, 4> OutputConstraints;
3606 SmallVector<void*, 4> InputExprs;
3607 SmallVector<void*, 4> OutputExprs;
3608 std::set<std::string> ClobberRegs;
3609
3610 SmallVector<struct AsmOpRewrite, 4> AsmStrRewrites;
3611
3612 // Prime the lexer.
3613 Lex();
3614
3615 // While we have input, parse each statement.
3616 unsigned InputIdx = 0;
3617 unsigned OutputIdx = 0;
3618 while (getLexer().isNot(AsmToken::Eof)) {
3619 if (ParseStatement()) return true;
3620
3621 if (isInstruction()) {
3622 const MCInstrDesc &Desc = MII->get(getOpcode());
3623
3624 // Build the list of clobbers, outputs and inputs.
3625 for (unsigned i = 1, e = ParsedOperands.size(); i != e; ++i) {
3626 MCParsedAsmOperand *Operand = ParsedOperands[i];
3627
3628 // Immediate.
3629 if (Operand->isImm()) {
3630 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Imm,
3631 Operand->getStartLoc(),
3632 Operand->getNameLen()));
3633 continue;
3634 }
3635
3636 // Register operand.
3637 if (Operand->isReg()) {
3638 unsigned NumDefs = Desc.getNumDefs();
3639 // Clobber.
3640 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3641 std::string Reg;
3642 raw_string_ostream OS(Reg);
3643 IP->printRegName(OS, Operand->getReg());
3644 ClobberRegs.insert(StringRef(OS.str()));
3645 }
3646 continue;
3647 }
3648
3649 // Expr/Input or Output.
3650 void *II;
3651 void *ExprResult = SI.LookupInlineAsmIdentifier(Operand->getName(),
3652 AsmLoc, &II);
3653 if (ExprResult) {
3654 bool isOutput = (i == 1) && Desc.mayStore();
3655 if (isOutput) {
3656 std::string Constraint = "=";
3657 ++InputIdx;
3658 Outputs.push_back(II);
3659 OutputExprs.push_back(ExprResult);
3660 Constraint += Operand->getConstraint().str();
3661 OutputConstraints.push_back(Constraint);
3662 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Output,
3663 Operand->getStartLoc(),
3664 Operand->getNameLen()));
3665 } else {
3666 Inputs.push_back(II);
3667 InputExprs.push_back(ExprResult);
3668 InputConstraints.push_back(Operand->getConstraint().str());
3669 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Input,
3670 Operand->getStartLoc(),
3671 Operand->getNameLen()));
3672 }
3673 }
3674 }
3675 // Free any parsed operands.
3676 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
3677 delete ParsedOperands[i];
3678 ParsedOperands.clear();
3679 }
3680 }
3681
3682 // Set the number of Outputs and Inputs.
3683 NumOutputs = Outputs.size();
3684 NumInputs = Inputs.size();
3685
3686 // Set the unique clobbers.
3687 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3688 E = ClobberRegs.end(); I != E; ++I)
3689 Clobbers.push_back(*I);
3690
3691 // Merge the various outputs and inputs. Output are expected first.
3692 if (NumOutputs || NumInputs) {
3693 unsigned NumExprs = NumOutputs + NumInputs;
3694 Names.resize(NumExprs);
3695 Constraints.resize(NumExprs);
3696 Exprs.resize(NumExprs);
3697 for (unsigned i = 0; i < NumOutputs; ++i) {
3698 Names[i] = Outputs[i];
3699 Constraints[i] = OutputConstraints[i];
3700 Exprs[i] = OutputExprs[i];
3701 }
3702 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3703 Names[j] = Inputs[i];
3704 Constraints[j] = InputConstraints[i];
3705 Exprs[j] = InputExprs[i];
3706 }
3707 }
3708
3709 // Build the IR assembly string.
3710 std::string AsmStringIR;
3711 raw_string_ostream OS(AsmStringIR);
3712 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3713 for (SmallVectorImpl<struct AsmOpRewrite>::iterator
3714 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3715 const char *Loc = (*I).Loc.getPointer();
3716
3717 // Emit everything up to the immediate/expression.
3718 OS << StringRef(Start, Loc - Start);
3719
3720 // Rewrite expressions in $N notation.
3721 switch ((*I).Kind) {
3722 case AOK_Imm:
3723 OS << Twine("$$") + StringRef(Loc, (*I).Len);
3724 break;
3725 case AOK_Input:
3726 OS << '$';
3727 OS << InputIdx++;
3728 break;
3729 case AOK_Output:
3730 OS << '$';
3731 OS << OutputIdx++;
3732 break;
3733 }
3734
3735 // Skip the original expression.
3736 Start = Loc + (*I).Len;
3737 }
3738
3739 // Emit the remainder of the asm string.
3740 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3741 if (Start != AsmEnd)
3742 OS << StringRef(Start, AsmEnd - Start);
3743
3744 AsmString = OS.str();
3745 return false;
3746}
3747
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003748/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003749MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003750 MCContext &C, MCStreamer &Out,
3751 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003752 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003753}