blob: baf174c680a9598f600775de6395f61233fdcbf8 [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000016#include "llvm/ADT/StringMap.h"
Matt Fleming924c5e52010-05-21 11:36:59 +000017#include "llvm/ADT/StringSwitch.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000021#include "llvm/MC/MCExpr.h"
Chris Lattner29dfe7c2009-06-23 18:41:30 +000022#include "llvm/MC/MCInst.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000023#include "llvm/MC/MCParser/AsmCond.h"
24#include "llvm/MC/MCParser/AsmLexer.h"
25#include "llvm/MC/MCParser/MCAsmParser.h"
26#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000028#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000029#include "llvm/MC/MCSymbol.h"
Kevin Enderby7cbf73a2010-07-28 20:55:35 +000030#include "llvm/MC/MCDwarf.h"
Bill Wendling9bc0af82009-12-28 01:34:57 +000031#include "llvm/Support/Compiler.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000032#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000033#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000034#include "llvm/Support/raw_ostream.h"
Daniel Dunbara3af3702009-07-20 18:55:04 +000035#include "llvm/Target/TargetAsmParser.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000036#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000037using namespace llvm;
38
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000039namespace {
40
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000041/// \brief Helper class for tracking macro definitions.
42struct Macro {
43 StringRef Name;
44 StringRef Body;
45
46public:
47 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
48};
49
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000050/// \brief Helper class for storing information about an active macro
51/// instantiation.
52struct MacroInstantiation {
53 /// The macro being instantiated.
54 const Macro *TheMacro;
55
56 /// The macro instantiation with substitutions.
57 MemoryBuffer *Instantiation;
58
59 /// The location of the instantiation.
60 SMLoc InstantiationLoc;
61
62 /// The location where parsing should resume upon instantiation completion.
63 SMLoc ExitLoc;
64
65public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000066 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
67 const std::vector<std::vector<AsmToken> > &A);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000068};
69
Daniel Dunbaraef87e32010-07-18 18:31:38 +000070/// \brief The concrete assembly parser instance.
71class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +000072 friend class GenericAsmParser;
73
Daniel Dunbaraef87e32010-07-18 18:31:38 +000074 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
75 void operator=(const AsmParser &); // DO NOT IMPLEMENT
76private:
77 AsmLexer Lexer;
78 MCContext &Ctx;
79 MCStreamer &Out;
80 SourceMgr &SrcMgr;
81 MCAsmParserExtension *GenericParser;
82 MCAsmParserExtension *PlatformParser;
Daniel Dunbar3c802de2010-07-18 18:38:02 +000083
Daniel Dunbaraef87e32010-07-18 18:31:38 +000084 /// This is the current buffer index we're lexing from as managed by the
85 /// SourceMgr object.
86 int CurBuffer;
87
88 AsmCond TheCondState;
89 std::vector<AsmCond> TheCondStack;
90
91 /// DirectiveMap - This is a table handlers for directives. Each handler is
92 /// invoked after the directive identifier is read and is responsible for
93 /// parsing and validating the rest of the directive. The handler is passed
94 /// in the directive name and the location of the directive keyword.
95 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +000096
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000097 /// MacroMap - Map of currently defined macros.
98 StringMap<Macro*> MacroMap;
99
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000100 /// ActiveMacros - Stack of active macro instantiations.
101 std::vector<MacroInstantiation*> ActiveMacros;
102
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000103 /// Boolean tracking whether macro substitution is enabled.
104 unsigned MacrosEnabled : 1;
105
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000106 /// Flag tracking whether any errors have been encountered.
107 unsigned HadError : 1;
108
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000109public:
110 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
111 const MCAsmInfo &MAI);
112 ~AsmParser();
113
114 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
115
116 void AddDirectiveHandler(MCAsmParserExtension *Object,
117 StringRef Directive,
118 DirectiveHandler Handler) {
119 DirectiveMap[Directive] = std::make_pair(Object, Handler);
120 }
121
122public:
123 /// @name MCAsmParser Interface
124 /// {
125
126 virtual SourceMgr &getSourceManager() { return SrcMgr; }
127 virtual MCAsmLexer &getLexer() { return Lexer; }
128 virtual MCContext &getContext() { return Ctx; }
129 virtual MCStreamer &getStreamer() { return Out; }
130
131 virtual void Warning(SMLoc L, const Twine &Meg);
132 virtual bool Error(SMLoc L, const Twine &Msg);
133
134 const AsmToken &Lex();
135
136 bool ParseExpression(const MCExpr *&Res);
137 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
138 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
139 virtual bool ParseAbsoluteExpression(int64_t &Res);
140
141 /// }
142
143private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000144 void CheckForValidSection();
145
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000146 bool ParseStatement();
147
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000148 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
149 void HandleMacroExit();
150
151 void PrintMacroInstantiations();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000152 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
153
154 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
155 bool EnterIncludeFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000156
157 /// \brief Reset the current lexer position to that given by \arg Loc. The
158 /// current token is not set; clients should ensure Lex() is called
159 /// subsequently.
160 void JumpToLoc(SMLoc Loc);
161
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000162 void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000163
164 /// \brief Parse up to the end of statement and a return the contents from the
165 /// current token until the end of the statement; the current token on exit
166 /// will be either the EndOfStatement or EOF.
167 StringRef ParseStringToEndOfStatement();
168
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000169 bool ParseAssignment(StringRef Name);
170
171 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
172 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
173 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
174
175 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
176 /// and set \arg Res to the identifier contents.
177 bool ParseIdentifier(StringRef &Res);
178
179 // Directive Parsing.
180 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
181 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000182 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000183 bool ParseDirectiveFill(); // ".fill"
184 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000185 bool ParseDirectiveZero(); // ".zero"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000186 bool ParseDirectiveSet(); // ".set"
187 bool ParseDirectiveOrg(); // ".org"
188 // ".align{,32}", ".p2align{,w,l}"
189 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
190
191 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
192 /// accepts a single symbol (which should be a label or an external).
193 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
194 bool ParseDirectiveELFType(); // ELF specific ".type"
195
196 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
197
198 bool ParseDirectiveAbort(); // ".abort"
199 bool ParseDirectiveInclude(); // ".include"
200
201 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
202 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
203 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
204 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
205
206 /// ParseEscapedString - Parse the current token as a string which may include
207 /// escaped characters and return the string contents.
208 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000209
210 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
211 MCSymbolRefExpr::VariantKind Variant);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000212};
213
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000214/// \brief Generic implementations of directive handling, etc. which is shared
215/// (or the default, at least) for all assembler parser.
216class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000217 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
218 void AddDirectiveHandler(StringRef Directive) {
219 getParser().AddDirectiveHandler(this, Directive,
220 HandleDirective<GenericAsmParser, Handler>);
221 }
222
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000223public:
224 GenericAsmParser() {}
225
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000226 AsmParser &getParser() {
227 return (AsmParser&) this->MCAsmParserExtension::getParser();
228 }
229
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000230 virtual void Initialize(MCAsmParser &Parser) {
231 // Call the base implementation.
232 this->MCAsmParserExtension::Initialize(Parser);
233
234 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000235 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
236 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
237 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000238
239 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
241 ".macros_on");
242 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
243 ".macros_off");
244 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
245 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
246 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000247
248 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
249 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000250 }
251
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000252 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
253 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
254 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000255
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000256 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000257 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
258 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000259
260 void ParseUleb128(uint64_t Value);
261 void ParseSleb128(int64_t Value);
262 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000263};
264
265}
266
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000267namespace llvm {
268
269extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000270extern MCAsmParserExtension *createELFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000271
272}
273
Chris Lattneraaec2052010-01-19 19:46:13 +0000274enum { DEFAULT_ADDRSPACE = 0 };
275
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000276AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
277 MCStreamer &_Out, const MCAsmInfo &_MAI)
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000278 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
Daniel Dunbare4749702010-07-12 18:12:02 +0000279 GenericParser(new GenericAsmParser), PlatformParser(0),
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000280 CurBuffer(0), MacrosEnabled(true) {
Sean Callananfd0b0282010-01-21 00:19:58 +0000281 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000282
283 // Initialize the generic parser.
284 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000285
286 // Initialize the platform / file format parser.
287 //
288 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
289 // created.
290 if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000291 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000292 PlatformParser->Initialize(*this);
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000293 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000294 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000295 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000296 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000297}
298
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000299AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000300 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
301
302 // Destroy any macros.
303 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
304 ie = MacroMap.end(); it != ie; ++it)
305 delete it->getValue();
306
Daniel Dunbare4749702010-07-12 18:12:02 +0000307 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000308 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000309}
310
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000311void AsmParser::PrintMacroInstantiations() {
312 // Print the active macro instantiation stack.
313 for (std::vector<MacroInstantiation*>::const_reverse_iterator
314 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
315 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
316 "note");
317}
318
Daniel Dunbarf9507ff2009-07-27 23:20:52 +0000319void AsmParser::Warning(SMLoc L, const Twine &Msg) {
Sean Callananbf2013e2010-01-20 23:19:55 +0000320 PrintMessage(L, Msg.str(), "warning");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000321 PrintMacroInstantiations();
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000322}
323
Daniel Dunbarf9507ff2009-07-27 23:20:52 +0000324bool AsmParser::Error(SMLoc L, const Twine &Msg) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000325 HadError = true;
Sean Callananbf2013e2010-01-20 23:19:55 +0000326 PrintMessage(L, Msg.str(), "error");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000327 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000328 return true;
329}
330
Sean Callananbf2013e2010-01-20 23:19:55 +0000331void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
332 const char *Type) const {
333 SrcMgr.PrintMessage(Loc, Msg, Type);
334}
Sean Callananfd0b0282010-01-21 00:19:58 +0000335
336bool AsmParser::EnterIncludeFile(const std::string &Filename) {
337 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
338 if (NewBuf == -1)
339 return true;
Sean Callanan79036e42010-01-20 22:18:24 +0000340
Sean Callananfd0b0282010-01-21 00:19:58 +0000341 CurBuffer = NewBuf;
342
343 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
344
345 return false;
346}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000347
348void AsmParser::JumpToLoc(SMLoc Loc) {
349 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
350 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
351}
352
Sean Callananfd0b0282010-01-21 00:19:58 +0000353const AsmToken &AsmParser::Lex() {
354 const AsmToken *tok = &Lexer.Lex();
355
356 if (tok->is(AsmToken::Eof)) {
357 // If this is the end of an included file, pop the parent file off the
358 // include stack.
359 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
360 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000361 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000362 tok = &Lexer.Lex();
363 }
364 }
365
366 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000367 Error(Lexer.getErrLoc(), Lexer.getErr());
Sean Callanan79036e42010-01-20 22:18:24 +0000368
Sean Callananfd0b0282010-01-21 00:19:58 +0000369 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000370}
371
Chris Lattner79180e22010-04-05 23:15:42 +0000372bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000373 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000374 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000375 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000376
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000377 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000378 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000379
380 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000381 AsmCond StartingCondState = TheCondState;
382
Chris Lattnerb717fb02009-07-02 21:53:43 +0000383 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000384 while (Lexer.isNot(AsmToken::Eof)) {
Chris Lattnerb717fb02009-07-02 21:53:43 +0000385 if (!ParseStatement()) continue;
386
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000387 // We had an error, validate that one was emitted and recover by skipping to
388 // the next line.
389 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000390 EatToEndOfStatement();
391 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000392
393 if (TheCondState.TheCond != StartingCondState.TheCond ||
394 TheCondState.Ignore != StartingCondState.Ignore)
395 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000396
397 // Check to see there are no empty DwarfFile slots.
398 const std::vector<MCDwarfFile *> &MCDwarfFiles =
399 getContext().getMCDwarfFiles();
400 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000401 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000402 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000403 }
Chris Lattnerb717fb02009-07-02 21:53:43 +0000404
Chris Lattner79180e22010-04-05 23:15:42 +0000405 // Finalize the output stream if there are no errors and if the client wants
406 // us to.
407 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000408 Out.Finish();
409
Chris Lattnerb717fb02009-07-02 21:53:43 +0000410 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000411}
412
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000413void AsmParser::CheckForValidSection() {
414 if (!getStreamer().getCurrentSection()) {
415 TokError("expected section directive before assembly directive");
416 Out.SwitchSection(Ctx.getMachOSection(
417 "__TEXT", "__text",
418 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
419 0, SectionKind::getText()));
420 }
421}
422
Chris Lattner2cf5f142009-06-22 01:29:09 +0000423/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
424void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000425 while (Lexer.isNot(AsmToken::EndOfStatement) &&
426 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000427 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000428
429 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000430 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000431 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000432}
433
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000434StringRef AsmParser::ParseStringToEndOfStatement() {
435 const char *Start = getTok().getLoc().getPointer();
436
437 while (Lexer.isNot(AsmToken::EndOfStatement) &&
438 Lexer.isNot(AsmToken::Eof))
439 Lex();
440
441 const char *End = getTok().getLoc().getPointer();
442 return StringRef(Start, End - Start);
443}
Chris Lattnerc4193832009-06-22 05:51:26 +0000444
Chris Lattner74ec1a32009-06-22 06:32:03 +0000445/// ParseParenExpr - Parse a paren expression and return it.
446/// NOTE: This assumes the leading '(' has already been consumed.
447///
448/// parenexpr ::= expr)
449///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000450bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000451 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000452 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000453 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000454 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000455 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000456 return false;
457}
Chris Lattnerc4193832009-06-22 05:51:26 +0000458
Chris Lattner74ec1a32009-06-22 06:32:03 +0000459/// ParsePrimaryExpr - Parse a primary expression and return it.
460/// primaryexpr ::= (parenexpr
461/// primaryexpr ::= symbol
462/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000463/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000464/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000465bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000466 switch (Lexer.getKind()) {
467 default:
468 return TokError("unknown token in expression");
Daniel Dunbar3f872332009-07-28 16:08:33 +0000469 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000470 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000471 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000472 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000473 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000474 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000475 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000476 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000477 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000478 EndLoc = Lexer.getLoc();
479
480 StringRef Identifier;
481 if (ParseIdentifier(Identifier))
482 return false;
483
Daniel Dunbarfffff912009-10-16 01:34:54 +0000484 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000485 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000486 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000487
Daniel Dunbar525a3a62010-05-17 17:46:23 +0000488 // Mark the symbol as used in an expression.
489 Sym->setUsedInExpr(true);
490
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000491 // Lookup the symbol variant if used.
492 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000493 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000494 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000495 if (Variant == MCSymbolRefExpr::VK_Invalid) {
496 Variant = MCSymbolRefExpr::VK_None;
497 TokError("invalid variant '" + Split.second + "'");
498 }
499 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000500
Daniel Dunbarfffff912009-10-16 01:34:54 +0000501 // If this is an absolute variable reference, substitute it now to preserve
502 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000503 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000504 if (Variant)
505 return Error(EndLoc, "unexpected modified on variable reference");
506
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000507 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000508 return false;
509 }
510
511 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000512 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000513 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000514 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000515 case AsmToken::Integer: {
516 SMLoc Loc = getTok().getLoc();
517 int64_t IntVal = getTok().getIntVal();
518 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000519 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000520 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000521 // Look for 'b' or 'f' following an Integer as a directional label
522 if (Lexer.getKind() == AsmToken::Identifier) {
523 StringRef IDVal = getTok().getString();
524 if (IDVal == "f" || IDVal == "b"){
525 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
526 IDVal == "f" ? 1 : 0);
527 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
528 getContext());
529 if(IDVal == "b" && Sym->isUndefined())
530 return Error(Loc, "invalid reference to undefined symbol");
531 EndLoc = Lexer.getLoc();
532 Lex(); // Eat identifier.
533 }
534 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000535 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000536 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000537 case AsmToken::Dot: {
538 // This is a '.' reference, which references the current PC. Emit a
539 // temporary label to the streamer and refer to it.
540 MCSymbol *Sym = Ctx.CreateTempSymbol();
541 Out.EmitLabel(Sym);
542 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
543 EndLoc = Lexer.getLoc();
544 Lex(); // Eat identifier.
545 return false;
546 }
547
Daniel Dunbar3f872332009-07-28 16:08:33 +0000548 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000549 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000550 return ParseParenExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000551 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000552 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000553 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000554 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000555 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000556 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000557 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000558 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000559 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000560 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000561 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000562 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000563 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000564 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000565 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000566 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000567 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000568 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000569 }
570}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000571
Chris Lattnerb4307b32010-01-15 19:28:38 +0000572bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000573 SMLoc EndLoc;
574 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000575}
576
Daniel Dunbarcceba832010-09-17 02:47:07 +0000577const MCExpr *
578AsmParser::ApplyModifierToExpr(const MCExpr *E,
579 MCSymbolRefExpr::VariantKind Variant) {
580 // Recurse over the given expression, rebuilding it to apply the given variant
581 // if there is exactly one symbol.
582 switch (E->getKind()) {
583 case MCExpr::Target:
584 case MCExpr::Constant:
585 return 0;
586
587 case MCExpr::SymbolRef: {
588 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
589
590 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
591 TokError("invalid variant on expression '" +
592 getTok().getIdentifier() + "' (already modified)");
593 return E;
594 }
595
596 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
597 }
598
599 case MCExpr::Unary: {
600 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
601 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
602 if (!Sub)
603 return 0;
604 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
605 }
606
607 case MCExpr::Binary: {
608 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
609 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
610 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
611
612 if (!LHS && !RHS)
613 return 0;
614
615 if (!LHS) LHS = BE->getLHS();
616 if (!RHS) RHS = BE->getRHS();
617
618 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
619 }
620 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000621
622 assert(0 && "Invalid expression kind!");
623 return 0;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000624}
625
Chris Lattner74ec1a32009-06-22 06:32:03 +0000626/// ParseExpression - Parse an expression and return it.
627///
628/// expr ::= expr +,- expr -> lowest.
629/// expr ::= expr |,^,&,! expr -> middle.
630/// expr ::= expr *,/,%,<<,>> expr -> highest.
631/// expr ::= primaryexpr
632///
Chris Lattner54482b42010-01-15 19:39:23 +0000633bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000634 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000635 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000636 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
637 return true;
638
Daniel Dunbarcceba832010-09-17 02:47:07 +0000639 // As a special case, we support 'a op b @ modifier' by rewriting the
640 // expression to include the modifier. This is inefficient, but in general we
641 // expect users to use 'a@modifier op b'.
642 if (Lexer.getKind() == AsmToken::At) {
643 Lex();
644
645 if (Lexer.isNot(AsmToken::Identifier))
646 return TokError("unexpected symbol modifier following '@'");
647
648 MCSymbolRefExpr::VariantKind Variant =
649 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
650 if (Variant == MCSymbolRefExpr::VK_Invalid)
651 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
652
653 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
654 if (!ModifiedRes) {
655 return TokError("invalid modifier '" + getTok().getIdentifier() +
656 "' (no symbols present)");
657 return true;
658 }
659
660 Res = ModifiedRes;
661 Lex();
662 }
663
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000664 // Try to constant fold it up front, if possible.
665 int64_t Value;
666 if (Res->EvaluateAsAbsolute(Value))
667 Res = MCConstantExpr::Create(Value, getContext());
668
669 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000670}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000671
Chris Lattnerb4307b32010-01-15 19:28:38 +0000672bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000673 Res = 0;
674 return ParseParenExpr(Res, EndLoc) ||
675 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000676}
677
Daniel Dunbar475839e2009-06-29 20:37:27 +0000678bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000679 const MCExpr *Expr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000680
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000681 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000682 if (ParseExpression(Expr))
683 return true;
684
Daniel Dunbare00b0112009-10-16 01:57:52 +0000685 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000686 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000687
688 return false;
689}
690
Daniel Dunbar3f872332009-07-28 16:08:33 +0000691static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000692 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000693 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000694 default:
695 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000696
Daniel Dunbarcceba832010-09-17 02:47:07 +0000697 // Lowest Precedence: &&, ||, @
Daniel Dunbar3f872332009-07-28 16:08:33 +0000698 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000699 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000700 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000701 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000702 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000703 return 1;
704
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000705
706 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000707 //
708 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000709 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000710 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000711 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000712 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000713 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000714 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000715 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000716 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000717 return 2;
718
719 // Intermediate Precedence: +, -, ==, !=, <>, <, <=, >, >=
720 case AsmToken::Plus:
721 Kind = MCBinaryExpr::Add;
722 return 3;
723 case AsmToken::Minus:
724 Kind = MCBinaryExpr::Sub;
725 return 3;
726 case AsmToken::EqualEqual:
727 Kind = MCBinaryExpr::EQ;
728 return 3;
729 case AsmToken::ExclaimEqual:
730 case AsmToken::LessGreater:
731 Kind = MCBinaryExpr::NE;
732 return 3;
733 case AsmToken::Less:
734 Kind = MCBinaryExpr::LT;
735 return 3;
736 case AsmToken::LessEqual:
737 Kind = MCBinaryExpr::LTE;
738 return 3;
739 case AsmToken::Greater:
740 Kind = MCBinaryExpr::GT;
741 return 3;
742 case AsmToken::GreaterEqual:
743 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000744 return 3;
745
746 // Highest Precedence: *, /, %, <<, >>
Daniel Dunbar3f872332009-07-28 16:08:33 +0000747 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000748 Kind = MCBinaryExpr::Mul;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000749 return 4;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000750 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000751 Kind = MCBinaryExpr::Div;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000752 return 4;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000753 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000754 Kind = MCBinaryExpr::Mod;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000755 return 4;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000756 case AsmToken::LessLess:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000757 Kind = MCBinaryExpr::Shl;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000758 return 4;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000759 case AsmToken::GreaterGreater:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000760 Kind = MCBinaryExpr::Shr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000761 return 4;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000762 }
763}
764
765
766/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
767/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000768bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
769 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000770 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000771 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000772 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000773
774 // If the next token is lower precedence than we are allowed to eat, return
775 // successfully with what we ate already.
776 if (TokPrec < Precedence)
777 return false;
778
Sean Callanan79ed1a82010-01-19 20:22:31 +0000779 Lex();
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000780
781 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000782 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +0000783 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000784
785 // If BinOp binds less tightly with RHS than the operator after RHS, let
786 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000787 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000788 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000789 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +0000790 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000791 }
792
Daniel Dunbar475839e2009-06-29 20:37:27 +0000793 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000794 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000795 }
796}
797
Chris Lattnerc4193832009-06-22 05:51:26 +0000798
799
800
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000801/// ParseStatement:
802/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +0000803/// ::= Label* Directive ...Operands... EndOfStatement
804/// ::= Label* Identifier OperandList* EndOfStatement
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000805bool AsmParser::ParseStatement() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000806 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +0000807 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000808 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000809 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000810 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000811
812 // Statements always start with an identifier.
Sean Callanan18b83232010-01-19 21:44:56 +0000813 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +0000814 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000815 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000816 int64_t LocalLabelVal = -1;
817 // GUESS allow an integer followed by a ':' as a directional local label
818 if (Lexer.is(AsmToken::Integer)) {
819 LocalLabelVal = getTok().getIntVal();
820 if (LocalLabelVal < 0) {
821 if (!TheCondState.Ignore)
822 return TokError("unexpected token at start of statement");
823 IDVal = "";
824 }
825 else {
826 IDVal = getTok().getString();
827 Lex(); // Consume the integer token to be used as an identifier token.
828 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +0000829 if (!TheCondState.Ignore)
830 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000831 }
832 }
833 }
834 else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +0000835 if (!TheCondState.Ignore)
836 return TokError("unexpected token at start of statement");
837 IDVal = "";
838 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000839
Chris Lattner7834fac2010-04-17 18:14:27 +0000840 // Handle conditional assembly here before checking for skipping. We
841 // have to do this so that .endif isn't skipped in a ".if 0" block for
842 // example.
843 if (IDVal == ".if")
844 return ParseDirectiveIf(IDLoc);
845 if (IDVal == ".elseif")
846 return ParseDirectiveElseIf(IDLoc);
847 if (IDVal == ".else")
848 return ParseDirectiveElse(IDLoc);
849 if (IDVal == ".endif")
850 return ParseDirectiveEndIf(IDLoc);
851
852 // If we are in a ".if 0" block, ignore this statement.
853 if (TheCondState.Ignore) {
854 EatToEndOfStatement();
855 return false;
856 }
857
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000858 // FIXME: Recurse on local labels?
859
860 // See what kind of statement we have.
861 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000862 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000863 CheckForValidSection();
864
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000865 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000866 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +0000867
868 // Diagnose attempt to use a variable as a label.
869 //
870 // FIXME: Diagnostics. Note the location of the definition as a label.
871 // FIXME: This doesn't diagnose assignment to a symbol which has been
872 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000873 MCSymbol *Sym;
874 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000875 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000876 else
877 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +0000878 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +0000879 return Error(IDLoc, "invalid symbol redefinition");
Chris Lattnerc69485e2009-06-24 04:31:49 +0000880
Daniel Dunbar959fd882009-08-26 22:13:22 +0000881 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +0000882 Out.EmitLabel(Sym);
883
Daniel Dunbar01777ff2010-05-23 18:36:34 +0000884 // Consume any end of statement token, if present, to avoid spurious
885 // AddBlankLine calls().
886 if (Lexer.is(AsmToken::EndOfStatement)) {
887 Lex();
888 if (Lexer.is(AsmToken::Eof))
889 return false;
890 }
891
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000892 return ParseStatement();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +0000893 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +0000894
Daniel Dunbar3f872332009-07-28 16:08:33 +0000895 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +0000896 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +0000897 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +0000898
Daniel Dunbare2ace502009-08-31 08:09:09 +0000899 return ParseAssignment(IDVal);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +0000900
901 default: // Normal instruction or directive.
902 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000903 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000904
905 // If macros are enabled, check to see if this is a macro instantiation.
906 if (MacrosEnabled)
907 if (const Macro *M = MacroMap.lookup(IDVal))
908 return HandleMacroEntry(IDVal, IDLoc, M);
909
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000910 // Otherwise, we have a normal instruction or directive.
Chris Lattner2cf5f142009-06-22 01:29:09 +0000911 if (IDVal[0] == '.') {
Daniel Dunbar8f780cd2009-06-25 21:56:11 +0000912 // Assembler features
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000913 if (IDVal == ".set")
Daniel Dunbar8f780cd2009-06-25 21:56:11 +0000914 return ParseDirectiveSet();
915
Daniel Dunbara0d14262009-06-24 23:30:00 +0000916 // Data directives
917
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000918 if (IDVal == ".ascii")
Daniel Dunbara0d14262009-06-24 23:30:00 +0000919 return ParseDirectiveAscii(false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000920 if (IDVal == ".asciz")
Daniel Dunbara0d14262009-06-24 23:30:00 +0000921 return ParseDirectiveAscii(true);
922
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000923 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +0000924 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +0000925 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +0000926 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000927 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +0000928 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000929 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +0000930 return ParseDirectiveValue(8);
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000931 if (IDVal == ".single")
932 return ParseDirectiveRealValue(APFloat::IEEEsingle);
933 if (IDVal == ".double")
934 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +0000935
Eli Friedman5d68ec22010-07-19 04:17:25 +0000936 if (IDVal == ".align") {
937 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
938 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
939 }
940 if (IDVal == ".align32") {
941 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
942 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
943 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000944 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +0000945 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000946 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +0000947 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000948 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +0000949 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000950 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +0000951 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000952 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +0000953 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000954 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +0000955 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
956
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000957 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +0000958 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +0000959
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000960 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +0000961 return ParseDirectiveFill();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000962 if (IDVal == ".space")
Daniel Dunbara0d14262009-06-24 23:30:00 +0000963 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000964 if (IDVal == ".zero")
965 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +0000966
Daniel Dunbard7b267b2009-06-30 00:33:19 +0000967 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +0000968
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000969 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000970 return ParseDirectiveSymbolAttribute(MCSA_Global);
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000971 // ELF only? Should it be here?
972 if (IDVal == ".local")
973 return ParseDirectiveSymbolAttribute(MCSA_Local);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000974 if (IDVal == ".hidden")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000975 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000976 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000977 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000978 if (IDVal == ".internal")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000979 return ParseDirectiveSymbolAttribute(MCSA_Internal);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000980 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000981 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000982 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000983 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000984 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000985 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000986 if (IDVal == ".protected")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000987 return ParseDirectiveSymbolAttribute(MCSA_Protected);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000988 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000989 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Matt Fleming924c5e52010-05-21 11:36:59 +0000990 if (IDVal == ".type")
991 return ParseDirectiveELFType();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000992 if (IDVal == ".weak")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000993 return ParseDirectiveSymbolAttribute(MCSA_Weak);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000994 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000995 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +0000996 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000997 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +0000998 if (IDVal == ".weak_def_can_be_hidden")
999 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001000
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001001 if (IDVal == ".comm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001002 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001003 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001004 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001005
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001006 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001007 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001008 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001009 return ParseDirectiveInclude();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001010
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001011 // Look up the handler in the handler table.
1012 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1013 DirectiveMap.lookup(IDVal);
1014 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001015 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001016
Kevin Enderby9c656452009-09-10 20:51:44 +00001017 // Target hook for parsing target specific directives.
1018 if (!getTargetParser().ParseDirective(ID))
1019 return false;
1020
Daniel Dunbar3fb76832009-06-30 00:49:23 +00001021 Warning(IDLoc, "ignoring directive for now");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001022 EatToEndOfStatement();
1023 return false;
1024 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001025
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001026 CheckForValidSection();
1027
Chris Lattnera7f13542010-05-19 23:34:33 +00001028 // Canonicalize the opcode to lower case.
1029 SmallString<128> Opcode;
1030 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1031 Opcode.push_back(tolower(IDVal[i]));
1032
Chris Lattner98986712010-01-14 22:21:20 +00001033 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
Chris Lattnera7f13542010-05-19 23:34:33 +00001034 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001035 ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001036
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001037 // Dump the parsed representation, if requested.
1038 if (getShowParsedOperands()) {
1039 SmallString<256> Str;
1040 raw_svector_ostream OS(Str);
1041 OS << "parsed instruction: [";
1042 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1043 if (i != 0)
1044 OS << ", ";
1045 ParsedOperands[i]->dump(OS);
1046 }
1047 OS << "]";
1048
1049 PrintMessage(IDLoc, OS.str(), "note");
1050 }
1051
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001052 // If parsing succeeded, match the instruction.
1053 if (!HadError) {
1054 MCInst Inst;
Daniel Dunbarf1e29d42010-08-12 00:55:38 +00001055 if (!getTargetParser().MatchInstruction(IDLoc, ParsedOperands, Inst)) {
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001056 // Emit the instruction on success.
1057 Out.EmitInstruction(Inst);
Daniel Dunbarf1e29d42010-08-12 00:55:38 +00001058 } else
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001059 HadError = true;
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001060 }
Chris Lattner98986712010-01-14 22:21:20 +00001061
Chris Lattner98986712010-01-14 22:21:20 +00001062 // Free any parsed operands.
1063 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1064 delete ParsedOperands[i];
1065
Chris Lattnercbf8a982010-09-11 16:18:25 +00001066 // Don't skip the rest of the line, the instruction parser is responsible for
1067 // that.
1068 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001069}
Chris Lattner9a023f72009-06-24 04:43:34 +00001070
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001071MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1072 const std::vector<std::vector<AsmToken> > &A)
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001073 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1074{
1075 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1076 // to hold the macro body with substitutions.
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001077 SmallString<256> Buf;
1078 raw_svector_ostream OS(Buf);
1079
1080 StringRef Body = M->Body;
1081 while (!Body.empty()) {
1082 // Scan for the next substitution.
1083 std::size_t End = Body.size(), Pos = 0;
1084 for (; Pos != End; ++Pos) {
1085 // Check for a substitution or escape.
1086 if (Body[Pos] != '$' || Pos + 1 == End)
1087 continue;
1088
1089 char Next = Body[Pos + 1];
1090 if (Next == '$' || Next == 'n' || isdigit(Next))
1091 break;
1092 }
1093
1094 // Add the prefix.
1095 OS << Body.slice(0, Pos);
1096
1097 // Check if we reached the end.
1098 if (Pos == End)
1099 break;
1100
1101 switch (Body[Pos+1]) {
1102 // $$ => $
1103 case '$':
1104 OS << '$';
1105 break;
1106
1107 // $n => number of arguments
1108 case 'n':
1109 OS << A.size();
1110 break;
1111
1112 // $[0-9] => argument
1113 default: {
1114 // Missing arguments are ignored.
1115 unsigned Index = Body[Pos+1] - '0';
1116 if (Index >= A.size())
1117 break;
1118
1119 // Otherwise substitute with the token values, with spaces eliminated.
1120 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1121 ie = A[Index].end(); it != ie; ++it)
1122 OS << it->getString();
1123 break;
1124 }
1125 }
1126
1127 // Update the scan point.
1128 Body = Body.substr(Pos + 2);
1129 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001130
1131 // We include the .endmacro in the buffer as our queue to exit the macro
1132 // instantiation.
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001133 OS << ".endmacro\n";
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001134
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001135 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001136}
1137
1138bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1139 const Macro *M) {
1140 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1141 // this, although we should protect against infinite loops.
1142 if (ActiveMacros.size() == 20)
1143 return TokError("macros cannot be nested more than 20 levels deep");
1144
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001145 // Parse the macro instantiation arguments.
1146 std::vector<std::vector<AsmToken> > MacroArguments;
1147 MacroArguments.push_back(std::vector<AsmToken>());
1148 unsigned ParenLevel = 0;
1149 for (;;) {
1150 if (Lexer.is(AsmToken::Eof))
1151 return TokError("unexpected token in macro instantiation");
1152 if (Lexer.is(AsmToken::EndOfStatement))
1153 break;
1154
1155 // If we aren't inside parentheses and this is a comma, start a new token
1156 // list.
1157 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1158 MacroArguments.push_back(std::vector<AsmToken>());
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001159 } else {
Daniel Dunbare25c6b92010-08-10 17:38:52 +00001160 // Adjust the current parentheses level.
1161 if (Lexer.is(AsmToken::LParen))
1162 ++ParenLevel;
1163 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1164 --ParenLevel;
1165
1166 // Append the token to the current argument list.
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001167 MacroArguments.back().push_back(getTok());
1168 }
1169 Lex();
1170 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001171
1172 // Create the macro instantiation object and add to the current macro
1173 // instantiation stack.
1174 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001175 getTok().getLoc(),
1176 MacroArguments);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001177 ActiveMacros.push_back(MI);
1178
1179 // Jump to the macro instantiation and prime the lexer.
1180 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1181 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1182 Lex();
1183
1184 return false;
1185}
1186
1187void AsmParser::HandleMacroExit() {
1188 // Jump to the EndOfStatement we should return to, and consume it.
1189 JumpToLoc(ActiveMacros.back()->ExitLoc);
1190 Lex();
1191
1192 // Pop the instantiation entry.
1193 delete ActiveMacros.back();
1194 ActiveMacros.pop_back();
1195}
1196
Benjamin Kramer38e59892010-07-14 22:38:02 +00001197bool AsmParser::ParseAssignment(StringRef Name) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001198 // FIXME: Use better location, we should use proper tokens.
1199 SMLoc EqualLoc = Lexer.getLoc();
1200
Daniel Dunbar821e3332009-08-31 08:09:28 +00001201 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001202 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001203 return true;
1204
Daniel Dunbar3f872332009-07-28 16:08:33 +00001205 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001206 return TokError("unexpected token in assignment");
1207
1208 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001209 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001210
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001211 // Validate that the LHS is allowed to be a variable (either it has not been
1212 // used as a symbol, or it is an absolute symbol).
1213 MCSymbol *Sym = getContext().LookupSymbol(Name);
1214 if (Sym) {
1215 // Diagnose assignment to a label.
1216 //
1217 // FIXME: Diagnostics. Note the location of the definition as a label.
1218 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001219 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1220 ; // Allow redefinitions of undefined symbols only used in directives.
1221 else if (!Sym->isUndefined() && !Sym->isAbsolute())
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001222 return Error(EqualLoc, "redefinition of '" + Name + "'");
1223 else if (!Sym->isVariable())
1224 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001225 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001226 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1227 Name + "'");
1228 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001229 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001230
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001231 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001232
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001233 Sym->setUsedInExpr(true);
1234
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001235 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001236 Out.EmitAssignment(Sym, Value);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001237
1238 return false;
1239}
1240
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001241/// ParseIdentifier:
1242/// ::= identifier
1243/// ::= string
1244bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001245 // The assembler has relaxed rules for accepting identifiers, in particular we
1246 // allow things like '.globl $foo', which would normally be separate
1247 // tokens. At this level, we have already lexed so we cannot (currently)
1248 // handle this as a context dependent token, instead we detect adjacent tokens
1249 // and return the combined identifier.
1250 if (Lexer.is(AsmToken::Dollar)) {
1251 SMLoc DollarLoc = getLexer().getLoc();
1252
1253 // Consume the dollar sign, and check for a following identifier.
1254 Lex();
1255 if (Lexer.isNot(AsmToken::Identifier))
1256 return true;
1257
1258 // We have a '$' followed by an identifier, make sure they are adjacent.
1259 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1260 return true;
1261
1262 // Construct the joined identifier and consume the token.
1263 Res = StringRef(DollarLoc.getPointer(),
1264 getTok().getIdentifier().size() + 1);
1265 Lex();
1266 return false;
1267 }
1268
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001269 if (Lexer.isNot(AsmToken::Identifier) &&
1270 Lexer.isNot(AsmToken::String))
1271 return true;
1272
Sean Callanan18b83232010-01-19 21:44:56 +00001273 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001274
Sean Callanan79ed1a82010-01-19 20:22:31 +00001275 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001276
1277 return false;
1278}
1279
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001280/// ParseDirectiveSet:
1281/// ::= .set identifier ',' expression
1282bool AsmParser::ParseDirectiveSet() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001283 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001284
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001285 if (ParseIdentifier(Name))
1286 return TokError("expected identifier after '.set' directive");
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001287
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001288 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001289 return TokError("unexpected token in '.set'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001290 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001291
Daniel Dunbare2ace502009-08-31 08:09:09 +00001292 return ParseAssignment(Name);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001293}
1294
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001295bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001296 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001297
1298 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00001299 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001300 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1301 if (Str[i] != '\\') {
1302 Data += Str[i];
1303 continue;
1304 }
1305
1306 // Recognize escaped characters. Note that this escape semantics currently
1307 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1308 ++i;
1309 if (i == e)
1310 return TokError("unexpected backslash at end of string");
1311
1312 // Recognize octal sequences.
1313 if ((unsigned) (Str[i] - '0') <= 7) {
1314 // Consume up to three octal characters.
1315 unsigned Value = Str[i] - '0';
1316
1317 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1318 ++i;
1319 Value = Value * 8 + (Str[i] - '0');
1320
1321 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1322 ++i;
1323 Value = Value * 8 + (Str[i] - '0');
1324 }
1325 }
1326
1327 if (Value > 255)
1328 return TokError("invalid octal escape sequence (out of range)");
1329
1330 Data += (unsigned char) Value;
1331 continue;
1332 }
1333
1334 // Otherwise recognize individual escapes.
1335 switch (Str[i]) {
1336 default:
1337 // Just reject invalid escape sequences for now.
1338 return TokError("invalid escape sequence (unrecognized character)");
1339
1340 case 'b': Data += '\b'; break;
1341 case 'f': Data += '\f'; break;
1342 case 'n': Data += '\n'; break;
1343 case 'r': Data += '\r'; break;
1344 case 't': Data += '\t'; break;
1345 case '"': Data += '"'; break;
1346 case '\\': Data += '\\'; break;
1347 }
1348 }
1349
1350 return false;
1351}
1352
Daniel Dunbara0d14262009-06-24 23:30:00 +00001353/// ParseDirectiveAscii:
Daniel Dunbar475839e2009-06-29 20:37:27 +00001354/// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
Daniel Dunbara0d14262009-06-24 23:30:00 +00001355bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001356 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001357 CheckForValidSection();
1358
Daniel Dunbara0d14262009-06-24 23:30:00 +00001359 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001360 if (getLexer().isNot(AsmToken::String))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001361 return TokError("expected string in '.ascii' or '.asciz' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001362
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001363 std::string Data;
1364 if (ParseEscapedString(Data))
1365 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001366
1367 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001368 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001369 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1370
Sean Callanan79ed1a82010-01-19 20:22:31 +00001371 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001372
1373 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001374 break;
1375
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001376 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001377 return TokError("unexpected token in '.ascii' or '.asciz' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001378 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001379 }
1380 }
1381
Sean Callanan79ed1a82010-01-19 20:22:31 +00001382 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001383 return false;
1384}
1385
1386/// ParseDirectiveValue
1387/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1388bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001389 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001390 CheckForValidSection();
1391
Daniel Dunbara0d14262009-06-24 23:30:00 +00001392 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00001393 const MCExpr *Value;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001394 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00001395 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001396 return true;
1397
Daniel Dunbar414c0c42010-05-23 18:36:38 +00001398 // Special case constant expressions to match code generator.
1399 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001400 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
Daniel Dunbar414c0c42010-05-23 18:36:38 +00001401 else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001402 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001403
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001404 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001405 break;
1406
1407 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001408 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001409 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001410 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001411 }
1412 }
1413
Sean Callanan79ed1a82010-01-19 20:22:31 +00001414 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001415 return false;
1416}
1417
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001418/// ParseDirectiveRealValue
1419/// ::= (.single | .double) [ expression (, expression)* ]
1420bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1421 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1422 CheckForValidSection();
1423
1424 for (;;) {
1425 // We don't truly support arithmetic on floating point expressions, so we
1426 // have to manually parse unary prefixes.
1427 bool IsNeg = false;
1428 if (getLexer().is(AsmToken::Minus)) {
1429 Lex();
1430 IsNeg = true;
1431 } else if (getLexer().is(AsmToken::Plus))
1432 Lex();
1433
1434 if (getLexer().isNot(AsmToken::Integer) &&
1435 getLexer().isNot(AsmToken::Real))
1436 return TokError("unexpected token in directive");
1437
1438 // Convert to an APFloat.
1439 APFloat Value(Semantics);
1440 if (Value.convertFromString(getTok().getString(),
1441 APFloat::rmNearestTiesToEven) ==
1442 APFloat::opInvalidOp)
1443 return TokError("invalid floating point literal");
1444 if (IsNeg)
1445 Value.changeSign();
1446
1447 // Consume the numeric token.
1448 Lex();
1449
1450 // Emit the value as an integer.
1451 APInt AsInt = Value.bitcastToAPInt();
1452 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1453 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1454
1455 if (getLexer().is(AsmToken::EndOfStatement))
1456 break;
1457
1458 if (getLexer().isNot(AsmToken::Comma))
1459 return TokError("unexpected token in directive");
1460 Lex();
1461 }
1462 }
1463
1464 Lex();
1465 return false;
1466}
1467
Daniel Dunbara0d14262009-06-24 23:30:00 +00001468/// ParseDirectiveSpace
1469/// ::= .space expression [ , expression ]
1470bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001471 CheckForValidSection();
1472
Daniel Dunbara0d14262009-06-24 23:30:00 +00001473 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001474 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001475 return true;
1476
1477 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001478 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1479 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001480 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001481 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001482
Daniel Dunbar475839e2009-06-29 20:37:27 +00001483 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001484 return true;
1485
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001486 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001487 return TokError("unexpected token in '.space' directive");
1488 }
1489
Sean Callanan79ed1a82010-01-19 20:22:31 +00001490 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001491
1492 if (NumBytes <= 0)
1493 return TokError("invalid number of bytes in '.space' directive");
1494
1495 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001496 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001497
1498 return false;
1499}
1500
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001501/// ParseDirectiveZero
1502/// ::= .zero expression
1503bool AsmParser::ParseDirectiveZero() {
1504 CheckForValidSection();
1505
1506 int64_t NumBytes;
1507 if (ParseAbsoluteExpression(NumBytes))
1508 return true;
1509
1510 if (getLexer().isNot(AsmToken::EndOfStatement))
1511 return TokError("unexpected token in '.zero' directive");
1512
1513 Lex();
1514
1515 getStreamer().EmitFill(NumBytes, 0, DEFAULT_ADDRSPACE);
1516
1517 return false;
1518}
1519
Daniel Dunbara0d14262009-06-24 23:30:00 +00001520/// ParseDirectiveFill
1521/// ::= .fill expression , expression , expression
1522bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001523 CheckForValidSection();
1524
Daniel Dunbara0d14262009-06-24 23:30:00 +00001525 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001526 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001527 return true;
1528
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001529 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001530 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001531 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001532
1533 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001534 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001535 return true;
1536
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001537 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001538 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001539 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001540
1541 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001542 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001543 return true;
1544
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001545 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001546 return TokError("unexpected token in '.fill' directive");
1547
Sean Callanan79ed1a82010-01-19 20:22:31 +00001548 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001549
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00001550 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1551 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00001552
1553 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001554 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001555
1556 return false;
1557}
Daniel Dunbarc238b582009-06-25 22:44:51 +00001558
1559/// ParseDirectiveOrg
1560/// ::= .org expression [ , expression ]
1561bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001562 CheckForValidSection();
1563
Daniel Dunbar821e3332009-08-31 08:09:28 +00001564 const MCExpr *Offset;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001565 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001566 return true;
1567
1568 // Parse optional fill expression.
1569 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001570 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1571 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001572 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001573 Lex();
Daniel Dunbarc238b582009-06-25 22:44:51 +00001574
Daniel Dunbar475839e2009-06-29 20:37:27 +00001575 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001576 return true;
1577
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001578 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001579 return TokError("unexpected token in '.org' directive");
1580 }
1581
Sean Callanan79ed1a82010-01-19 20:22:31 +00001582 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001583
1584 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1585 // has to be relative to the current section.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001586 getStreamer().EmitValueToOffset(Offset, FillExpr);
Daniel Dunbarc238b582009-06-25 22:44:51 +00001587
1588 return false;
1589}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001590
1591/// ParseDirectiveAlign
1592/// ::= {.align, ...} expression [ , expression [ , expression ]]
1593bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001594 CheckForValidSection();
1595
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001596 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001597 int64_t Alignment;
1598 if (ParseAbsoluteExpression(Alignment))
1599 return true;
1600
1601 SMLoc MaxBytesLoc;
1602 bool HasFillExpr = false;
1603 int64_t FillExpr = 0;
1604 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001605 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1606 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001607 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001608 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001609
1610 // The fill expression can be omitted while specifying a maximum number of
1611 // alignment bytes, e.g:
1612 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001613 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001614 HasFillExpr = true;
1615 if (ParseAbsoluteExpression(FillExpr))
1616 return true;
1617 }
1618
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001619 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1620 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001621 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001622 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001623
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001624 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001625 if (ParseAbsoluteExpression(MaxBytesToFill))
1626 return true;
1627
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001628 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001629 return TokError("unexpected token in directive");
1630 }
1631 }
1632
Sean Callanan79ed1a82010-01-19 20:22:31 +00001633 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001634
Daniel Dunbar648ac512010-05-17 21:54:30 +00001635 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001636 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001637
1638 // Compute alignment in bytes.
1639 if (IsPow2) {
1640 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00001641 if (Alignment >= 32) {
1642 Error(AlignmentLoc, "invalid alignment value");
1643 Alignment = 31;
1644 }
1645
Benjamin Kramer12fd7672009-09-06 09:35:10 +00001646 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001647 }
1648
Daniel Dunbarb58a8042009-08-26 09:16:34 +00001649 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001650 if (MaxBytesLoc.isValid()) {
1651 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00001652 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1653 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00001654 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001655 }
1656
1657 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00001658 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1659 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001660 MaxBytesToFill = 0;
1661 }
1662 }
1663
Daniel Dunbar648ac512010-05-17 21:54:30 +00001664 // Check whether we should use optimal code alignment for this .align
1665 // directive.
1666 //
1667 // FIXME: This should be using a target hook.
1668 bool UseCodeAlign = false;
1669 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001670 getStreamer().getCurrentSection()))
Chris Lattnera9558532010-07-15 21:19:31 +00001671 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
Daniel Dunbar648ac512010-05-17 21:54:30 +00001672 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1673 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001674 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00001675 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00001676 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00001677 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1678 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00001679 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001680
1681 return false;
1682}
1683
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001684/// ParseDirectiveSymbolAttribute
1685/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001686bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001687 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001688 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001689 StringRef Name;
1690
1691 if (ParseIdentifier(Name))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001692 return TokError("expected identifier in directive");
1693
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001694 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001695
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001696 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001697
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001698 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001699 break;
1700
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001701 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001702 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001703 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001704 }
1705 }
1706
Sean Callanan79ed1a82010-01-19 20:22:31 +00001707 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001708 return false;
1709}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001710
Matt Fleming924c5e52010-05-21 11:36:59 +00001711/// ParseDirectiveELFType
1712/// ::= .type identifier , @attribute
1713bool AsmParser::ParseDirectiveELFType() {
1714 StringRef Name;
1715 if (ParseIdentifier(Name))
1716 return TokError("expected identifier in directive");
1717
1718 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001719 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Matt Fleming924c5e52010-05-21 11:36:59 +00001720
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001721 if (getLexer().isNot(AsmToken::Comma))
Matt Fleming924c5e52010-05-21 11:36:59 +00001722 return TokError("unexpected token in '.type' directive");
1723 Lex();
1724
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001725 if (getLexer().isNot(AsmToken::At))
Matt Fleming924c5e52010-05-21 11:36:59 +00001726 return TokError("expected '@' before type");
1727 Lex();
1728
1729 StringRef Type;
1730 SMLoc TypeLoc;
1731
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001732 TypeLoc = getLexer().getLoc();
Matt Fleming924c5e52010-05-21 11:36:59 +00001733 if (ParseIdentifier(Type))
1734 return TokError("expected symbol type in directive");
1735
1736 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1737 .Case("function", MCSA_ELF_TypeFunction)
1738 .Case("object", MCSA_ELF_TypeObject)
1739 .Case("tls_object", MCSA_ELF_TypeTLS)
1740 .Case("common", MCSA_ELF_TypeCommon)
1741 .Case("notype", MCSA_ELF_TypeNoType)
1742 .Default(MCSA_Invalid);
1743
1744 if (Attr == MCSA_Invalid)
1745 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1746
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001747 if (getLexer().isNot(AsmToken::EndOfStatement))
Matt Fleming924c5e52010-05-21 11:36:59 +00001748 return TokError("unexpected token in '.type' directive");
1749
1750 Lex();
1751
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001752 getStreamer().EmitSymbolAttribute(Sym, Attr);
Matt Fleming924c5e52010-05-21 11:36:59 +00001753
1754 return false;
1755}
1756
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001757/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00001758/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1759bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001760 CheckForValidSection();
1761
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001762 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001763 StringRef Name;
1764 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001765 return TokError("expected identifier in directive");
1766
Daniel Dunbar76c4d762009-07-31 21:55:09 +00001767 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001768 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001769
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001770 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001771 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001772 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001773
1774 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001775 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001776 if (ParseAbsoluteExpression(Size))
1777 return true;
1778
1779 int64_t Pow2Alignment = 0;
1780 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001781 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00001782 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001783 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001784 if (ParseAbsoluteExpression(Pow2Alignment))
1785 return true;
Chris Lattner258281d2010-01-19 06:22:22 +00001786
1787 // If this target takes alignments in bytes (not log) validate and convert.
1788 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1789 if (!isPowerOf2_64(Pow2Alignment))
1790 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1791 Pow2Alignment = Log2_64(Pow2Alignment);
1792 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001793 }
1794
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001795 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00001796 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001797
Sean Callanan79ed1a82010-01-19 20:22:31 +00001798 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001799
Chris Lattner1fc3d752009-07-09 17:25:12 +00001800 // NOTE: a size of zero for a .comm should create a undefined symbol
1801 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001802 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00001803 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1804 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001805
Eric Christopherc260a3e2010-05-14 01:38:54 +00001806 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001807 // may internally end up wanting an alignment in bytes.
1808 // FIXME: Diagnose overflow.
1809 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00001810 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1811 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001812
Daniel Dunbar8906ff12009-08-22 07:22:36 +00001813 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001814 return Error(IDLoc, "invalid symbol redefinition");
1815
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00001816 // '.lcomm' is equivalent to '.zerofill'.
Chris Lattner1fc3d752009-07-09 17:25:12 +00001817 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00001818 if (IsLocal) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001819 getStreamer().EmitZerofill(Ctx.getMachOSection(
1820 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1821 0, SectionKind::getBSS()),
1822 Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00001823 return false;
1824 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001825
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001826 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001827 return false;
1828}
Chris Lattner9be3fee2009-07-10 22:20:30 +00001829
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001830/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00001831/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001832bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00001833 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001834 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00001835
Daniel Dunbar6a46d572010-07-18 20:15:59 +00001836 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001837 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001838 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00001839
Sean Callanan79ed1a82010-01-19 20:22:31 +00001840 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001841
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00001842 if (Str.empty())
1843 Error(Loc, ".abort detected. Assembly stopping.");
1844 else
1845 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00001846 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001847
1848 return false;
1849}
Kevin Enderby71148242009-07-14 21:35:03 +00001850
Kevin Enderby1f049b22009-07-14 23:21:55 +00001851/// ParseDirectiveInclude
1852/// ::= .include "filename"
1853bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001854 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00001855 return TokError("expected string in '.include' directive");
1856
Sean Callanan18b83232010-01-19 21:44:56 +00001857 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001858 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001859 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00001860
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001861 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00001862 return TokError("unexpected token in '.include' directive");
1863
Chris Lattner8e25e2d2009-07-16 06:14:39 +00001864 // Strip the quotes.
1865 Filename = Filename.substr(1, Filename.size()-2);
1866
1867 // Attempt to switch the lexer to the included file before consuming the end
1868 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00001869 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00001870 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00001871 return true;
1872 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00001873
1874 return false;
1875}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00001876
Kevin Enderbyc114ed72009-08-07 22:46:00 +00001877/// ParseDirectiveIf
1878/// ::= .if expression
1879bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00001880 TheCondStack.push_back(TheCondState);
1881 TheCondState.TheCond = AsmCond::IfCond;
1882 if(TheCondState.Ignore) {
1883 EatToEndOfStatement();
1884 }
1885 else {
1886 int64_t ExprValue;
1887 if (ParseAbsoluteExpression(ExprValue))
1888 return true;
1889
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001890 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00001891 return TokError("unexpected token in '.if' directive");
1892
Sean Callanan79ed1a82010-01-19 20:22:31 +00001893 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00001894
1895 TheCondState.CondMet = ExprValue;
1896 TheCondState.Ignore = !TheCondState.CondMet;
1897 }
1898
1899 return false;
1900}
1901
1902/// ParseDirectiveElseIf
1903/// ::= .elseif expression
1904bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1905 if (TheCondState.TheCond != AsmCond::IfCond &&
1906 TheCondState.TheCond != AsmCond::ElseIfCond)
1907 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1908 " an .elseif");
1909 TheCondState.TheCond = AsmCond::ElseIfCond;
1910
Kevin Enderbyc114ed72009-08-07 22:46:00 +00001911 bool LastIgnoreState = false;
1912 if (!TheCondStack.empty())
1913 LastIgnoreState = TheCondStack.back().Ignore;
1914 if (LastIgnoreState || TheCondState.CondMet) {
1915 TheCondState.Ignore = true;
1916 EatToEndOfStatement();
1917 }
1918 else {
1919 int64_t ExprValue;
1920 if (ParseAbsoluteExpression(ExprValue))
1921 return true;
1922
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001923 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00001924 return TokError("unexpected token in '.elseif' directive");
1925
Sean Callanan79ed1a82010-01-19 20:22:31 +00001926 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00001927 TheCondState.CondMet = ExprValue;
1928 TheCondState.Ignore = !TheCondState.CondMet;
1929 }
1930
1931 return false;
1932}
1933
1934/// ParseDirectiveElse
1935/// ::= .else
1936bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001937 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00001938 return TokError("unexpected token in '.else' directive");
1939
Sean Callanan79ed1a82010-01-19 20:22:31 +00001940 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00001941
1942 if (TheCondState.TheCond != AsmCond::IfCond &&
1943 TheCondState.TheCond != AsmCond::ElseIfCond)
1944 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1945 ".elseif");
1946 TheCondState.TheCond = AsmCond::ElseCond;
1947 bool LastIgnoreState = false;
1948 if (!TheCondStack.empty())
1949 LastIgnoreState = TheCondStack.back().Ignore;
1950 if (LastIgnoreState || TheCondState.CondMet)
1951 TheCondState.Ignore = true;
1952 else
1953 TheCondState.Ignore = false;
1954
1955 return false;
1956}
1957
1958/// ParseDirectiveEndIf
1959/// ::= .endif
1960bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001961 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00001962 return TokError("unexpected token in '.endif' directive");
1963
Sean Callanan79ed1a82010-01-19 20:22:31 +00001964 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00001965
1966 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1967 TheCondStack.empty())
1968 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1969 ".else");
1970 if (!TheCondStack.empty()) {
1971 TheCondState = TheCondStack.back();
1972 TheCondStack.pop_back();
1973 }
1974
1975 return false;
1976}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001977
1978/// ParseDirectiveFile
1979/// ::= .file [number] string
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001980bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001981 // FIXME: I'm not sure what this is.
1982 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00001983 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00001984 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00001985 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001986 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00001987
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001988 if (FileNumber < 1)
1989 return TokError("file number less than one");
1990 }
1991
Daniel Dunbareceec052010-07-12 17:45:27 +00001992 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001993 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00001994
Chris Lattnerd32e8032010-01-25 19:02:58 +00001995 StringRef Filename = getTok().getString();
1996 Filename = Filename.substr(1, Filename.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00001997 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001998
Daniel Dunbareceec052010-07-12 17:45:27 +00001999 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002000 return TokError("unexpected token in '.file' directive");
2001
Chris Lattnerd32e8032010-01-25 19:02:58 +00002002 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002003 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002004 else {
2005 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
2006 Error(FileNumberLoc, "file number already allocated");
Daniel Dunbareceec052010-07-12 17:45:27 +00002007 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002008 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002009
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002010 return false;
2011}
2012
2013/// ParseDirectiveLine
2014/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002015bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002016 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2017 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002018 return TokError("unexpected token in '.line' directive");
2019
Sean Callanan18b83232010-01-19 21:44:56 +00002020 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002021 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002022 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002023
2024 // FIXME: Do something with the .line.
2025 }
2026
Daniel Dunbareceec052010-07-12 17:45:27 +00002027 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002028 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002029
2030 return false;
2031}
2032
2033
2034/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002035/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002036/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2037/// The first number is a file number, must have been previously assigned with
2038/// a .file directive, the second number is the line number and optionally the
2039/// third number is a column position (zero if not specified). The remaining
2040/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002041bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002042
Daniel Dunbareceec052010-07-12 17:45:27 +00002043 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002044 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002045 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002046 if (FileNumber < 1)
2047 return TokError("file number less than one in '.loc' directive");
2048 if (!getContext().ValidateDwarfFileNumber(FileNumber))
2049 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002050 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002051
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002052 int64_t LineNumber = 0;
2053 if (getLexer().is(AsmToken::Integer)) {
2054 LineNumber = getTok().getIntVal();
2055 if (LineNumber < 1)
2056 return TokError("line number less than one in '.loc' directive");
2057 Lex();
2058 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002059
2060 int64_t ColumnPos = 0;
2061 if (getLexer().is(AsmToken::Integer)) {
2062 ColumnPos = getTok().getIntVal();
2063 if (ColumnPos < 0)
2064 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002065 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002066 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002067
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002068 unsigned Flags = 0;
2069 unsigned Isa = 0;
2070 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2071 for (;;) {
2072 if (getLexer().is(AsmToken::EndOfStatement))
2073 break;
2074
2075 StringRef Name;
2076 SMLoc Loc = getTok().getLoc();
2077 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002078 return TokError("unexpected token in '.loc' directive");
2079
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002080 if (Name == "basic_block")
2081 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2082 else if (Name == "prologue_end")
2083 Flags |= DWARF2_FLAG_PROLOGUE_END;
2084 else if (Name == "epilogue_begin")
2085 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2086 else if (Name == "is_stmt") {
2087 SMLoc Loc = getTok().getLoc();
2088 const MCExpr *Value;
2089 if (getParser().ParseExpression(Value))
2090 return true;
2091 // The expression must be the constant 0 or 1.
2092 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2093 int Value = MCE->getValue();
2094 if (Value == 0)
2095 Flags &= ~DWARF2_FLAG_IS_STMT;
2096 else if (Value == 1)
2097 Flags |= DWARF2_FLAG_IS_STMT;
2098 else
2099 return Error(Loc, "is_stmt value not 0 or 1");
2100 }
2101 else {
2102 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2103 }
2104 }
2105 else if (Name == "isa") {
2106 SMLoc Loc = getTok().getLoc();
2107 const MCExpr *Value;
2108 if (getParser().ParseExpression(Value))
2109 return true;
2110 // The expression must be a constant greater or equal to 0.
2111 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2112 int Value = MCE->getValue();
2113 if (Value < 0)
2114 return Error(Loc, "isa number less than zero");
2115 Isa = Value;
2116 }
2117 else {
2118 return Error(Loc, "isa number not a constant value");
2119 }
2120 }
2121 else {
2122 return Error(Loc, "unknown sub-directive in '.loc' directive");
2123 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002124
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002125 if (getLexer().is(AsmToken::EndOfStatement))
2126 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002127 }
2128 }
2129
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002130 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002131
2132 return false;
2133}
2134
Daniel Dunbar3c802de2010-07-18 18:38:02 +00002135/// ParseDirectiveMacrosOnOff
2136/// ::= .macros_on
2137/// ::= .macros_off
2138bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2139 SMLoc DirectiveLoc) {
2140 if (getLexer().isNot(AsmToken::EndOfStatement))
2141 return Error(getLexer().getLoc(),
2142 "unexpected token in '" + Directive + "' directive");
2143
2144 getParser().MacrosEnabled = Directive == ".macros_on";
2145
2146 return false;
2147}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00002148
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002149/// ParseDirectiveMacro
2150/// ::= .macro name
2151bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2152 SMLoc DirectiveLoc) {
2153 StringRef Name;
2154 if (getParser().ParseIdentifier(Name))
2155 return TokError("expected identifier in directive");
2156
2157 if (getLexer().isNot(AsmToken::EndOfStatement))
2158 return TokError("unexpected token in '.macro' directive");
2159
2160 // Eat the end of statement.
2161 Lex();
2162
2163 AsmToken EndToken, StartToken = getTok();
2164
2165 // Lex the macro definition.
2166 for (;;) {
2167 // Check whether we have reached the end of the file.
2168 if (getLexer().is(AsmToken::Eof))
2169 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2170
2171 // Otherwise, check whether we have reach the .endmacro.
2172 if (getLexer().is(AsmToken::Identifier) &&
2173 (getTok().getIdentifier() == ".endm" ||
2174 getTok().getIdentifier() == ".endmacro")) {
2175 EndToken = getTok();
2176 Lex();
2177 if (getLexer().isNot(AsmToken::EndOfStatement))
2178 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2179 "' directive");
2180 break;
2181 }
2182
2183 // Otherwise, scan til the end of the statement.
2184 getParser().EatToEndOfStatement();
2185 }
2186
2187 if (getParser().MacroMap.lookup(Name)) {
2188 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2189 }
2190
2191 const char *BodyStart = StartToken.getLoc().getPointer();
2192 const char *BodyEnd = EndToken.getLoc().getPointer();
2193 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2194 getParser().MacroMap[Name] = new Macro(Name, Body);
2195 return false;
2196}
2197
2198/// ParseDirectiveEndMacro
2199/// ::= .endm
2200/// ::= .endmacro
2201bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2202 SMLoc DirectiveLoc) {
2203 if (getLexer().isNot(AsmToken::EndOfStatement))
2204 return TokError("unexpected token in '" + Directive + "' directive");
2205
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002206 // If we are inside a macro instantiation, terminate the current
2207 // instantiation.
2208 if (!getParser().ActiveMacros.empty()) {
2209 getParser().HandleMacroExit();
2210 return false;
2211 }
2212
2213 // Otherwise, this .endmacro is a stray entry in the file; well formed
2214 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002215 return TokError("unexpected '" + Directive + "' in file, "
2216 "no current macro definition");
2217}
2218
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00002219void GenericAsmParser::ParseUleb128(uint64_t Value) {
2220 const uint64_t Mask = (1 << 7) - 1;
2221 do {
2222 unsigned Byte = Value & Mask;
2223 Value >>= 7;
2224 if (Value) // Not the last one
2225 Byte |= (1 << 7);
2226 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2227 } while (Value);
2228}
2229
2230void GenericAsmParser::ParseSleb128(int64_t Value) {
2231 const int64_t Mask = (1 << 7) - 1;
2232 for(;;) {
2233 unsigned Byte = Value & Mask;
2234 Value >>= 7;
2235 bool Done = ((Value == 0 && (Byte & 0x40) == 0) ||
2236 (Value == -1 && (Byte & 0x40) != 0));
2237 if (!Done)
2238 Byte |= (1 << 7);
2239 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2240 if (Done)
2241 break;
2242 }
2243}
2244
2245bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2246 int64_t Value;
2247 if (getParser().ParseAbsoluteExpression(Value))
2248 return true;
2249
2250 if (getLexer().isNot(AsmToken::EndOfStatement))
2251 return TokError("unexpected token in directive");
2252
2253 if (DirName[1] == 's')
2254 ParseSleb128(Value);
2255 else
2256 ParseUleb128(Value);
2257 return false;
2258}
2259
2260
Daniel Dunbard1e3b442010-07-17 02:26:10 +00002261/// \brief Create an MCAsmParser instance.
2262MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2263 MCContext &C, MCStreamer &Out,
2264 const MCAsmInfo &MAI) {
2265 return new AsmParser(T, SM, C, Out, MAI);
2266}