blob: 360de5db883d8105d3fb692a41336e547c79dbd6 [file] [log] [blame]
Chris Lattnerb0133452009-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 Dunbar2af16532010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Chad Rosiereb5c1682013-02-13 18:38:58 +000015#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000016#include "llvm/ADT/SmallString.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000017#include "llvm/ADT/StringMap.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Evan Cheng11424442011-07-26 00:24:13 +000021#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000022#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000023#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000025#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000026#include "llvm/MC/MCParser/AsmCond.h"
27#include "llvm/MC/MCParser/AsmLexer.h"
28#include "llvm/MC/MCParser/MCAsmParser.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000029#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000030#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000031#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000032#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000033#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000034#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000035#include "llvm/MC/MCSymbol.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000036#include "llvm/MC/MCValue.h"
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +000037#include "llvm/Support/CommandLine.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000038#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000039#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000040#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000041#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000042#include "llvm/Support/raw_ostream.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000043#include <cctype>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000044#include <deque>
Chad Rosier8bce6642012-10-18 15:49:34 +000045#include <set>
46#include <string>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000047#include <vector>
Chris Lattnerb0133452009-06-21 20:16:42 +000048using namespace llvm;
49
Eric Christophera7c32732012-12-18 00:30:54 +000050MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewyckyac612272012-10-19 07:00:09 +000051
Daniel Dunbar86033402010-07-12 17:54:38 +000052namespace {
Eli Benderskya313ae62013-01-16 18:56:50 +000053/// \brief Helper types for tracking macro definitions.
54typedef std::vector<AsmToken> MCAsmMacroArgument;
55typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000056
57struct MCAsmMacroParameter {
58 StringRef Name;
59 MCAsmMacroArgument Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000060 bool Required;
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000061 bool Vararg;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000062
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000063 MCAsmMacroParameter() : Required(false), Vararg(false) {}
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000064};
65
Eli Benderskya313ae62013-01-16 18:56:50 +000066typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
67
68struct MCAsmMacro {
69 StringRef Name;
70 StringRef Body;
71 MCAsmMacroParameters Parameters;
72
73public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +000074 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
75 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +000076};
77
Daniel Dunbar43235712010-07-18 18:54:11 +000078/// \brief Helper class for storing information about an active macro
79/// instantiation.
80struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000081 /// The location of the instantiation.
82 SMLoc InstantiationLoc;
83
Daniel Dunbar40f1d852012-12-01 01:38:48 +000084 /// The buffer where parsing should resume upon instantiation completion.
85 int ExitBuffer;
86
Daniel Dunbar43235712010-07-18 18:54:11 +000087 /// The location where parsing should resume upon instantiation completion.
88 SMLoc ExitLoc;
89
Nico Weber155dccd12014-07-24 17:08:39 +000090 /// The depth of TheCondStack at the start of the instantiation.
91 size_t CondStackDepth;
92
Daniel Dunbar43235712010-07-18 18:54:11 +000093public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +000094 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +000095};
96
Eli Friedman0f4871d2012-10-22 23:58:19 +000097struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +000098 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +000099 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000100
Jim Grosbach4b905842013-09-20 23:08:21 +0000101 /// \brief The opcode from the last parsed instruction.
Eli Friedman0f4871d2012-10-22 23:58:19 +0000102 unsigned Opcode;
103
Jim Grosbach4b905842013-09-20 23:08:21 +0000104 /// \brief Was there an error parsing the inline assembly?
Chad Rosier149e8e02012-12-12 22:45:52 +0000105 bool ParseError;
106
Eli Friedman0f4871d2012-10-22 23:58:19 +0000107 SmallVectorImpl<AsmRewrite> *AsmRewrites;
108
Craig Topper353eda42014-04-24 06:44:33 +0000109 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000110 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier149e8e02012-12-12 22:45:52 +0000111 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000112};
113
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000114/// \brief The concrete assembly parser instance.
115class AsmParser : public MCAsmParser {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000116 AsmParser(const AsmParser &) = delete;
117 void operator=(const AsmParser &) = delete;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000118private:
119 AsmLexer Lexer;
120 MCContext &Ctx;
121 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000122 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000123 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000124 SourceMgr::DiagHandlerTy SavedDiagHandler;
125 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000126 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000127
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000128 /// This is the current buffer index we're lexing from as managed by the
129 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000130 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000131
132 AsmCond TheCondState;
133 std::vector<AsmCond> TheCondStack;
134
Jim Grosbach4b905842013-09-20 23:08:21 +0000135 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000136 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000137 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000138 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000139
Jim Grosbach4b905842013-09-20 23:08:21 +0000140 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000141 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000142
Jim Grosbach4b905842013-09-20 23:08:21 +0000143 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000144 std::vector<MacroInstantiation*> ActiveMacros;
145
Jim Grosbach4b905842013-09-20 23:08:21 +0000146 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000147 std::deque<MCAsmMacro> MacroLikeBodies;
148
Daniel Dunbar828984f2010-07-18 18:38:02 +0000149 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000150 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000151
Toma Tabacu217116e2015-04-27 10:50:29 +0000152 /// \brief Keeps track of how many .macro's have been instantiated.
153 unsigned NumOfMacroInstantiations;
154
Daniel Dunbar43325c42010-09-09 22:42:56 +0000155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
157
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
161 SMLoc CppHashLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000162 unsigned CppHashBuf;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000163 /// When generating dwarf for assembly source files we need to calculate the
164 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000165 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000166 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
167 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000168 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000169 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000170
Devang Patela173ee52012-01-31 18:14:05 +0000171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
172 unsigned AssemblerDialect;
173
Jim Grosbach4b905842013-09-20 23:08:21 +0000174 /// \brief is Darwin compatibility enabled?
Preston Gurd05500642012-09-19 20:36:12 +0000175 bool IsDarwin;
176
Jim Grosbach4b905842013-09-20 23:08:21 +0000177 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier49963552012-10-13 00:26:04 +0000178 bool ParsingInlineAsm;
179
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000180public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000181 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000182 const MCAsmInfo &MAI);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000183 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000184
Craig Topper59be68f2014-03-08 07:14:16 +0000185 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000186
Craig Topper59be68f2014-03-08 07:14:16 +0000187 void addDirectiveHandler(StringRef Directive,
188 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000189 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000190 }
191
Toma Tabacu11e14a92015-04-21 11:50:52 +0000192 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
193 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
194 }
195
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000196public:
197 /// @name MCAsmParser Interface
198 /// {
199
Craig Topper59be68f2014-03-08 07:14:16 +0000200 SourceMgr &getSourceManager() override { return SrcMgr; }
201 MCAsmLexer &getLexer() override { return Lexer; }
202 MCContext &getContext() override { return Ctx; }
203 MCStreamer &getStreamer() override { return Out; }
204 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000205 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000206 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000207 else
208 return AssemblerDialect;
209 }
Craig Topper59be68f2014-03-08 07:14:16 +0000210 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000211 AssemblerDialect = i;
212 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000213
Craig Topper59be68f2014-03-08 07:14:16 +0000214 void Note(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None) override;
216 bool Warning(SMLoc L, const Twine &Msg,
217 ArrayRef<SMRange> Ranges = None) override;
218 bool Error(SMLoc L, const Twine &Msg,
219 ArrayRef<SMRange> Ranges = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000220
Craig Topper59be68f2014-03-08 07:14:16 +0000221 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000222
Craig Topper59be68f2014-03-08 07:14:16 +0000223 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
224 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000225
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000226 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000227 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier37e755c2012-10-23 17:43:43 +0000228 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000229 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000230 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000231 const MCInstrInfo *MII, const MCInstPrinter *IP,
232 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000233
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000234 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000235 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
237 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000238 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
239 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000240 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000241
Jim Grosbach4b905842013-09-20 23:08:21 +0000242 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000243 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000244 bool parseIdentifier(StringRef &Res) override;
245 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000246
Craig Topper59be68f2014-03-08 07:14:16 +0000247 void checkForValidSection() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000248 /// }
249
250private:
Daniel Dunbare5444a82010-09-09 22:42:59 +0000251
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000252 bool parseStatement(ParseStatementInfo &Info,
253 MCAsmParserSemaCallback *SI);
Jim Grosbach4b905842013-09-20 23:08:21 +0000254 void eatToEndOfLine();
Craig Topper3c76c522015-09-20 23:35:59 +0000255 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000256
Jim Grosbach4b905842013-09-20 23:08:21 +0000257 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000258 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000259 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000260 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000261 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000262 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000263
Eli Benderskya313ae62013-01-16 18:56:50 +0000264 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000265 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000266
267 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000268 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000269
270 /// \brief Lookup a previously defined macro.
271 /// \param Name Macro name.
272 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000273 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000274
275 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000276 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000277
278 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000279 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000280
281 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000282 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000283
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000284 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000285 ///
286 /// \param M The macro.
287 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000288 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000289
290 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000291 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000292
David Majnemer91fc4c22014-01-29 18:57:46 +0000293 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000294 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000295
296 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000297 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000298
Jim Grosbach4b905842013-09-20 23:08:21 +0000299 void printMacroInstantiations();
300 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000301 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner72845262011-10-16 05:47:55 +0000302 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000303 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000304 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000305
Jim Grosbach4b905842013-09-20 23:08:21 +0000306 /// \brief Enter the specified file. This returns true on failure.
307 bool enterIncludeFile(const std::string &Filename);
308
309 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000310 /// This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000311 bool processIncbinFile(const std::string &Filename);
Daniel Dunbar43235712010-07-18 18:54:11 +0000312
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000313 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000314 /// current token is not set; clients should ensure Lex() is called
315 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000316 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000317 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000318 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000319 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000320
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000321 /// \brief Parse up to the end of statement and a return the contents from the
322 /// current token until the end of the statement; the current token on exit
323 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000324 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000325
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000326 /// \brief Parse until the end of a statement or a comma is encountered,
327 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000328 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000329
Jim Grosbach4b905842013-09-20 23:08:21 +0000330 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000331 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000332
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000333 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
334 MCBinaryExpr::Opcode &Kind);
335
Jim Grosbach4b905842013-09-20 23:08:21 +0000336 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
338 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000339
Jim Grosbach4b905842013-09-20 23:08:21 +0000340 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000341
Eli Bendersky17233942013-01-15 22:59:42 +0000342 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000343 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000344 DK_NO_DIRECTIVE, // Placeholder
345 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000346 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000347 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
348 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000349 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000350 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000351 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000352 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
353 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
354 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
355 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000356 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000357 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
358 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000359 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
Reid Kleckner2214ed82016-01-29 00:49:42 +0000360 DK_CV_FILE, DK_CV_LOC, DK_CV_LINETABLE, DK_CV_STRINGTABLE,
361 DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000362 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
363 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
364 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
365 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
366 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000367 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000368 DK_MACROS_ON, DK_MACROS_OFF,
369 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000370 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000371 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000372 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000373 };
374
Jim Grosbach4b905842013-09-20 23:08:21 +0000375 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000376 /// directives parsed by this class.
377 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000378
379 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000380 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000381 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Jim Grosbach4b905842013-09-20 23:08:21 +0000382 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
David Woodhoused6de0d92014-02-01 16:20:59 +0000383 bool parseDirectiveOctaValue(); // ".octa"
Jim Grosbach4b905842013-09-20 23:08:21 +0000384 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
385 bool parseDirectiveFill(); // ".fill"
386 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000387 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000388 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
389 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000390 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000391 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000392
Eli Bendersky17233942013-01-15 22:59:42 +0000393 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000394 bool parseDirectiveFile(SMLoc DirectiveLoc);
395 bool parseDirectiveLine();
396 bool parseDirectiveLoc();
397 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000398
Reid Kleckner2214ed82016-01-29 00:49:42 +0000399 // ".cv_file", ".cv_loc", ".cv_linetable"
400 bool parseDirectiveCVFile();
401 bool parseDirectiveCVLoc();
402 bool parseDirectiveCVLinetable();
403 bool parseDirectiveCVStringTable();
404 bool parseDirectiveCVFileChecksums();
405
Eli Bendersky17233942013-01-15 22:59:42 +0000406 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000407 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000408 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000409 bool parseDirectiveCFISections();
410 bool parseDirectiveCFIStartProc();
411 bool parseDirectiveCFIEndProc();
412 bool parseDirectiveCFIDefCfaOffset();
413 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
414 bool parseDirectiveCFIAdjustCfaOffset();
415 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
416 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
417 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
418 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
419 bool parseDirectiveCFIRememberState();
420 bool parseDirectiveCFIRestoreState();
421 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
422 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
423 bool parseDirectiveCFIEscape();
424 bool parseDirectiveCFISignalFrame();
425 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000426
427 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000428 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000429 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000430 bool parseDirectiveEndMacro(StringRef Directive);
431 bool parseDirectiveMacro(SMLoc DirectiveLoc);
432 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000433
Eli Benderskyf483ff92012-12-20 19:05:53 +0000434 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000435 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000436 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000437 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000438 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000439 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000440
Eli Bendersky17233942013-01-15 22:59:42 +0000441 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000442 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000443
444 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000445 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000446
Jim Grosbach4b905842013-09-20 23:08:21 +0000447 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000448 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000449 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000450
Jim Grosbach4b905842013-09-20 23:08:21 +0000451 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000452
Jim Grosbach4b905842013-09-20 23:08:21 +0000453 bool parseDirectiveAbort(); // ".abort"
454 bool parseDirectiveInclude(); // ".include"
455 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000456
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000457 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
458 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000459 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000460 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000461 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000462 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000463 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
464 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000465 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000466 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
467 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
468 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
469 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000470 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000471
Jim Grosbach4b905842013-09-20 23:08:21 +0000472 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000473 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000474
Rafael Espindola34b9c512012-06-03 23:57:14 +0000475 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000476 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
477 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000478 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000479 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000480 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
481 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
482 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000483
Chad Rosierc7f552c2013-02-12 21:33:51 +0000484 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000485 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000486 size_t Len);
487
488 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000489 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000490
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000491 // "end"
492 bool parseDirectiveEnd(SMLoc DirectiveLoc);
493
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000494 // ".err" or ".error"
495 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000496
Nico Weber404012b2014-07-24 16:26:06 +0000497 // ".warning"
498 bool parseDirectiveWarning(SMLoc DirectiveLoc);
499
Eli Bendersky17233942013-01-15 22:59:42 +0000500 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000501};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000502}
Daniel Dunbar86033402010-07-12 17:54:38 +0000503
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000504namespace llvm {
505
506extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000507extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000508extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000509
510}
511
Chris Lattnerc35681b2010-01-19 19:46:13 +0000512enum { DEFAULT_ADDRSPACE = 0 };
513
David Blaikie9f380a32015-03-16 18:06:57 +0000514AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
515 const MCAsmInfo &MAI)
516 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
517 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Alp Tokera55b95b2014-07-06 10:33:31 +0000518 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
Oliver Stannardcf6bfb12014-11-03 12:19:03 +0000519 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000520 // Save the old handler.
521 SavedDiagHandler = SrcMgr.getDiagHandler();
522 SavedDiagContext = SrcMgr.getDiagContext();
523 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000524 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000525 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000526
Daniel Dunbarc5011082010-07-12 18:12:02 +0000527 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000528 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
529 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000530 PlatformParser.reset(createCOFFAsmParser());
531 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000532 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000533 PlatformParser.reset(createDarwinAsmParser());
534 IsDarwin = true;
535 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000536 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000537 PlatformParser.reset(createELFAsmParser());
538 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000539 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000540
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000541 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000542 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000543
544 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000545}
546
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000547AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000548 assert((HadError || ActiveMacros.empty()) &&
549 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000550}
551
Jim Grosbach4b905842013-09-20 23:08:21 +0000552void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000553 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000554 for (std::vector<MacroInstantiation *>::const_reverse_iterator
555 it = ActiveMacros.rbegin(),
556 ie = ActiveMacros.rend();
557 it != ie; ++it)
558 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000559 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000560}
561
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000562void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
563 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
564 printMacroInstantiations();
565}
566
Chris Lattnera3a06812011-10-16 04:47:35 +0000567bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000568 if(getTargetParser().getTargetOptions().MCNoWarn)
569 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000570 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Chris Lattnera3a06812011-10-16 04:47:35 +0000571 return Error(L, Msg, Ranges);
Jim Grosbach4b905842013-09-20 23:08:21 +0000572 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
573 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000574 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000575}
576
Chris Lattnera3a06812011-10-16 04:47:35 +0000577bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000578 HadError = true;
Jim Grosbach4b905842013-09-20 23:08:21 +0000579 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
580 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000581 return true;
582}
583
Jim Grosbach4b905842013-09-20 23:08:21 +0000584bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000585 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000586 unsigned NewBuf =
587 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
588 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000589 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000590
Sean Callanan7a77eae2010-01-21 00:19:58 +0000591 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000592 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000593 return false;
594}
Daniel Dunbar43235712010-07-18 18:54:11 +0000595
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000596/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000597/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000598/// returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000599bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000600 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000601 unsigned NewBuf =
602 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
603 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000604 return true;
605
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000606 // Pick up the bytes from the file and emit them.
Rafael Espindola64e1af82013-07-02 15:49:13 +0000607 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderby109f25c2011-12-14 21:47:48 +0000608 return false;
609}
610
Alp Tokera55b95b2014-07-06 10:33:31 +0000611void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
612 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000613 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
614 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000615}
616
Sean Callanan7a77eae2010-01-21 00:19:58 +0000617const AsmToken &AsmParser::Lex() {
618 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000619
Sean Callanan7a77eae2010-01-21 00:19:58 +0000620 if (tok->is(AsmToken::Eof)) {
621 // If this is the end of an included file, pop the parent file off the
622 // include stack.
623 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
624 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000625 jumpToLoc(ParentIncludeLoc);
Sean Callanan7a77eae2010-01-21 00:19:58 +0000626 tok = &Lexer.Lex();
627 }
628 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000629
Sean Callanan7a77eae2010-01-21 00:19:58 +0000630 if (tok->is(AsmToken::Error))
Daniel Dunbard8a18452010-07-18 18:31:45 +0000631 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencer530ce852010-10-09 11:00:50 +0000632
Sean Callanan7a77eae2010-01-21 00:19:58 +0000633 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000634}
635
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000636bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000637 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000638 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000639 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000640
Chris Lattner36e02122009-06-21 20:54:55 +0000641 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000642 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000643
644 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000645 AsmCond StartingCondState = TheCondState;
646
Kevin Enderby6469fc22011-11-01 22:27:22 +0000647 // If we are generating dwarf for assembly source files save the initial text
648 // section and generate a .file directive.
649 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000650 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000651 if (!Sec->getBeginSymbol()) {
652 MCSymbol *SectionStartSym = getContext().createTempSymbol();
653 getStreamer().EmitLabel(SectionStartSym);
654 Sec->setBeginSymbol(SectionStartSym);
655 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000656 bool InsertResult = getContext().addGenDwarfSection(Sec);
657 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000658 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000659 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
660 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000661 }
662
Chris Lattner73f36112009-07-02 21:53:43 +0000663 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000664 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000665 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000666 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000667 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000668
Daniel Dunbar43325c42010-09-09 22:42:56 +0000669 // We had an error, validate that one was emitted and recover by skipping to
670 // the next line.
671 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000672 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000673 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000674
675 if (TheCondState.TheCond != StartingCondState.TheCond ||
676 TheCondState.Ignore != StartingCondState.Ignore)
677 return TokError("unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000678
679 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000680 const auto &LineTables = getContext().getMCDwarfLineTables();
681 if (!LineTables.empty()) {
682 unsigned Index = 0;
683 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
684 if (File.Name.empty() && Index != 0)
685 TokError("unassigned file number: " + Twine(Index) +
686 " for .file directives");
687 ++Index;
688 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000689 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000690
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000691 // Check to see that all assembler local symbols were actually defined.
692 // Targets that don't do subsections via symbols may not want this, though,
693 // so conservatively exclude them. Only do this if we're finalizing, though,
694 // as otherwise we won't necessarilly have seen everything yet.
695 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
Craig Topper84008482015-10-10 05:38:14 +0000696 for (const auto &TableEntry : getContext().getSymbols()) {
697 MCSymbol *Sym = TableEntry.getValue();
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000698 // Variable symbols may not be marked as defined, so check those
699 // explicitly. If we know it's a variable, we have a definition for
700 // the purposes of this check.
701 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
702 // FIXME: We would really like to refer back to where the symbol was
703 // first referenced for a source location. We need to add something
704 // to track that. Currently, we just point to the end of the file.
Jim Grosbach0fdd5722015-10-16 22:07:59 +0000705 return Error(getLexer().getLoc(), "assembler local symbol '" +
706 Sym->getName() + "' not defined");
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000707 }
708 }
709
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000710 // Finalize the output stream if there are no errors and if the client wants
711 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000712 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000713 Out.Finish();
714
Oliver Stannard07b43d32015-11-17 09:58:07 +0000715 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000716}
717
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000718void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000719 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbare5444a82010-09-09 22:42:59 +0000720 TokError("expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000721 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000722 }
723}
724
Jim Grosbach4b905842013-09-20 23:08:21 +0000725/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000726void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000727 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000728 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000729
Chris Lattnere5074c42009-06-22 01:29:09 +0000730 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000731 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000732 Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000733}
734
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000735StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000736 const char *Start = getTok().getLoc().getPointer();
737
Jim Grosbach4b905842013-09-20 23:08:21 +0000738 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000739 Lex();
740
741 const char *End = getTok().getLoc().getPointer();
742 return StringRef(Start, End - Start);
743}
Chris Lattner78db3622009-06-22 05:51:26 +0000744
Jim Grosbach4b905842013-09-20 23:08:21 +0000745StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000746 const char *Start = getTok().getLoc().getPointer();
747
748 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000749 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000750 Lex();
751
752 const char *End = getTok().getLoc().getPointer();
753 return StringRef(Start, End - Start);
754}
755
Jim Grosbach4b905842013-09-20 23:08:21 +0000756/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000757/// NOTE: This assumes the leading '(' has already been consumed.
758///
759/// parenexpr ::= expr)
760///
Jim Grosbach4b905842013-09-20 23:08:21 +0000761bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
762 if (parseExpression(Res))
763 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000764 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000765 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000766 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000767 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000768 return false;
769}
Chris Lattner78db3622009-06-22 05:51:26 +0000770
Jim Grosbach4b905842013-09-20 23:08:21 +0000771/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000772/// NOTE: This assumes the leading '[' has already been consumed.
773///
774/// bracketexpr ::= expr]
775///
Jim Grosbach4b905842013-09-20 23:08:21 +0000776bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
777 if (parseExpression(Res))
778 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000779 if (Lexer.isNot(AsmToken::RBrac))
780 return TokError("expected ']' in brackets expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000781 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000782 Lex();
783 return false;
784}
785
Jim Grosbach4b905842013-09-20 23:08:21 +0000786/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000787/// primaryexpr ::= (parenexpr
788/// primaryexpr ::= symbol
789/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000790/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000791/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000792bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000793 SMLoc FirstTokenLoc = getLexer().getLoc();
794 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
795 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000796 default:
797 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000798 // If we have an error assume that we've already handled it.
799 case AsmToken::Error:
800 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000801 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000802 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000803 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000804 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000805 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000806 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000807 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000808 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000809 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000810 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000811 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000812 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000813 if (FirstTokenKind == AsmToken::Dollar) {
814 if (Lexer.getMAI().getDollarIsPC()) {
815 // This is a '$' reference, which references the current PC. Emit a
816 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000817 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000818 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000819 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000820 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000821 EndLoc = FirstTokenLoc;
822 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000823 }
824 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000825 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000826 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000827 // Parse symbol variant
828 std::pair<StringRef, StringRef> Split;
829 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000830 if (FirstTokenKind == AsmToken::String) {
831 if (Lexer.is(AsmToken::At)) {
832 Lexer.Lex(); // eat @
833 SMLoc AtLoc = getLexer().getLoc();
834 StringRef VName;
835 if (parseIdentifier(VName))
836 return Error(AtLoc, "expected symbol variant after '@'");
837
838 Split = std::make_pair(Identifier, VName);
839 }
840 } else {
841 Split = Identifier.split('@');
842 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000843 } else if (Lexer.is(AsmToken::LParen)) {
844 Lexer.Lex(); // eat (
845 StringRef VName;
846 parseIdentifier(VName);
847 if (Lexer.isNot(AsmToken::RParen)) {
848 return Error(Lexer.getTok().getLoc(),
849 "unexpected token in variant, expected ')'");
850 }
851 Lexer.Lex(); // eat )
852 Split = std::make_pair(Identifier, VName);
853 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000854
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000855 EndLoc = SMLoc::getFromPointer(Identifier.end());
856
Daniel Dunbard20cda02009-10-16 01:34:54 +0000857 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000858 StringRef SymbolName = Identifier;
859 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000860
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000861 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000862 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000863 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000864 if (Variant != MCSymbolRefExpr::VK_Invalid) {
865 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000866 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000867 Variant = MCSymbolRefExpr::VK_None;
868 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000869 return Error(SMLoc::getFromPointer(Split.second.begin()),
870 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000871 }
872 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000873
Jim Grosbach6f482002015-05-18 18:43:14 +0000874 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000875
Daniel Dunbard20cda02009-10-16 01:34:54 +0000876 // If this is an absolute variable reference, substitute it now to preserve
877 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000878 if (Sym->isVariable() &&
879 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000880 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000881 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000882
Vedant Kumar86dbd922015-08-31 17:44:53 +0000883 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +0000884 return false;
885 }
886
887 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000888 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +0000889 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +0000890 }
David Woodhousef42a6662014-02-01 16:20:54 +0000891 case AsmToken::BigNum:
892 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +0000893 case AsmToken::Integer: {
894 SMLoc Loc = getTok().getLoc();
895 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000896 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000897 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000898 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +0000899 // Look for 'b' or 'f' following an Integer as a directional label
900 if (Lexer.getKind() == AsmToken::Identifier) {
901 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +0000902 // Lookup the symbol variant if used.
903 std::pair<StringRef, StringRef> Split = IDVal.split('@');
904 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
905 if (Split.first.size() != IDVal.size()) {
906 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +0000907 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +0000908 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000909 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +0000910 }
Jim Grosbach4b905842013-09-20 23:08:21 +0000911 if (IDVal == "f" || IDVal == "b") {
912 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +0000913 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +0000914 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +0000915 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderby0510b482010-05-17 23:08:19 +0000916 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000917 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +0000918 Lex(); // Eat identifier.
919 }
920 }
Chris Lattner78db3622009-06-22 05:51:26 +0000921 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +0000922 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000923 case AsmToken::Real: {
924 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +0000925 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000926 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000927 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000928 Lex(); // Eat token.
929 return false;
930 }
Chris Lattner6b55cb92010-04-14 04:40:28 +0000931 case AsmToken::Dot: {
932 // This is a '.' reference, which references the current PC. Emit a
933 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000934 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000935 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000936 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000937 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000938 Lex(); // Eat identifier.
939 return false;
940 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000941 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000942 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +0000943 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000944 case AsmToken::LBrac:
945 if (!PlatformParser->HasBracketExpressions())
946 return TokError("brackets expression not supported on this target");
947 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +0000948 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000949 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000950 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000951 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000952 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000953 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000954 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000955 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000956 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000957 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000958 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000959 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000960 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000961 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000962 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000963 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000964 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000965 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000966 return false;
Chris Lattner78db3622009-06-22 05:51:26 +0000967 }
968}
Chris Lattner7fdbce72009-06-22 06:32:03 +0000969
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000970bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +0000971 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000972 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +0000973}
974
Daniel Dunbar55f16672010-09-17 02:47:07 +0000975const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +0000976AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000977 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +0000978 // Ask the target implementation about this expression first.
979 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
980 if (NewE)
981 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000982 // Recurse over the given expression, rebuilding it to apply the given variant
983 // if there is exactly one symbol.
984 switch (E->getKind()) {
985 case MCExpr::Target:
986 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +0000987 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000988
989 case MCExpr::SymbolRef: {
990 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
991
992 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000993 TokError("invalid variant on expression '" + getTok().getIdentifier() +
994 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000995 return E;
996 }
997
Jim Grosbach13760bd2015-05-30 01:25:56 +0000998 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +0000999 }
1000
1001 case MCExpr::Unary: {
1002 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001003 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001004 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001005 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001006 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001007 }
1008
1009 case MCExpr::Binary: {
1010 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001011 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1012 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001013
1014 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001015 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001016
Jim Grosbach4b905842013-09-20 23:08:21 +00001017 if (!LHS)
1018 LHS = BE->getLHS();
1019 if (!RHS)
1020 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001021
Jim Grosbach13760bd2015-05-30 01:25:56 +00001022 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001023 }
1024 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001025
Craig Toppera2886c22012-02-07 05:05:23 +00001026 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001027}
1028
Jim Grosbach4b905842013-09-20 23:08:21 +00001029/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001030///
Jim Grosbachbd164242011-08-20 16:24:13 +00001031/// expr ::= expr &&,|| expr -> lowest.
1032/// expr ::= expr |,^,&,! expr
1033/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1034/// expr ::= expr <<,>> expr
1035/// expr ::= expr +,- expr
1036/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001037/// expr ::= primaryexpr
1038///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001039bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001040 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001041 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001042 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001043 return true;
1044
Daniel Dunbar55f16672010-09-17 02:47:07 +00001045 // As a special case, we support 'a op b @ modifier' by rewriting the
1046 // expression to include the modifier. This is inefficient, but in general we
1047 // expect users to use 'a@modifier op b'.
1048 if (Lexer.getKind() == AsmToken::At) {
1049 Lex();
1050
1051 if (Lexer.isNot(AsmToken::Identifier))
1052 return TokError("unexpected symbol modifier following '@'");
1053
1054 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001055 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001056 if (Variant == MCSymbolRefExpr::VK_Invalid)
1057 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1058
Jim Grosbach4b905842013-09-20 23:08:21 +00001059 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001060 if (!ModifiedRes) {
1061 return TokError("invalid modifier '" + getTok().getIdentifier() +
1062 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001063 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001064
Daniel Dunbar55f16672010-09-17 02:47:07 +00001065 Res = ModifiedRes;
1066 Lex();
1067 }
1068
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001069 // Try to constant fold it up front, if possible.
1070 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001071 if (Res->evaluateAsAbsolute(Value))
1072 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001073
1074 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001075}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001076
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001077bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001078 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001079 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001080}
1081
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001082bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1083 SMLoc &EndLoc) {
1084 if (parseParenExpr(Res, EndLoc))
1085 return true;
1086
1087 for (; ParenDepth > 0; --ParenDepth) {
1088 if (parseBinOpRHS(1, Res, EndLoc))
1089 return true;
1090
1091 // We don't Lex() the last RParen.
1092 // This is the same behavior as parseParenExpression().
1093 if (ParenDepth - 1 > 0) {
1094 if (Lexer.isNot(AsmToken::RParen))
1095 return TokError("expected ')' in parentheses expression");
1096 EndLoc = Lexer.getTok().getEndLoc();
1097 Lex();
1098 }
1099 }
1100 return false;
1101}
1102
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001103bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001104 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001105
Daniel Dunbar75630b32009-06-30 02:10:03 +00001106 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001107 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001108 return true;
1109
Jim Grosbach13760bd2015-05-30 01:25:56 +00001110 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001111 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001112
1113 return false;
1114}
1115
David Majnemer0993e0b2015-10-26 03:15:34 +00001116static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1117 MCBinaryExpr::Opcode &Kind,
1118 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001119 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001120 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001121 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001122
Jim Grosbach4b905842013-09-20 23:08:21 +00001123 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001124 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001125 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001126 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001127 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001128 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001129 return 1;
1130
Jim Grosbach4b905842013-09-20 23:08:21 +00001131 // Low Precedence: |, &, ^
1132 //
1133 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001134 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001135 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001136 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001137 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001138 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001139 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001140 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001141 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001142 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001143
Jim Grosbach4b905842013-09-20 23:08:21 +00001144 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001145 case AsmToken::EqualEqual:
1146 Kind = MCBinaryExpr::EQ;
1147 return 3;
1148 case AsmToken::ExclaimEqual:
1149 case AsmToken::LessGreater:
1150 Kind = MCBinaryExpr::NE;
1151 return 3;
1152 case AsmToken::Less:
1153 Kind = MCBinaryExpr::LT;
1154 return 3;
1155 case AsmToken::LessEqual:
1156 Kind = MCBinaryExpr::LTE;
1157 return 3;
1158 case AsmToken::Greater:
1159 Kind = MCBinaryExpr::GT;
1160 return 3;
1161 case AsmToken::GreaterEqual:
1162 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001163 return 3;
1164
Jim Grosbach4b905842013-09-20 23:08:21 +00001165 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001166 case AsmToken::LessLess:
1167 Kind = MCBinaryExpr::Shl;
1168 return 4;
1169 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001170 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001171 return 4;
1172
Jim Grosbach4b905842013-09-20 23:08:21 +00001173 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001174 case AsmToken::Plus:
1175 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001176 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001177 case AsmToken::Minus:
1178 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001179 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001180
Jim Grosbach4b905842013-09-20 23:08:21 +00001181 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001182 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001183 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001184 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001185 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001186 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001187 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001188 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001189 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001190 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001191 }
1192}
1193
David Majnemer0993e0b2015-10-26 03:15:34 +00001194static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1195 MCBinaryExpr::Opcode &Kind,
1196 bool ShouldUseLogicalShr) {
1197 switch (K) {
1198 default:
1199 return 0; // not a binop.
1200
1201 // Lowest Precedence: &&, ||
1202 case AsmToken::AmpAmp:
1203 Kind = MCBinaryExpr::LAnd;
1204 return 2;
1205 case AsmToken::PipePipe:
1206 Kind = MCBinaryExpr::LOr;
1207 return 1;
1208
1209 // Low Precedence: ==, !=, <>, <, <=, >, >=
1210 case AsmToken::EqualEqual:
1211 Kind = MCBinaryExpr::EQ;
1212 return 3;
1213 case AsmToken::ExclaimEqual:
1214 case AsmToken::LessGreater:
1215 Kind = MCBinaryExpr::NE;
1216 return 3;
1217 case AsmToken::Less:
1218 Kind = MCBinaryExpr::LT;
1219 return 3;
1220 case AsmToken::LessEqual:
1221 Kind = MCBinaryExpr::LTE;
1222 return 3;
1223 case AsmToken::Greater:
1224 Kind = MCBinaryExpr::GT;
1225 return 3;
1226 case AsmToken::GreaterEqual:
1227 Kind = MCBinaryExpr::GTE;
1228 return 3;
1229
1230 // Low Intermediate Precedence: +, -
1231 case AsmToken::Plus:
1232 Kind = MCBinaryExpr::Add;
1233 return 4;
1234 case AsmToken::Minus:
1235 Kind = MCBinaryExpr::Sub;
1236 return 4;
1237
1238 // High Intermediate Precedence: |, &, ^
1239 //
1240 // FIXME: gas seems to support '!' as an infix operator?
1241 case AsmToken::Pipe:
1242 Kind = MCBinaryExpr::Or;
1243 return 5;
1244 case AsmToken::Caret:
1245 Kind = MCBinaryExpr::Xor;
1246 return 5;
1247 case AsmToken::Amp:
1248 Kind = MCBinaryExpr::And;
1249 return 5;
1250
1251 // Highest Precedence: *, /, %, <<, >>
1252 case AsmToken::Star:
1253 Kind = MCBinaryExpr::Mul;
1254 return 6;
1255 case AsmToken::Slash:
1256 Kind = MCBinaryExpr::Div;
1257 return 6;
1258 case AsmToken::Percent:
1259 Kind = MCBinaryExpr::Mod;
1260 return 6;
1261 case AsmToken::LessLess:
1262 Kind = MCBinaryExpr::Shl;
1263 return 6;
1264 case AsmToken::GreaterGreater:
1265 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1266 return 6;
1267 }
1268}
1269
1270unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1271 MCBinaryExpr::Opcode &Kind) {
1272 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1273 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1274 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1275}
1276
Jim Grosbach4b905842013-09-20 23:08:21 +00001277/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001278/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001279bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001280 SMLoc &EndLoc) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001281 while (1) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001282 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001283 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001284
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001285 // If the next token is lower precedence than we are allowed to eat, return
1286 // successfully with what we ate already.
1287 if (TokPrec < Precedence)
1288 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001289
Sean Callanan686ed8d2010-01-19 20:22:31 +00001290 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001291
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001292 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001293 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001294 if (parsePrimaryExpr(RHS, EndLoc))
1295 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001296
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001297 // If BinOp binds less tightly with RHS than the operator after RHS, let
1298 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001299 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001300 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001301 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1302 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001303
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001304 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001305 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001306 }
1307}
1308
Chris Lattner36e02122009-06-21 20:54:55 +00001309/// ParseStatement:
1310/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001311/// ::= Label* Directive ...Operands... EndOfStatement
1312/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001313bool AsmParser::parseStatement(ParseStatementInfo &Info,
1314 MCAsmParserSemaCallback *SI) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001315 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001316 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001317 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001318 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001319 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001320
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001321 // Statements always start with an identifier or are a full line comment.
Sean Callanan936b0d32010-01-19 21:44:56 +00001322 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001323 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001324 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001325 int64_t LocalLabelVal = -1;
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001326 // A full line comment is a '#' as the first token.
Kevin Enderby72553612011-09-13 23:45:18 +00001327 if (Lexer.is(AsmToken::Hash))
Jim Grosbach4b905842013-09-20 23:08:21 +00001328 return parseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar3f561042011-03-25 17:47:14 +00001329
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001330 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001331 if (Lexer.is(AsmToken::Integer)) {
1332 LocalLabelVal = getTok().getIntVal();
1333 if (LocalLabelVal < 0) {
1334 if (!TheCondState.Ignore)
1335 return TokError("unexpected token at start of statement");
1336 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001337 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001338 IDVal = getTok().getString();
1339 Lex(); // Consume the integer token to be used as an identifier token.
1340 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001341 if (!TheCondState.Ignore)
1342 return TokError("unexpected token at start of statement");
Kevin Enderby0510b482010-05-17 23:08:19 +00001343 }
1344 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001345 } else if (Lexer.is(AsmToken::Dot)) {
1346 // Treat '.' as a valid identifier in this context.
1347 Lex();
1348 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001349 } else if (Lexer.is(AsmToken::LCurly)) {
1350 // Treat '{' as a valid identifier in this context.
1351 Lex();
1352 IDVal = "{";
1353
1354 } else if (Lexer.is(AsmToken::RCurly)) {
1355 // Treat '}' as a valid identifier in this context.
1356 Lex();
1357 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001358 } else if (parseIdentifier(IDVal)) {
Chris Lattner926885c2010-04-17 18:14:27 +00001359 if (!TheCondState.Ignore)
1360 return TokError("unexpected token at start of statement");
1361 IDVal = "";
1362 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001363
Chris Lattner926885c2010-04-17 18:14:27 +00001364 // Handle conditional assembly here before checking for skipping. We
1365 // have to do this so that .endif isn't skipped in a ".if 0" block for
1366 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001367 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001368 DirectiveKindMap.find(IDVal);
1369 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1370 ? DK_NO_DIRECTIVE
1371 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001372 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001373 default:
1374 break;
1375 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001376 case DK_IFEQ:
1377 case DK_IFGE:
1378 case DK_IFGT:
1379 case DK_IFLE:
1380 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001381 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001382 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001383 case DK_IFB:
1384 return parseDirectiveIfb(IDLoc, true);
1385 case DK_IFNB:
1386 return parseDirectiveIfb(IDLoc, false);
1387 case DK_IFC:
1388 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001389 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001390 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001391 case DK_IFNC:
1392 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001393 case DK_IFNES:
1394 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001395 case DK_IFDEF:
1396 return parseDirectiveIfdef(IDLoc, true);
1397 case DK_IFNDEF:
1398 case DK_IFNOTDEF:
1399 return parseDirectiveIfdef(IDLoc, false);
1400 case DK_ELSEIF:
1401 return parseDirectiveElseIf(IDLoc);
1402 case DK_ELSE:
1403 return parseDirectiveElse(IDLoc);
1404 case DK_ENDIF:
1405 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001406 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001407
Eli Bendersky88024712013-01-16 19:32:36 +00001408 // Ignore the statement if in the middle of inactive conditional
1409 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001410 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001411 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001412 return false;
1413 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001414
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001415 // FIXME: Recurse on local labels?
1416
1417 // See what kind of statement we have.
1418 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001419 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001420 if (!getTargetParser().isLabel(ID))
1421 break;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001422 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001423
Chris Lattner36e02122009-06-21 20:54:55 +00001424 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001425 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001426
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001427 // Diagnose attempt to use '.' as a label.
1428 if (IDVal == ".")
1429 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1430
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001431 // Diagnose attempt to use a variable as a label.
1432 //
1433 // FIXME: Diagnostics. Note the location of the definition as a label.
1434 // FIXME: This doesn't diagnose assignment to a symbol which has been
1435 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001436 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001437 if (LocalLabelVal == -1) {
1438 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001439 StringRef RewrittenLabel =
1440 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1441 assert(RewrittenLabel.size() &&
1442 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001443 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1444 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001445 IDVal = RewrittenLabel;
1446 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001447 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001448 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001449 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001450
1451 Sym->redefineIfPossible();
1452
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001453 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001454 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001455
Daniel Dunbare73b2672009-08-26 22:13:22 +00001456 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001457 if (!ParsingInlineAsm)
1458 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001459
Kevin Enderbye7739d42011-12-09 18:09:40 +00001460 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001461 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001462 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001463 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1464 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001465
Tim Northover1744d0a2013-10-25 12:49:50 +00001466 getTargetParser().onLabelParsed(Sym);
1467
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001468 // Consume any end of statement token, if present, to avoid spurious
1469 // AddBlankLine calls().
1470 if (Lexer.is(AsmToken::EndOfStatement)) {
1471 Lex();
1472 if (Lexer.is(AsmToken::Eof))
1473 return false;
1474 }
1475
Eli Friedman0f4871d2012-10-22 23:58:19 +00001476 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001477 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001478
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001479 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001480 if (!getTargetParser().equalIsAsmAssignment())
1481 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001482 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001483 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001484
Jim Grosbach4b905842013-09-20 23:08:21 +00001485 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001486
1487 default: // Normal instruction or directive.
1488 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001489 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001490
1491 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001492 if (areMacrosEnabled())
1493 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1494 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001495 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001496
Michael J. Spencer530ce852010-10-09 11:00:50 +00001497 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001498
Eli Bendersky17233942013-01-15 22:59:42 +00001499 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001500 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001501 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001502 //
Eli Bendersky17233942013-01-15 22:59:42 +00001503 // 1. The target-specific assembly parser. Some directives are target
1504 // specific or may potentially behave differently on certain targets.
1505 // 2. Asm parser extensions. For example, platform-specific parsers
1506 // (like the ELF parser) register themselves as extensions.
1507 // 3. The generic directive parser implemented by this class. These are
1508 // all the directives that behave in a target and platform independent
1509 // manner, or at least have a default behavior that's shared between
1510 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001511
Eli Bendersky17233942013-01-15 22:59:42 +00001512 // First query the target-specific parser. It will return 'true' if it
1513 // isn't interested in this directive.
Akira Hatanakad3590752012-07-05 19:09:33 +00001514 if (!getTargetParser().ParseDirective(ID))
1515 return false;
1516
Alp Tokercb402912014-01-24 17:20:08 +00001517 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001518 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001519 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1520 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001521 if (Handler.first)
1522 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1523
1524 // Finally, if no one else is interested in this directive, it must be
1525 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001526 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001527 default:
1528 break;
1529 case DK_SET:
1530 case DK_EQU:
1531 return parseDirectiveSet(IDVal, true);
1532 case DK_EQUIV:
1533 return parseDirectiveSet(IDVal, false);
1534 case DK_ASCII:
1535 return parseDirectiveAscii(IDVal, false);
1536 case DK_ASCIZ:
1537 case DK_STRING:
1538 return parseDirectiveAscii(IDVal, true);
1539 case DK_BYTE:
1540 return parseDirectiveValue(1);
1541 case DK_SHORT:
1542 case DK_VALUE:
1543 case DK_2BYTE:
1544 return parseDirectiveValue(2);
1545 case DK_LONG:
1546 case DK_INT:
1547 case DK_4BYTE:
1548 return parseDirectiveValue(4);
1549 case DK_QUAD:
1550 case DK_8BYTE:
1551 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001552 case DK_OCTA:
1553 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001554 case DK_SINGLE:
1555 case DK_FLOAT:
1556 return parseDirectiveRealValue(APFloat::IEEEsingle);
1557 case DK_DOUBLE:
1558 return parseDirectiveRealValue(APFloat::IEEEdouble);
1559 case DK_ALIGN: {
1560 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1561 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1562 }
1563 case DK_ALIGN32: {
1564 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1565 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1566 }
1567 case DK_BALIGN:
1568 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1569 case DK_BALIGNW:
1570 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1571 case DK_BALIGNL:
1572 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1573 case DK_P2ALIGN:
1574 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1575 case DK_P2ALIGNW:
1576 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1577 case DK_P2ALIGNL:
1578 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1579 case DK_ORG:
1580 return parseDirectiveOrg();
1581 case DK_FILL:
1582 return parseDirectiveFill();
1583 case DK_ZERO:
1584 return parseDirectiveZero();
1585 case DK_EXTERN:
1586 eatToEndOfStatement(); // .extern is the default, ignore it.
1587 return false;
1588 case DK_GLOBL:
1589 case DK_GLOBAL:
1590 return parseDirectiveSymbolAttribute(MCSA_Global);
1591 case DK_LAZY_REFERENCE:
1592 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1593 case DK_NO_DEAD_STRIP:
1594 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1595 case DK_SYMBOL_RESOLVER:
1596 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1597 case DK_PRIVATE_EXTERN:
1598 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1599 case DK_REFERENCE:
1600 return parseDirectiveSymbolAttribute(MCSA_Reference);
1601 case DK_WEAK_DEFINITION:
1602 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1603 case DK_WEAK_REFERENCE:
1604 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1605 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1606 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1607 case DK_COMM:
1608 case DK_COMMON:
1609 return parseDirectiveComm(/*IsLocal=*/false);
1610 case DK_LCOMM:
1611 return parseDirectiveComm(/*IsLocal=*/true);
1612 case DK_ABORT:
1613 return parseDirectiveAbort();
1614 case DK_INCLUDE:
1615 return parseDirectiveInclude();
1616 case DK_INCBIN:
1617 return parseDirectiveIncbin();
1618 case DK_CODE16:
1619 case DK_CODE16GCC:
1620 return TokError(Twine(IDVal) + " not supported yet");
1621 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001622 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001623 case DK_IRP:
1624 return parseDirectiveIrp(IDLoc);
1625 case DK_IRPC:
1626 return parseDirectiveIrpc(IDLoc);
1627 case DK_ENDR:
1628 return parseDirectiveEndr(IDLoc);
1629 case DK_BUNDLE_ALIGN_MODE:
1630 return parseDirectiveBundleAlignMode();
1631 case DK_BUNDLE_LOCK:
1632 return parseDirectiveBundleLock();
1633 case DK_BUNDLE_UNLOCK:
1634 return parseDirectiveBundleUnlock();
1635 case DK_SLEB128:
1636 return parseDirectiveLEB128(true);
1637 case DK_ULEB128:
1638 return parseDirectiveLEB128(false);
1639 case DK_SPACE:
1640 case DK_SKIP:
1641 return parseDirectiveSpace(IDVal);
1642 case DK_FILE:
1643 return parseDirectiveFile(IDLoc);
1644 case DK_LINE:
1645 return parseDirectiveLine();
1646 case DK_LOC:
1647 return parseDirectiveLoc();
1648 case DK_STABS:
1649 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001650 case DK_CV_FILE:
1651 return parseDirectiveCVFile();
1652 case DK_CV_LOC:
1653 return parseDirectiveCVLoc();
1654 case DK_CV_LINETABLE:
1655 return parseDirectiveCVLinetable();
1656 case DK_CV_STRINGTABLE:
1657 return parseDirectiveCVStringTable();
1658 case DK_CV_FILECHECKSUMS:
1659 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001660 case DK_CFI_SECTIONS:
1661 return parseDirectiveCFISections();
1662 case DK_CFI_STARTPROC:
1663 return parseDirectiveCFIStartProc();
1664 case DK_CFI_ENDPROC:
1665 return parseDirectiveCFIEndProc();
1666 case DK_CFI_DEF_CFA:
1667 return parseDirectiveCFIDefCfa(IDLoc);
1668 case DK_CFI_DEF_CFA_OFFSET:
1669 return parseDirectiveCFIDefCfaOffset();
1670 case DK_CFI_ADJUST_CFA_OFFSET:
1671 return parseDirectiveCFIAdjustCfaOffset();
1672 case DK_CFI_DEF_CFA_REGISTER:
1673 return parseDirectiveCFIDefCfaRegister(IDLoc);
1674 case DK_CFI_OFFSET:
1675 return parseDirectiveCFIOffset(IDLoc);
1676 case DK_CFI_REL_OFFSET:
1677 return parseDirectiveCFIRelOffset(IDLoc);
1678 case DK_CFI_PERSONALITY:
1679 return parseDirectiveCFIPersonalityOrLsda(true);
1680 case DK_CFI_LSDA:
1681 return parseDirectiveCFIPersonalityOrLsda(false);
1682 case DK_CFI_REMEMBER_STATE:
1683 return parseDirectiveCFIRememberState();
1684 case DK_CFI_RESTORE_STATE:
1685 return parseDirectiveCFIRestoreState();
1686 case DK_CFI_SAME_VALUE:
1687 return parseDirectiveCFISameValue(IDLoc);
1688 case DK_CFI_RESTORE:
1689 return parseDirectiveCFIRestore(IDLoc);
1690 case DK_CFI_ESCAPE:
1691 return parseDirectiveCFIEscape();
1692 case DK_CFI_SIGNAL_FRAME:
1693 return parseDirectiveCFISignalFrame();
1694 case DK_CFI_UNDEFINED:
1695 return parseDirectiveCFIUndefined(IDLoc);
1696 case DK_CFI_REGISTER:
1697 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001698 case DK_CFI_WINDOW_SAVE:
1699 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001700 case DK_MACROS_ON:
1701 case DK_MACROS_OFF:
1702 return parseDirectiveMacrosOnOff(IDVal);
1703 case DK_MACRO:
1704 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001705 case DK_EXITM:
1706 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001707 case DK_ENDM:
1708 case DK_ENDMACRO:
1709 return parseDirectiveEndMacro(IDVal);
1710 case DK_PURGEM:
1711 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001712 case DK_END:
1713 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001714 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001715 return parseDirectiveError(IDLoc, false);
1716 case DK_ERROR:
1717 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001718 case DK_WARNING:
1719 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001720 case DK_RELOC:
1721 return parseDirectiveReloc(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00001722 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001723
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001724 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001725 }
Chris Lattner36e02122009-06-21 20:54:55 +00001726
Chad Rosierc7f552c2013-02-12 21:33:51 +00001727 // __asm _emit or __asm __emit
1728 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1729 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001730 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001731
1732 // __asm align
1733 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001734 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001735
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001736 if (ParsingInlineAsm && (IDVal == "even"))
1737 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001738 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001739
Chris Lattner7cbfa442010-05-19 23:34:33 +00001740 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001741 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001742 ParseInstructionInfo IInfo(Info.AsmRewrites);
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001743 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001744 Info.ParsedOperands);
Chad Rosier149e8e02012-12-12 22:45:52 +00001745 Info.ParseError = HadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001746
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001747 // Dump the parsed representation, if requested.
1748 if (getShowParsedOperands()) {
1749 SmallString<256> Str;
1750 raw_svector_ostream OS(Str);
1751 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001752 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001753 if (i != 0)
1754 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001755 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001756 }
1757 OS << "]";
1758
Jim Grosbach4b905842013-09-20 23:08:21 +00001759 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001760 }
1761
Oliver Stannard8b273082014-06-19 15:52:37 +00001762 // If we are generating dwarf for the current section then generate a .loc
1763 // directive for the instruction.
Kevin Enderby6469fc22011-11-01 22:27:22 +00001764 if (!HadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001765 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001766 getStreamer().getCurrentSection().first)) {
1767 unsigned Line;
1768 if (ActiveMacros.empty())
1769 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1770 else
Frederic Riss16238d92015-06-25 21:57:33 +00001771 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1772 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001773
Eli Bendersky88024712013-01-16 19:32:36 +00001774 // If we previously parsed a cpp hash file line comment then make sure the
1775 // current Dwarf File is for the CppHashFilename if not then emit the
1776 // Dwarf File table for it and adjust the line number for the .loc.
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001777 if (CppHashFilename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001778 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1779 0, StringRef(), CppHashFilename);
1780 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001781
Jim Grosbach4b905842013-09-20 23:08:21 +00001782 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1783 // cache with the different Loc from the call above we save the last
1784 // info we queried here with SrcMgr.FindLineNumber().
1785 unsigned CppHashLocLineNo;
1786 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1787 CppHashLocLineNo = LastQueryLine;
1788 else {
1789 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1790 LastQueryLine = CppHashLocLineNo;
1791 LastQueryIDLoc = CppHashLoc;
1792 LastQueryBuffer = CppHashBuf;
1793 }
1794 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00001795 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001796
Jim Grosbach4b905842013-09-20 23:08:21 +00001797 getStreamer().EmitDwarfLocDirective(
1798 getContext().getGenDwarfFileNumber(), Line, 0,
1799 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1800 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00001801 }
1802
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00001803 // If parsing succeeded, match the instruction.
Chad Rosier49963552012-10-13 00:26:04 +00001804 if (!HadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00001805 uint64_t ErrorInfo;
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001806 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1807 Info.ParsedOperands, Out,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00001808 ErrorInfo, ParsingInlineAsm);
Chad Rosier49963552012-10-13 00:26:04 +00001809 }
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001810
Chris Lattnera2a9d162010-09-11 16:18:25 +00001811 // Don't skip the rest of the line, the instruction parser is responsible for
1812 // that.
1813 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00001814}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00001815
Jim Grosbach4b905842013-09-20 23:08:21 +00001816/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
Kevin Enderby72553612011-09-13 23:45:18 +00001817/// since they may not be able to be tokenized to get to the end of line token.
Jim Grosbach4b905842013-09-20 23:08:21 +00001818void AsmParser::eatToEndOfLine() {
Rafael Espindolae0d09082011-10-19 18:48:52 +00001819 if (!Lexer.is(AsmToken::EndOfStatement))
1820 Lexer.LexUntilEndOfLine();
Jim Grosbach4b905842013-09-20 23:08:21 +00001821 // Eat EOL.
1822 Lex();
Kevin Enderby72553612011-09-13 23:45:18 +00001823}
1824
Jim Grosbach4b905842013-09-20 23:08:21 +00001825/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00001826/// ::= # number "filename"
1827/// or just as a full line comment if it doesn't have a number and a string.
Craig Topper3c76c522015-09-20 23:35:59 +00001828bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00001829 Lex(); // Eat the hash token.
1830
1831 if (getLexer().isNot(AsmToken::Integer)) {
1832 // Consume the line since in cases it is not a well-formed line directive,
1833 // as if were simply a full line comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001834 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001835 return false;
1836 }
1837
1838 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00001839 Lex();
1840
1841 if (getLexer().isNot(AsmToken::String)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001842 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001843 return false;
1844 }
1845
1846 StringRef Filename = getTok().getString();
1847 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00001848 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00001849
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001850 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1851 CppHashLoc = L;
1852 CppHashFilename = Filename;
1853 CppHashLineNumber = LineNumber;
Kevin Enderby27121c12012-11-05 21:55:41 +00001854 CppHashBuf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00001855
1856 // Ignore any trailing characters, they're just comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001857 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001858 return false;
1859}
1860
Jim Grosbach4b905842013-09-20 23:08:21 +00001861/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001862/// for the Filename and LineNo if any in the diagnostic.
1863void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001864 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001865 raw_ostream &OS = errs();
1866
1867 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00001868 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00001869 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1870 unsigned CppHashBuf =
1871 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001872
Jim Grosbach4b905842013-09-20 23:08:21 +00001873 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001874 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00001875 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1876 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1877 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001878 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1879 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001880 }
1881
Eric Christophera7c32732012-12-18 00:30:54 +00001882 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001883 // manager changed or buffer changed (like in a nested include) then just
1884 // print the normal diagnostic using its Filename and LineNo.
Jim Grosbach4b905842013-09-20 23:08:21 +00001885 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001886 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001887 if (Parser->SavedDiagHandler)
1888 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1889 else
Craig Topper353eda42014-04-24 06:44:33 +00001890 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001891 return;
1892 }
1893
Eric Christophera7c32732012-12-18 00:30:54 +00001894 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001895 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1896 // the diagnostic.
Jakub Staszakec2ffa92013-09-16 22:03:38 +00001897 const std::string &Filename = Parser->CppHashFilename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001898
1899 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1900 int CppHashLocLineNo =
1901 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001902 int LineNo =
1903 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001904
Jim Grosbach4b905842013-09-20 23:08:21 +00001905 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1906 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00001907 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001908
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001909 if (Parser->SavedDiagHandler)
1910 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1911 else
Craig Topper353eda42014-04-24 06:44:33 +00001912 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001913}
1914
Rafael Espindola2c064482012-08-21 18:29:30 +00001915// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1916// difference being that that function accepts '@' as part of identifiers and
1917// we can't do that. AsmLexer.cpp should probably be changed to handle
1918// '@' as a special case when needed.
1919static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001920 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1921 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00001922}
1923
Rafael Espindola34b9c512012-06-03 23:57:14 +00001924bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00001925 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00001926 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00001927 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001928 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001929 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00001930 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00001931 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001932
Preston Gurd05500642012-09-19 20:36:12 +00001933 // A macro without parameters is handled differently on Darwin:
1934 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001935 while (!Body.empty()) {
1936 // Scan for the next substitution.
1937 std::size_t End = Body.size(), Pos = 0;
1938 for (; Pos != End; ++Pos) {
1939 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00001940 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001941 // This macro has no parameters, look for $0, $1, etc.
1942 if (Body[Pos] != '$' || Pos + 1 == End)
1943 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001944
Rafael Espindola1134ab232011-06-05 02:43:45 +00001945 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00001946 if (Next == '$' || Next == 'n' ||
1947 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00001948 break;
1949 } else {
1950 // This macro has parameters, look for \foo, \bar, etc.
1951 if (Body[Pos] == '\\' && Pos + 1 != End)
1952 break;
1953 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001954 }
1955
1956 // Add the prefix.
1957 OS << Body.slice(0, Pos);
1958
1959 // Check if we reached the end.
1960 if (Pos == End)
1961 break;
1962
Benjamin Kramer513e7442014-02-20 13:36:32 +00001963 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001964 switch (Body[Pos + 1]) {
1965 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00001966 case '$':
1967 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001968 break;
1969
Jim Grosbach4b905842013-09-20 23:08:21 +00001970 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00001971 case 'n':
1972 OS << A.size();
1973 break;
1974
Jim Grosbach4b905842013-09-20 23:08:21 +00001975 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00001976 default: {
1977 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00001978 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00001979 if (Index >= A.size())
1980 break;
1981
1982 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00001983 for (const AsmToken &Token : A[Index])
1984 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00001985 break;
1986 }
1987 }
1988 Pos += 2;
1989 } else {
1990 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00001991
1992 // Check for the \@ pseudo-variable.
1993 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00001994 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00001995 else
1996 while (isIdentifierChar(Body[I]) && I + 1 != End)
1997 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00001998
Jim Grosbach4b905842013-09-20 23:08:21 +00001999 const char *Begin = Body.data() + Pos + 1;
2000 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002001 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002002
Toma Tabacu217116e2015-04-27 10:50:29 +00002003 if (Argument == "@") {
2004 OS << NumOfMacroInstantiations;
2005 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002006 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002007 for (; Index < NParameters; ++Index)
2008 if (Parameters[Index].Name == Argument)
2009 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002010
Toma Tabacu217116e2015-04-27 10:50:29 +00002011 if (Index == NParameters) {
2012 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2013 Pos += 3;
2014 else {
2015 OS << '\\' << Argument;
2016 Pos = I;
2017 }
2018 } else {
2019 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002020 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002021 // We expect no quotes around the string's contents when
2022 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002023 if (Token.getKind() != AsmToken::String || VarargParameter)
2024 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002025 else
Craig Topper84008482015-10-10 05:38:14 +00002026 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002027
2028 Pos += 1 + Argument.size();
2029 }
Preston Gurd05500642012-09-19 20:36:12 +00002030 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002031 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002032 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002033 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002034 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002035
Rafael Espindola1134ab232011-06-05 02:43:45 +00002036 return false;
2037}
Daniel Dunbar43235712010-07-18 18:54:11 +00002038
Nico Weber2a8f9222014-07-24 16:29:04 +00002039MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002040 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002041 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002042 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002043
Jim Grosbach4b905842013-09-20 23:08:21 +00002044static bool isOperator(AsmToken::TokenKind kind) {
2045 switch (kind) {
2046 default:
2047 return false;
2048 case AsmToken::Plus:
2049 case AsmToken::Minus:
2050 case AsmToken::Tilde:
2051 case AsmToken::Slash:
2052 case AsmToken::Star:
2053 case AsmToken::Dot:
2054 case AsmToken::Equal:
2055 case AsmToken::EqualEqual:
2056 case AsmToken::Pipe:
2057 case AsmToken::PipePipe:
2058 case AsmToken::Caret:
2059 case AsmToken::Amp:
2060 case AsmToken::AmpAmp:
2061 case AsmToken::Exclaim:
2062 case AsmToken::ExclaimEqual:
2063 case AsmToken::Percent:
2064 case AsmToken::Less:
2065 case AsmToken::LessEqual:
2066 case AsmToken::LessLess:
2067 case AsmToken::LessGreater:
2068 case AsmToken::Greater:
2069 case AsmToken::GreaterEqual:
2070 case AsmToken::GreaterGreater:
2071 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002072 }
2073}
2074
David Majnemer16252452014-01-29 00:07:39 +00002075namespace {
2076class AsmLexerSkipSpaceRAII {
2077public:
2078 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2079 Lexer.setSkipSpace(SkipSpace);
2080 }
2081
2082 ~AsmLexerSkipSpaceRAII() {
2083 Lexer.setSkipSpace(true);
2084 }
2085
2086private:
2087 AsmLexer &Lexer;
2088};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002089}
David Majnemer16252452014-01-29 00:07:39 +00002090
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002091bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2092
2093 if (Vararg) {
2094 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2095 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002096 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002097 }
2098 return false;
2099 }
2100
Rafael Espindola768b41c2012-06-15 14:02:34 +00002101 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002102 unsigned AddTokens = 0;
2103
David Majnemer16252452014-01-29 00:07:39 +00002104 // Darwin doesn't use spaces to delmit arguments.
2105 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002106
2107 for (;;) {
David Majnemer16252452014-01-29 00:07:39 +00002108 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002109 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002110
David Majnemer91fc4c22014-01-29 18:57:46 +00002111 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
Preston Gurd05500642012-09-19 20:36:12 +00002112 break;
Preston Gurd05500642012-09-19 20:36:12 +00002113
2114 if (Lexer.is(AsmToken::Space)) {
2115 Lex(); // Eat spaces
2116
2117 // Spaces can delimit parameters, but could also be part an expression.
2118 // If the token after a space is an operator, add the token and the next
2119 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002120 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002121 if (isOperator(Lexer.getKind())) {
Preston Gurd05500642012-09-19 20:36:12 +00002122 // Check to see whether the token is used as an operator,
2123 // or part of an identifier
Jordan Rosee8f1eae2013-01-07 19:00:49 +00002124 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd05500642012-09-19 20:36:12 +00002125 if (*NextChar == ' ')
2126 AddTokens = 2;
2127 }
2128
2129 if (!AddTokens && ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002130 break;
2131 }
2132 }
2133 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002134
Jim Grosbach4b905842013-09-20 23:08:21 +00002135 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002136 // to be able to fill in the remaining default parameter values
2137 if (Lexer.is(AsmToken::EndOfStatement))
2138 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002139
2140 // Adjust the current parentheses level.
2141 if (Lexer.is(AsmToken::LParen))
2142 ++ParenLevel;
2143 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2144 --ParenLevel;
2145
2146 // Append the token to the current argument list.
2147 MA.push_back(getTok());
Preston Gurd05500642012-09-19 20:36:12 +00002148 if (AddTokens)
2149 AddTokens--;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002150 Lex();
2151 }
Preston Gurd05500642012-09-19 20:36:12 +00002152
Rafael Espindola768b41c2012-06-15 14:02:34 +00002153 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002154 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002155 return false;
2156}
2157
2158// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002159bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002160 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002161 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002162 bool NamedParametersFound = false;
2163 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002164
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002165 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002166 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002167
Rafael Espindola768b41c2012-06-15 14:02:34 +00002168 // Parse two kinds of macro invocations:
2169 // - macros defined without any parameters accept an arbitrary number of them
2170 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002171 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002172 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2173 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002174 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002175 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002176
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002177 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002178 if (parseIdentifier(FA.Name)) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002179 Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002180 eatToEndOfStatement();
2181 return true;
2182 }
2183
2184 if (!Lexer.is(AsmToken::Equal)) {
2185 TokError("expected '=' after formal parameter identifier");
2186 eatToEndOfStatement();
2187 return true;
2188 }
2189 Lex();
2190
2191 NamedParametersFound = true;
2192 }
2193
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002194 if (NamedParametersFound && FA.Name.empty()) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002195 Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002196 eatToEndOfStatement();
2197 return true;
2198 }
2199
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002200 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2201 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002202 return true;
2203
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002204 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002205 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002206 unsigned FAI = 0;
2207 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002208 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002209 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002210
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002211 if (FAI >= NParameters) {
Oliver Stannard8b273082014-06-19 15:52:37 +00002212 assert(M && "expected macro to be defined");
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002213 Error(IDLoc,
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002214 "parameter named '" + FA.Name + "' does not exist for macro '" +
Saleem Abdulrasool3f44cd72014-03-17 17:13:57 +00002215 M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002216 return true;
2217 }
2218 PI = FAI;
2219 }
2220
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002221 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002222 if (A.size() <= PI)
2223 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002224 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002225
2226 if (FALocs.size() <= PI)
2227 FALocs.resize(PI + 1);
2228
2229 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002230 }
Jim Grosbach206661622012-07-30 22:44:17 +00002231
Preston Gurd242ed3152012-09-19 20:29:04 +00002232 // At the end of the statement, fill in remaining arguments that have
2233 // default values. If there aren't any, then the next argument is
2234 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002235 if (Lexer.is(AsmToken::EndOfStatement)) {
2236 bool Failure = false;
2237 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2238 if (A[FAI].empty()) {
2239 if (M->Parameters[FAI].Required) {
2240 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2241 "missing value for required parameter "
2242 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2243 Failure = true;
2244 }
2245
2246 if (!M->Parameters[FAI].Value.empty())
2247 A[FAI] = M->Parameters[FAI].Value;
2248 }
2249 }
2250 return Failure;
2251 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002252
2253 if (Lexer.is(AsmToken::Comma))
2254 Lex();
2255 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002256
2257 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002258}
2259
Jim Grosbach4b905842013-09-20 23:08:21 +00002260const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002261 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2262 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002263}
2264
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002265void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2266 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002267}
2268
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002269void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002270
Jim Grosbach4b905842013-09-20 23:08:21 +00002271bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbar43235712010-07-18 18:54:11 +00002272 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2273 // this, although we should protect against infinite loops.
2274 if (ActiveMacros.size() == 20)
2275 return TokError("macros cannot be nested more than 20 levels deep");
2276
Eli Bendersky38274122013-01-14 23:22:36 +00002277 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002278 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002279 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002280
Rafael Espindola1134ab232011-06-05 02:43:45 +00002281 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2282 // to hold the macro body with substitutions.
2283 SmallString<256> Buf;
2284 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002285 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002286
Toma Tabacu217116e2015-04-27 10:50:29 +00002287 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002288 return true;
2289
Eli Bendersky38274122013-01-14 23:22:36 +00002290 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002291 // instantiation.
2292 OS << ".endmacro\n";
2293
Rafael Espindola3560ff22014-08-27 20:03:13 +00002294 std::unique_ptr<MemoryBuffer> Instantiation =
2295 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002296
Daniel Dunbar43235712010-07-18 18:54:11 +00002297 // Create the macro instantiation object and add to the current macro
2298 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002299 MacroInstantiation *MI = new MacroInstantiation(
2300 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002301 ActiveMacros.push_back(MI);
2302
Toma Tabacu217116e2015-04-27 10:50:29 +00002303 ++NumOfMacroInstantiations;
2304
Daniel Dunbar43235712010-07-18 18:54:11 +00002305 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002306 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002307 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002308 Lex();
2309
2310 return false;
2311}
2312
Jim Grosbach4b905842013-09-20 23:08:21 +00002313void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002314 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002315 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002316 Lex();
2317
2318 // Pop the instantiation entry.
2319 delete ActiveMacros.back();
2320 ActiveMacros.pop_back();
2321}
2322
Jim Grosbach4b905842013-09-20 23:08:21 +00002323bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002324 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002325 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002326 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002327 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2328 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002329 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002330
Pete Cooper80d21cb2015-06-22 19:35:57 +00002331 if (!Sym) {
2332 // In the case where we parse an expression starting with a '.', we will
2333 // not generate an error, nor will we create a symbol. In this case we
2334 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002335 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002336 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002337
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002338 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002339 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002340 if (NoDeadStrip)
2341 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2342
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002343 return false;
2344}
2345
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002346/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002347/// ::= identifier
2348/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002349bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002350 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002351 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2352 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002353 // handle this as a context dependent token, instead we detect adjacent tokens
2354 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002355 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2356 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002357
Hans Wennborgce69d772013-10-18 20:46:28 +00002358 // Consume the prefix character, and check for a following identifier.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002359 Lex();
2360 if (Lexer.isNot(AsmToken::Identifier))
2361 return true;
2362
Hans Wennborgce69d772013-10-18 20:46:28 +00002363 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2364 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002365 return true;
2366
2367 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002368 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002369 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002370 Lex();
2371 return false;
2372 }
2373
Jim Grosbach4b905842013-09-20 23:08:21 +00002374 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002375 return true;
2376
Sean Callanan936b0d32010-01-19 21:44:56 +00002377 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002378
Sean Callanan686ed8d2010-01-19 20:22:31 +00002379 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002380
2381 return false;
2382}
2383
Jim Grosbach4b905842013-09-20 23:08:21 +00002384/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002385/// ::= .equ identifier ',' expression
2386/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002387/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002388bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002389 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002390
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002391 if (parseIdentifier(Name))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002392 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencer530ce852010-10-09 11:00:50 +00002393
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002394 if (getLexer().isNot(AsmToken::Comma))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002395 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002396 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002397
Jim Grosbach4b905842013-09-20 23:08:21 +00002398 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002399}
2400
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002401bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002402 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002403
2404 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002405 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002406 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2407 if (Str[i] != '\\') {
2408 Data += Str[i];
2409 continue;
2410 }
2411
2412 // Recognize escaped characters. Note that this escape semantics currently
2413 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2414 ++i;
2415 if (i == e)
2416 return TokError("unexpected backslash at end of string");
2417
2418 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002419 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002420 // Consume up to three octal characters.
2421 unsigned Value = Str[i] - '0';
2422
Jim Grosbach4b905842013-09-20 23:08:21 +00002423 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002424 ++i;
2425 Value = Value * 8 + (Str[i] - '0');
2426
Jim Grosbach4b905842013-09-20 23:08:21 +00002427 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002428 ++i;
2429 Value = Value * 8 + (Str[i] - '0');
2430 }
2431 }
2432
2433 if (Value > 255)
2434 return TokError("invalid octal escape sequence (out of range)");
2435
Jim Grosbach4b905842013-09-20 23:08:21 +00002436 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002437 continue;
2438 }
2439
2440 // Otherwise recognize individual escapes.
2441 switch (Str[i]) {
2442 default:
2443 // Just reject invalid escape sequences for now.
2444 return TokError("invalid escape sequence (unrecognized character)");
2445
2446 case 'b': Data += '\b'; break;
2447 case 'f': Data += '\f'; break;
2448 case 'n': Data += '\n'; break;
2449 case 'r': Data += '\r'; break;
2450 case 't': Data += '\t'; break;
2451 case '"': Data += '"'; break;
2452 case '\\': Data += '\\'; break;
2453 }
2454 }
2455
2456 return false;
2457}
2458
Jim Grosbach4b905842013-09-20 23:08:21 +00002459/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002460/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002461bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002462 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002463 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002464
Daniel Dunbara10e5192009-06-24 23:30:00 +00002465 for (;;) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002466 if (getLexer().isNot(AsmToken::String))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002467 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002468
Daniel Dunbaref668c12009-08-14 18:19:52 +00002469 std::string Data;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002470 if (parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002471 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002472
Rafael Espindola64e1af82013-07-02 15:49:13 +00002473 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002474 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002475 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002476
Sean Callanan686ed8d2010-01-19 20:22:31 +00002477 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002478
2479 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002480 break;
2481
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002482 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002483 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002484 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002485 }
2486 }
2487
Sean Callanan686ed8d2010-01-19 20:22:31 +00002488 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002489 return false;
2490}
2491
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002492/// parseDirectiveReloc
2493/// ::= .reloc expression , identifier [ , expression ]
2494bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2495 const MCExpr *Offset;
2496 const MCExpr *Expr = nullptr;
2497
2498 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2499 if (parseExpression(Offset))
2500 return true;
2501
2502 // We can only deal with constant expressions at the moment.
2503 int64_t OffsetValue;
2504 if (!Offset->evaluateAsAbsolute(OffsetValue))
2505 return Error(OffsetLoc, "expression is not a constant value");
2506
David Majnemerce108422016-01-19 23:05:27 +00002507 if (OffsetValue < 0)
2508 return Error(OffsetLoc, "expression is negative");
2509
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002510 if (Lexer.isNot(AsmToken::Comma))
2511 return TokError("expected comma");
2512 Lexer.Lex();
2513
2514 if (Lexer.isNot(AsmToken::Identifier))
2515 return TokError("expected relocation name");
2516 SMLoc NameLoc = Lexer.getTok().getLoc();
2517 StringRef Name = Lexer.getTok().getIdentifier();
2518 Lexer.Lex();
2519
2520 if (Lexer.is(AsmToken::Comma)) {
2521 Lexer.Lex();
2522 SMLoc ExprLoc = Lexer.getLoc();
2523 if (parseExpression(Expr))
2524 return true;
2525
2526 MCValue Value;
2527 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2528 return Error(ExprLoc, "expression must be relocatable");
2529 }
2530
2531 if (Lexer.isNot(AsmToken::EndOfStatement))
2532 return TokError("unexpected token in .reloc directive");
2533
2534 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2535 return Error(NameLoc, "unknown relocation name");
2536
2537 return false;
2538}
2539
Jim Grosbach4b905842013-09-20 23:08:21 +00002540/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002541/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002542bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002543 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002544 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002545
Daniel Dunbara10e5192009-06-24 23:30:00 +00002546 for (;;) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002547 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002548 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002549 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002550 return true;
2551
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002552 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002553 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2554 assert(Size <= 8 && "Invalid size");
2555 uint64_t IntValue = MCE->getValue();
2556 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2557 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002558 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002559 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002560 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002561
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002562 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002563 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002564
Daniel Dunbara10e5192009-06-24 23:30:00 +00002565 // FIXME: Improve diagnostic.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002566 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002567 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002568 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002569 }
2570 }
2571
Sean Callanan686ed8d2010-01-19 20:22:31 +00002572 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002573 return false;
2574}
2575
David Woodhoused6de0d92014-02-01 16:20:59 +00002576/// ParseDirectiveOctaValue
2577/// ::= .octa [ hexconstant (, hexconstant)* ]
2578bool AsmParser::parseDirectiveOctaValue() {
2579 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2580 checkForValidSection();
2581
2582 for (;;) {
2583 if (Lexer.getKind() == AsmToken::Error)
2584 return true;
2585 if (Lexer.getKind() != AsmToken::Integer &&
2586 Lexer.getKind() != AsmToken::BigNum)
2587 return TokError("unknown token in expression");
2588
2589 SMLoc ExprLoc = getLexer().getLoc();
2590 APInt IntValue = getTok().getAPIntVal();
2591 Lex();
2592
2593 uint64_t hi, lo;
2594 if (IntValue.isIntN(64)) {
2595 hi = 0;
2596 lo = IntValue.getZExtValue();
2597 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002598 // It might actually have more than 128 bits, but the top ones are zero.
2599 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002600 lo = IntValue.getLoBits(64).getZExtValue();
2601 } else
2602 return Error(ExprLoc, "literal value out of range for directive");
2603
2604 if (MAI.isLittleEndian()) {
2605 getStreamer().EmitIntValue(lo, 8);
2606 getStreamer().EmitIntValue(hi, 8);
2607 } else {
2608 getStreamer().EmitIntValue(hi, 8);
2609 getStreamer().EmitIntValue(lo, 8);
2610 }
2611
2612 if (getLexer().is(AsmToken::EndOfStatement))
2613 break;
2614
2615 // FIXME: Improve diagnostic.
2616 if (getLexer().isNot(AsmToken::Comma))
2617 return TokError("unexpected token in directive");
2618 Lex();
2619 }
2620 }
2621
2622 Lex();
2623 return false;
2624}
2625
Jim Grosbach4b905842013-09-20 23:08:21 +00002626/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002627/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002628bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002629 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002630 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002631
2632 for (;;) {
2633 // We don't truly support arithmetic on floating point expressions, so we
2634 // have to manually parse unary prefixes.
2635 bool IsNeg = false;
2636 if (getLexer().is(AsmToken::Minus)) {
2637 Lex();
2638 IsNeg = true;
2639 } else if (getLexer().is(AsmToken::Plus))
2640 Lex();
2641
Michael J. Spencer530ce852010-10-09 11:00:50 +00002642 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002643 getLexer().isNot(AsmToken::Real) &&
2644 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002645 return TokError("unexpected token in directive");
2646
2647 // Convert to an APFloat.
2648 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002649 StringRef IDVal = getTok().getString();
2650 if (getLexer().is(AsmToken::Identifier)) {
2651 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2652 Value = APFloat::getInf(Semantics);
2653 else if (!IDVal.compare_lower("nan"))
2654 Value = APFloat::getNaN(Semantics, false, ~0);
2655 else
2656 return TokError("invalid floating point literal");
2657 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002658 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002659 return TokError("invalid floating point literal");
2660 if (IsNeg)
2661 Value.changeSign();
2662
2663 // Consume the numeric token.
2664 Lex();
2665
2666 // Emit the value as an integer.
2667 APInt AsInt = Value.bitcastToAPInt();
2668 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002669 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002670
2671 if (getLexer().is(AsmToken::EndOfStatement))
2672 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002673
Daniel Dunbar2af16532010-09-24 01:59:56 +00002674 if (getLexer().isNot(AsmToken::Comma))
2675 return TokError("unexpected token in directive");
2676 Lex();
2677 }
2678 }
2679
2680 Lex();
2681 return false;
2682}
2683
Jim Grosbach4b905842013-09-20 23:08:21 +00002684/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002685/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002686bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002687 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002688
2689 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002690 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002691 return true;
2692
Rafael Espindolab91bac62010-10-05 19:42:57 +00002693 int64_t Val = 0;
2694 if (getLexer().is(AsmToken::Comma)) {
2695 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002696 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002697 return true;
2698 }
2699
Rafael Espindola922e3f42010-09-16 15:03:59 +00002700 if (getLexer().isNot(AsmToken::EndOfStatement))
2701 return TokError("unexpected token in '.zero' directive");
2702
2703 Lex();
2704
Rafael Espindola64e1af82013-07-02 15:49:13 +00002705 getStreamer().EmitFill(NumBytes, Val);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002706
2707 return false;
2708}
2709
Jim Grosbach4b905842013-09-20 23:08:21 +00002710/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002711/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002712bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002713 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002714
David Majnemer522d3db2014-02-01 07:19:38 +00002715 SMLoc RepeatLoc = getLexer().getLoc();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002716 int64_t NumValues;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002717 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002718 return true;
2719
David Majnemer522d3db2014-02-01 07:19:38 +00002720 if (NumValues < 0) {
2721 Warning(RepeatLoc,
2722 "'.fill' directive with negative repeat count has no effect");
2723 NumValues = 0;
2724 }
2725
Roman Divackye33098f2013-09-24 17:44:41 +00002726 int64_t FillSize = 1;
2727 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002728
David Majnemer522d3db2014-02-01 07:19:38 +00002729 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002730 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2731 if (getLexer().isNot(AsmToken::Comma))
2732 return TokError("unexpected token in '.fill' directive");
2733 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002734
David Majnemer522d3db2014-02-01 07:19:38 +00002735 SizeLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002736 if (parseAbsoluteExpression(FillSize))
2737 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002738
Roman Divackye33098f2013-09-24 17:44:41 +00002739 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2740 if (getLexer().isNot(AsmToken::Comma))
2741 return TokError("unexpected token in '.fill' directive");
2742 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002743
David Majnemer522d3db2014-02-01 07:19:38 +00002744 ExprLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002745 if (parseAbsoluteExpression(FillExpr))
2746 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002747
Roman Divackye33098f2013-09-24 17:44:41 +00002748 if (getLexer().isNot(AsmToken::EndOfStatement))
2749 return TokError("unexpected token in '.fill' directive");
2750
2751 Lex();
2752 }
2753 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002754
David Majnemer522d3db2014-02-01 07:19:38 +00002755 if (FillSize < 0) {
2756 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2757 NumValues = 0;
2758 }
2759 if (FillSize > 8) {
2760 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2761 FillSize = 8;
2762 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002763
David Majnemer522d3db2014-02-01 07:19:38 +00002764 if (!isUInt<32>(FillExpr) && FillSize > 4)
2765 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2766
Alexey Samsonov1b0713c2014-09-02 17:25:29 +00002767 if (NumValues > 0) {
2768 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2769 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2770 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2771 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2772 if (NonZeroFillSize < FillSize)
2773 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2774 }
David Majnemer522d3db2014-02-01 07:19:38 +00002775 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002776
2777 return false;
2778}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002779
Jim Grosbach4b905842013-09-20 23:08:21 +00002780/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002781/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002782bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002783 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002784
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002785 const MCExpr *Offset;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002786 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002787 return true;
2788
2789 // Parse optional fill expression.
2790 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002791 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2792 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002793 return TokError("unexpected token in '.org' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002794 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00002795
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002796 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002797 return true;
2798
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002799 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002800 return TokError("unexpected token in '.org' directive");
2801 }
2802
Sean Callanan686ed8d2010-01-19 20:22:31 +00002803 Lex();
Rafael Espindola7ae65d82015-11-04 23:59:18 +00002804 getStreamer().emitValueToOffset(Offset, FillExpr);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002805 return false;
2806}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002807
Jim Grosbach4b905842013-09-20 23:08:21 +00002808/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002809/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002810bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002811 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002812
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002813 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002814 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002815 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002816 return true;
2817
2818 SMLoc MaxBytesLoc;
2819 bool HasFillExpr = false;
2820 int64_t FillExpr = 0;
2821 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002822 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2823 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002824 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002825 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002826
2827 // The fill expression can be omitted while specifying a maximum number of
2828 // alignment bytes, e.g:
2829 // .align 3,,4
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002830 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002831 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002832 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002833 return true;
2834 }
2835
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002836 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2837 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002838 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002839 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002840
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002841 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002842 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002843 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002844
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002845 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002846 return TokError("unexpected token in directive");
2847 }
2848 }
2849
Sean Callanan686ed8d2010-01-19 20:22:31 +00002850 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002851
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002852 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002853 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002854
2855 // Compute alignment in bytes.
2856 if (IsPow2) {
2857 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002858 if (Alignment >= 32) {
2859 Error(AlignmentLoc, "invalid alignment value");
2860 Alignment = 31;
2861 }
2862
Benjamin Kramer63951ad2009-09-06 09:35:10 +00002863 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002864 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00002865 // Reject alignments that aren't either a power of two or zero,
2866 // for gas compatibility. Alignment of zero is silently rounded
2867 // up to one.
2868 if (Alignment == 0)
2869 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002870 if (!isPowerOf2_64(Alignment))
2871 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002872 }
2873
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002874 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002875 if (MaxBytesLoc.isValid()) {
2876 if (MaxBytesToFill < 1) {
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002877 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00002878 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00002879 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002880 }
2881
2882 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00002883 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00002884 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002885 MaxBytesToFill = 0;
2886 }
2887 }
2888
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002889 // Check whether we should use optimal code alignment for this .align
2890 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00002891 const MCSection *Section = getStreamer().getCurrentSection().first;
2892 assert(Section && "must have section to emit alignment");
2893 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002894 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2895 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002896 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002897 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00002898 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00002899 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2900 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002901 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002902
2903 return false;
2904}
2905
Jim Grosbach4b905842013-09-20 23:08:21 +00002906/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00002907/// ::= .file [number] filename
2908/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00002909bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00002910 // FIXME: I'm not sure what this is.
2911 int64_t FileNumber = -1;
2912 SMLoc FileNumberLoc = getLexer().getLoc();
2913 if (getLexer().is(AsmToken::Integer)) {
2914 FileNumber = getTok().getIntVal();
2915 Lex();
2916
2917 if (FileNumber < 1)
2918 return TokError("file number less than one");
2919 }
2920
2921 if (getLexer().isNot(AsmToken::String))
2922 return TokError("unexpected token in '.file' directive");
2923
2924 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002925 // Allow the strings to have escaped octal character sequence.
2926 std::string Path = getTok().getString();
2927 if (parseEscapedString(Path))
2928 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00002929 Lex();
2930
2931 StringRef Directory;
2932 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002933 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002934 if (getLexer().is(AsmToken::String)) {
2935 if (FileNumber == -1)
2936 return TokError("explicit path specified, but no file number");
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002937 if (parseEscapedString(FilenameData))
2938 return true;
2939 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002940 Directory = Path;
2941 Lex();
2942 } else {
2943 Filename = Path;
2944 }
2945
2946 if (getLexer().isNot(AsmToken::EndOfStatement))
2947 return TokError("unexpected token in '.file' directive");
2948
2949 if (FileNumber == -1)
2950 getStreamer().EmitFileDirective(Filename);
2951 else {
David Blaikiedc3f01e2015-03-09 01:57:13 +00002952 if (getContext().getGenDwarfForAssembly())
Jim Grosbach4b905842013-09-20 23:08:21 +00002953 Error(DirectiveLoc,
2954 "input can't have .file dwarf directives when -g is "
2955 "used to generate dwarf debug info for assembly code");
Eli Bendersky17233942013-01-15 22:59:42 +00002956
David Blaikiec714ef42014-03-17 01:52:11 +00002957 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2958 0)
Eli Bendersky17233942013-01-15 22:59:42 +00002959 Error(FileNumberLoc, "file number already allocated");
2960 }
2961
2962 return false;
2963}
2964
Jim Grosbach4b905842013-09-20 23:08:21 +00002965/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00002966/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00002967bool AsmParser::parseDirectiveLine() {
Eli Bendersky17233942013-01-15 22:59:42 +00002968 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2969 if (getLexer().isNot(AsmToken::Integer))
2970 return TokError("unexpected token in '.line' directive");
2971
2972 int64_t LineNumber = getTok().getIntVal();
Jim Grosbach4b905842013-09-20 23:08:21 +00002973 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00002974 Lex();
2975
2976 // FIXME: Do something with the .line.
2977 }
2978
2979 if (getLexer().isNot(AsmToken::EndOfStatement))
2980 return TokError("unexpected token in '.line' directive");
2981
2982 return false;
2983}
2984
Jim Grosbach4b905842013-09-20 23:08:21 +00002985/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00002986/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2987/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2988/// The first number is a file number, must have been previously assigned with
2989/// a .file directive, the second number is the line number and optionally the
2990/// third number is a column position (zero if not specified). The remaining
2991/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00002992bool AsmParser::parseDirectiveLoc() {
Eli Bendersky17233942013-01-15 22:59:42 +00002993 if (getLexer().isNot(AsmToken::Integer))
2994 return TokError("unexpected token in '.loc' directive");
2995 int64_t FileNumber = getTok().getIntVal();
2996 if (FileNumber < 1)
2997 return TokError("file number less than one in '.loc' directive");
2998 if (!getContext().isValidDwarfFileNumber(FileNumber))
2999 return TokError("unassigned file number in '.loc' directive");
3000 Lex();
3001
3002 int64_t LineNumber = 0;
3003 if (getLexer().is(AsmToken::Integer)) {
3004 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003005 if (LineNumber < 0)
3006 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003007 Lex();
3008 }
3009
3010 int64_t ColumnPos = 0;
3011 if (getLexer().is(AsmToken::Integer)) {
3012 ColumnPos = getTok().getIntVal();
3013 if (ColumnPos < 0)
3014 return TokError("column position less than zero in '.loc' directive");
3015 Lex();
3016 }
3017
3018 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3019 unsigned Isa = 0;
3020 int64_t Discriminator = 0;
3021 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3022 for (;;) {
3023 if (getLexer().is(AsmToken::EndOfStatement))
3024 break;
3025
3026 StringRef Name;
3027 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003028 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003029 return TokError("unexpected token in '.loc' directive");
3030
3031 if (Name == "basic_block")
3032 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3033 else if (Name == "prologue_end")
3034 Flags |= DWARF2_FLAG_PROLOGUE_END;
3035 else if (Name == "epilogue_begin")
3036 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3037 else if (Name == "is_stmt") {
3038 Loc = getTok().getLoc();
3039 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003040 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003041 return true;
3042 // The expression must be the constant 0 or 1.
3043 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3044 int Value = MCE->getValue();
3045 if (Value == 0)
3046 Flags &= ~DWARF2_FLAG_IS_STMT;
3047 else if (Value == 1)
3048 Flags |= DWARF2_FLAG_IS_STMT;
3049 else
3050 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003051 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003052 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3053 }
Craig Topperf15655b2013-04-22 04:22:40 +00003054 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00003055 Loc = getTok().getLoc();
3056 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003057 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003058 return true;
3059 // The expression must be a constant greater or equal to 0.
3060 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3061 int Value = MCE->getValue();
3062 if (Value < 0)
3063 return Error(Loc, "isa number less than zero");
3064 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00003065 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003066 return Error(Loc, "isa number not a constant value");
3067 }
Craig Topperf15655b2013-04-22 04:22:40 +00003068 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003069 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00003070 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00003071 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003072 return Error(Loc, "unknown sub-directive in '.loc' directive");
3073 }
3074
3075 if (getLexer().is(AsmToken::EndOfStatement))
3076 break;
3077 }
3078 }
3079
3080 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3081 Isa, Discriminator, StringRef());
3082
3083 return false;
3084}
3085
Jim Grosbach4b905842013-09-20 23:08:21 +00003086/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003087/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003088bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003089 return TokError("unsupported directive '.stabs'");
3090}
3091
Reid Kleckner2214ed82016-01-29 00:49:42 +00003092/// parseDirectiveCVFile
3093/// ::= .cv_file number filename
3094bool AsmParser::parseDirectiveCVFile() {
3095 SMLoc FileNumberLoc = getLexer().getLoc();
3096 if (getLexer().isNot(AsmToken::Integer))
3097 return TokError("expected file number in '.cv_file' directive");
3098
3099 int64_t FileNumber = getTok().getIntVal();
3100 Lex();
3101
3102 if (FileNumber < 1)
3103 return TokError("file number less than one");
3104
3105 if (getLexer().isNot(AsmToken::String))
3106 return TokError("unexpected token in '.cv_file' directive");
3107
3108 // Usually the directory and filename together, otherwise just the directory.
3109 // Allow the strings to have escaped octal character sequence.
3110 std::string Filename;
3111 if (parseEscapedString(Filename))
3112 return true;
3113 Lex();
3114
3115 if (getLexer().isNot(AsmToken::EndOfStatement))
3116 return TokError("unexpected token in '.cv_file' directive");
3117
3118 if (getStreamer().EmitCVFileDirective(FileNumber, Filename) == 0)
3119 Error(FileNumberLoc, "file number already allocated");
3120
3121 return false;
3122}
3123
3124/// parseDirectiveCVLoc
3125/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3126/// [is_stmt VALUE]
3127/// The first number is a file number, must have been previously assigned with
3128/// a .file directive, the second number is the line number and optionally the
3129/// third number is a column position (zero if not specified). The remaining
3130/// optional items are .loc sub-directives.
3131bool AsmParser::parseDirectiveCVLoc() {
3132 if (getLexer().isNot(AsmToken::Integer))
3133 return TokError("unexpected token in '.cv_loc' directive");
3134
3135 int64_t FunctionId = getTok().getIntVal();
3136 if (FunctionId < 0)
3137 return TokError("function id less than zero in '.cv_loc' directive");
3138 Lex();
3139
3140 int64_t FileNumber = getTok().getIntVal();
3141 if (FileNumber < 1)
3142 return TokError("file number less than one in '.cv_loc' directive");
3143 if (!getContext().isValidCVFileNumber(FileNumber))
3144 return TokError("unassigned file number in '.cv_loc' directive");
3145 Lex();
3146
3147 int64_t LineNumber = 0;
3148 if (getLexer().is(AsmToken::Integer)) {
3149 LineNumber = getTok().getIntVal();
3150 if (LineNumber < 0)
3151 return TokError("line number less than zero in '.cv_loc' directive");
3152 Lex();
3153 }
3154
3155 int64_t ColumnPos = 0;
3156 if (getLexer().is(AsmToken::Integer)) {
3157 ColumnPos = getTok().getIntVal();
3158 if (ColumnPos < 0)
3159 return TokError("column position less than zero in '.cv_loc' directive");
3160 Lex();
3161 }
3162
3163 bool PrologueEnd = false;
3164 uint64_t IsStmt = 0;
3165 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3166 StringRef Name;
3167 SMLoc Loc = getTok().getLoc();
3168 if (parseIdentifier(Name))
3169 return TokError("unexpected token in '.cv_loc' directive");
3170
3171 if (Name == "prologue_end")
3172 PrologueEnd = true;
3173 else if (Name == "is_stmt") {
3174 Loc = getTok().getLoc();
3175 const MCExpr *Value;
3176 if (parseExpression(Value))
3177 return true;
3178 // The expression must be the constant 0 or 1.
3179 IsStmt = ~0ULL;
3180 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3181 IsStmt = MCE->getValue();
3182
3183 if (IsStmt > 1)
3184 return Error(Loc, "is_stmt value not 0 or 1");
3185 } else {
3186 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3187 }
3188 }
3189
3190 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3191 ColumnPos, PrologueEnd, IsStmt, StringRef());
3192 return false;
3193}
3194
3195/// parseDirectiveCVLinetable
3196/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3197bool AsmParser::parseDirectiveCVLinetable() {
3198 int64_t FunctionId = getTok().getIntVal();
3199 if (FunctionId < 0)
3200 return TokError("function id less than zero in '.cv_linetable' directive");
3201 Lex();
3202
3203 if (Lexer.isNot(AsmToken::Comma))
3204 return TokError("unexpected token in '.cv_linetable' directive");
3205 Lex();
3206
3207 SMLoc Loc = getLexer().getLoc();
3208 StringRef FnStartName;
3209 if (parseIdentifier(FnStartName))
3210 return Error(Loc, "expected identifier in directive");
3211
3212 if (Lexer.isNot(AsmToken::Comma))
3213 return TokError("unexpected token in '.cv_linetable' directive");
3214 Lex();
3215
3216 Loc = getLexer().getLoc();
3217 StringRef FnEndName;
3218 if (parseIdentifier(FnEndName))
3219 return Error(Loc, "expected identifier in directive");
3220
3221 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3222 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3223
3224 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3225 return false;
3226}
3227
3228/// parseDirectiveCVStringTable
3229/// ::= .cv_stringtable
3230bool AsmParser::parseDirectiveCVStringTable() {
3231 getStreamer().EmitCVStringTableDirective();
3232 return false;
3233}
3234
3235/// parseDirectiveCVFileChecksums
3236/// ::= .cv_filechecksums
3237bool AsmParser::parseDirectiveCVFileChecksums() {
3238 getStreamer().EmitCVFileChecksumsDirective();
3239 return false;
3240}
3241
Jim Grosbach4b905842013-09-20 23:08:21 +00003242/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003243/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003244bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003245 StringRef Name;
3246 bool EH = false;
3247 bool Debug = false;
3248
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003249 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003250 return TokError("Expected an identifier");
3251
3252 if (Name == ".eh_frame")
3253 EH = true;
3254 else if (Name == ".debug_frame")
3255 Debug = true;
3256
3257 if (getLexer().is(AsmToken::Comma)) {
3258 Lex();
3259
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003260 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003261 return TokError("Expected an identifier");
3262
3263 if (Name == ".eh_frame")
3264 EH = true;
3265 else if (Name == ".debug_frame")
3266 Debug = true;
3267 }
3268
3269 getStreamer().EmitCFISections(EH, Debug);
3270 return false;
3271}
3272
Jim Grosbach4b905842013-09-20 23:08:21 +00003273/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003274/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003275bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003276 StringRef Simple;
3277 if (getLexer().isNot(AsmToken::EndOfStatement))
3278 if (parseIdentifier(Simple) || Simple != "simple")
3279 return TokError("unexpected token in .cfi_startproc directive");
3280
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003281 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003282 return false;
3283}
3284
Jim Grosbach4b905842013-09-20 23:08:21 +00003285/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003286/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003287bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003288 getStreamer().EmitCFIEndProc();
3289 return false;
3290}
3291
Jim Grosbach4b905842013-09-20 23:08:21 +00003292/// \brief parse register name or number.
3293bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003294 SMLoc DirectiveLoc) {
3295 unsigned RegNo;
3296
3297 if (getLexer().isNot(AsmToken::Integer)) {
3298 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3299 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003300 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003301 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003302 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003303
3304 return false;
3305}
3306
Jim Grosbach4b905842013-09-20 23:08:21 +00003307/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003308/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003309bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003310 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003311 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003312 return true;
3313
3314 if (getLexer().isNot(AsmToken::Comma))
3315 return TokError("unexpected token in directive");
3316 Lex();
3317
3318 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003319 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003320 return true;
3321
3322 getStreamer().EmitCFIDefCfa(Register, Offset);
3323 return false;
3324}
3325
Jim Grosbach4b905842013-09-20 23:08:21 +00003326/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003327/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003328bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003329 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003330 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003331 return true;
3332
3333 getStreamer().EmitCFIDefCfaOffset(Offset);
3334 return false;
3335}
3336
Jim Grosbach4b905842013-09-20 23:08:21 +00003337/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003338/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003339bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003340 int64_t Register1 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003341 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003342 return true;
3343
3344 if (getLexer().isNot(AsmToken::Comma))
3345 return TokError("unexpected token in directive");
3346 Lex();
3347
3348 int64_t Register2 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003349 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003350 return true;
3351
3352 getStreamer().EmitCFIRegister(Register1, Register2);
3353 return false;
3354}
3355
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003356/// parseDirectiveCFIWindowSave
3357/// ::= .cfi_window_save
3358bool AsmParser::parseDirectiveCFIWindowSave() {
3359 getStreamer().EmitCFIWindowSave();
3360 return false;
3361}
3362
Jim Grosbach4b905842013-09-20 23:08:21 +00003363/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003364/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003365bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003366 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003367 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003368 return true;
3369
3370 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3371 return false;
3372}
3373
Jim Grosbach4b905842013-09-20 23:08:21 +00003374/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003375/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003376bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003377 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003378 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003379 return true;
3380
3381 getStreamer().EmitCFIDefCfaRegister(Register);
3382 return false;
3383}
3384
Jim Grosbach4b905842013-09-20 23:08:21 +00003385/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003386/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003387bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003388 int64_t Register = 0;
3389 int64_t Offset = 0;
3390
Jim Grosbach4b905842013-09-20 23:08:21 +00003391 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003392 return true;
3393
3394 if (getLexer().isNot(AsmToken::Comma))
3395 return TokError("unexpected token in directive");
3396 Lex();
3397
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003398 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003399 return true;
3400
3401 getStreamer().EmitCFIOffset(Register, Offset);
3402 return false;
3403}
3404
Jim Grosbach4b905842013-09-20 23:08:21 +00003405/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003406/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003407bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003408 int64_t Register = 0;
3409
Jim Grosbach4b905842013-09-20 23:08:21 +00003410 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003411 return true;
3412
3413 if (getLexer().isNot(AsmToken::Comma))
3414 return TokError("unexpected token in directive");
3415 Lex();
3416
3417 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003418 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003419 return true;
3420
3421 getStreamer().EmitCFIRelOffset(Register, Offset);
3422 return false;
3423}
3424
3425static bool isValidEncoding(int64_t Encoding) {
3426 if (Encoding & ~0xff)
3427 return false;
3428
3429 if (Encoding == dwarf::DW_EH_PE_omit)
3430 return true;
3431
3432 const unsigned Format = Encoding & 0xf;
3433 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3434 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3435 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3436 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3437 return false;
3438
3439 const unsigned Application = Encoding & 0x70;
3440 if (Application != dwarf::DW_EH_PE_absptr &&
3441 Application != dwarf::DW_EH_PE_pcrel)
3442 return false;
3443
3444 return true;
3445}
3446
Jim Grosbach4b905842013-09-20 23:08:21 +00003447/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003448/// IsPersonality true for cfi_personality, false for cfi_lsda
3449/// ::= .cfi_personality encoding, [symbol_name]
3450/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003451bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003452 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003453 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003454 return true;
3455 if (Encoding == dwarf::DW_EH_PE_omit)
3456 return false;
3457
3458 if (!isValidEncoding(Encoding))
3459 return TokError("unsupported encoding.");
3460
3461 if (getLexer().isNot(AsmToken::Comma))
3462 return TokError("unexpected token in directive");
3463 Lex();
3464
3465 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003466 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003467 return TokError("expected identifier in directive");
3468
Jim Grosbach6f482002015-05-18 18:43:14 +00003469 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003470
3471 if (IsPersonality)
3472 getStreamer().EmitCFIPersonality(Sym, Encoding);
3473 else
3474 getStreamer().EmitCFILsda(Sym, Encoding);
3475 return false;
3476}
3477
Jim Grosbach4b905842013-09-20 23:08:21 +00003478/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003479/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003480bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003481 getStreamer().EmitCFIRememberState();
3482 return false;
3483}
3484
Jim Grosbach4b905842013-09-20 23:08:21 +00003485/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003486/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003487bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003488 getStreamer().EmitCFIRestoreState();
3489 return false;
3490}
3491
Jim Grosbach4b905842013-09-20 23:08:21 +00003492/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003493/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003494bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003495 int64_t Register = 0;
3496
Jim Grosbach4b905842013-09-20 23:08:21 +00003497 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003498 return true;
3499
3500 getStreamer().EmitCFISameValue(Register);
3501 return false;
3502}
3503
Jim Grosbach4b905842013-09-20 23:08:21 +00003504/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003505/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003506bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003507 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003508 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003509 return true;
3510
3511 getStreamer().EmitCFIRestore(Register);
3512 return false;
3513}
3514
Jim Grosbach4b905842013-09-20 23:08:21 +00003515/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003516/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003517bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003518 std::string Values;
3519 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003520 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003521 return true;
3522
3523 Values.push_back((uint8_t)CurrValue);
3524
3525 while (getLexer().is(AsmToken::Comma)) {
3526 Lex();
3527
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003528 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003529 return true;
3530
3531 Values.push_back((uint8_t)CurrValue);
3532 }
3533
3534 getStreamer().EmitCFIEscape(Values);
3535 return false;
3536}
3537
Jim Grosbach4b905842013-09-20 23:08:21 +00003538/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003539/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003540bool AsmParser::parseDirectiveCFISignalFrame() {
Eli Bendersky17233942013-01-15 22:59:42 +00003541 if (getLexer().isNot(AsmToken::EndOfStatement))
3542 return Error(getLexer().getLoc(),
3543 "unexpected token in '.cfi_signal_frame'");
3544
3545 getStreamer().EmitCFISignalFrame();
3546 return false;
3547}
3548
Jim Grosbach4b905842013-09-20 23:08:21 +00003549/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003550/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003551bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003552 int64_t Register = 0;
3553
Jim Grosbach4b905842013-09-20 23:08:21 +00003554 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003555 return true;
3556
3557 getStreamer().EmitCFIUndefined(Register);
3558 return false;
3559}
3560
Jim Grosbach4b905842013-09-20 23:08:21 +00003561/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003562/// ::= .macros_on
3563/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003564bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003565 if (getLexer().isNot(AsmToken::EndOfStatement))
3566 return Error(getLexer().getLoc(),
3567 "unexpected token in '" + Directive + "' directive");
3568
Jim Grosbach4b905842013-09-20 23:08:21 +00003569 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003570 return false;
3571}
3572
Jim Grosbach4b905842013-09-20 23:08:21 +00003573/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003574/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003575bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003576 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003577 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003578 return TokError("expected identifier in '.macro' directive");
3579
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003580 if (getLexer().is(AsmToken::Comma))
3581 Lex();
3582
Eli Bendersky17233942013-01-15 22:59:42 +00003583 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003584 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003585
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003586 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003587 return Error(Lexer.getLoc(),
3588 "Vararg parameter '" + Parameters.back().Name +
3589 "' should be last one in the list of parameters.");
3590
David Majnemer91fc4c22014-01-29 18:57:46 +00003591 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003592 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003593 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003594
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003595 if (Lexer.is(AsmToken::Colon)) {
3596 Lex(); // consume ':'
3597
3598 SMLoc QualLoc;
3599 StringRef Qualifier;
3600
3601 QualLoc = Lexer.getLoc();
3602 if (parseIdentifier(Qualifier))
3603 return Error(QualLoc, "missing parameter qualifier for "
3604 "'" + Parameter.Name + "' in macro '" + Name + "'");
3605
3606 if (Qualifier == "req")
3607 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003608 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003609 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003610 else
3611 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3612 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3613 }
3614
David Majnemer91fc4c22014-01-29 18:57:46 +00003615 if (getLexer().is(AsmToken::Equal)) {
3616 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003617
3618 SMLoc ParamLoc;
3619
3620 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003621 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003622 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003623
3624 if (Parameter.Required)
3625 Warning(ParamLoc, "pointless default value for required parameter "
3626 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003627 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003628
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003629 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003630
3631 if (getLexer().is(AsmToken::Comma))
3632 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003633 }
3634
3635 // Eat the end of statement.
3636 Lex();
3637
3638 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003639 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003640
3641 // Lex the macro definition.
3642 for (;;) {
3643 // Check whether we have reached the end of the file.
3644 if (getLexer().is(AsmToken::Eof))
3645 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3646
3647 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003648 if (getLexer().is(AsmToken::Identifier)) {
3649 if (getTok().getIdentifier() == ".endm" ||
3650 getTok().getIdentifier() == ".endmacro") {
3651 if (MacroDepth == 0) { // Outermost macro.
3652 EndToken = getTok();
3653 Lex();
3654 if (getLexer().isNot(AsmToken::EndOfStatement))
3655 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3656 "' directive");
3657 break;
3658 } else {
3659 // Otherwise we just found the end of an inner macro.
3660 --MacroDepth;
3661 }
3662 } else if (getTok().getIdentifier() == ".macro") {
3663 // We allow nested macros. Those aren't instantiated until the outermost
3664 // macro is expanded so just ignore them for now.
3665 ++MacroDepth;
3666 }
Eli Bendersky17233942013-01-15 22:59:42 +00003667 }
3668
3669 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003670 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003671 }
3672
Jim Grosbach4b905842013-09-20 23:08:21 +00003673 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003674 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3675 }
3676
3677 const char *BodyStart = StartToken.getLoc().getPointer();
3678 const char *BodyEnd = EndToken.getLoc().getPointer();
3679 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003680 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003681 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003682 return false;
3683}
3684
Jim Grosbach4b905842013-09-20 23:08:21 +00003685/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003686///
3687/// With the support added for named parameters there may be code out there that
3688/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003689/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003690/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003691/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003692/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3693/// warning that the positional parameter found in body which have no effect.
3694/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003695/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003696/// intended or change the macro to use the named parameters. It is possible
3697/// this warning will trigger when the none of the named parameters are used
3698/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003699void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003700 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003701 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003702 // If this macro is not defined with named parameters the warning we are
3703 // checking for here doesn't apply.
3704 unsigned NParameters = Parameters.size();
3705 if (NParameters == 0)
3706 return;
3707
3708 bool NamedParametersFound = false;
3709 bool PositionalParametersFound = false;
3710
3711 // Look at the body of the macro for use of both the named parameters and what
3712 // are likely to be positional parameters. This is what expandMacro() is
3713 // doing when it finds the parameters in the body.
3714 while (!Body.empty()) {
3715 // Scan for the next possible parameter.
3716 std::size_t End = Body.size(), Pos = 0;
3717 for (; Pos != End; ++Pos) {
3718 // Check for a substitution or escape.
3719 // This macro is defined with parameters, look for \foo, \bar, etc.
3720 if (Body[Pos] == '\\' && Pos + 1 != End)
3721 break;
3722
3723 // This macro should have parameters, but look for $0, $1, ..., $n too.
3724 if (Body[Pos] != '$' || Pos + 1 == End)
3725 continue;
3726 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00003727 if (Next == '$' || Next == 'n' ||
3728 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00003729 break;
3730 }
3731
3732 // Check if we reached the end.
3733 if (Pos == End)
3734 break;
3735
3736 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00003737 switch (Body[Pos + 1]) {
3738 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00003739 case '$':
3740 break;
3741
Jim Grosbach4b905842013-09-20 23:08:21 +00003742 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00003743 case 'n':
3744 PositionalParametersFound = true;
3745 break;
3746
Jim Grosbach4b905842013-09-20 23:08:21 +00003747 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00003748 default: {
3749 PositionalParametersFound = true;
3750 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00003751 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003752 }
3753 Pos += 2;
3754 } else {
3755 unsigned I = Pos + 1;
3756 while (isIdentifierChar(Body[I]) && I + 1 != End)
3757 ++I;
3758
Jim Grosbach4b905842013-09-20 23:08:21 +00003759 const char *Begin = Body.data() + Pos + 1;
3760 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00003761 unsigned Index = 0;
3762 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003763 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00003764 break;
3765
3766 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00003767 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3768 Pos += 3;
3769 else {
3770 Pos = I;
3771 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003772 } else {
3773 NamedParametersFound = true;
3774 Pos += 1 + Argument.size();
3775 }
3776 }
3777 // Update the scan point.
3778 Body = Body.substr(Pos);
3779 }
3780
3781 if (!NamedParametersFound && PositionalParametersFound)
3782 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3783 "used in macro body, possible positional parameter "
3784 "found in body which will have no effect");
3785}
3786
Nico Weber155dccd12014-07-24 17:08:39 +00003787/// parseDirectiveExitMacro
3788/// ::= .exitm
3789bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3790 if (getLexer().isNot(AsmToken::EndOfStatement))
3791 return TokError("unexpected token in '" + Directive + "' directive");
3792
3793 if (!isInsideMacroInstantiation())
3794 return TokError("unexpected '" + Directive + "' in file, "
3795 "no current macro definition");
3796
3797 // Exit all conditionals that are active in the current macro.
3798 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3799 TheCondState = TheCondStack.back();
3800 TheCondStack.pop_back();
3801 }
3802
3803 handleMacroExit();
3804 return false;
3805}
3806
Jim Grosbach4b905842013-09-20 23:08:21 +00003807/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003808/// ::= .endm
3809/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00003810bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003811 if (getLexer().isNot(AsmToken::EndOfStatement))
3812 return TokError("unexpected token in '" + Directive + "' directive");
3813
3814 // If we are inside a macro instantiation, terminate the current
3815 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00003816 if (isInsideMacroInstantiation()) {
3817 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00003818 return false;
3819 }
3820
3821 // Otherwise, this .endmacro is a stray entry in the file; well formed
3822 // .endmacro directives are handled during the macro definition parsing.
3823 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00003824 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00003825}
3826
Jim Grosbach4b905842013-09-20 23:08:21 +00003827/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003828/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00003829bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003830 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003831 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003832 return TokError("expected identifier in '.purgem' directive");
3833
3834 if (getLexer().isNot(AsmToken::EndOfStatement))
3835 return TokError("unexpected token in '.purgem' directive");
3836
Jim Grosbach4b905842013-09-20 23:08:21 +00003837 if (!lookupMacro(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003838 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3839
Jim Grosbach4b905842013-09-20 23:08:21 +00003840 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003841 return false;
3842}
Eli Benderskyf483ff92012-12-20 19:05:53 +00003843
Jim Grosbach4b905842013-09-20 23:08:21 +00003844/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00003845/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003846bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003847 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003848
3849 // Expect a single argument: an expression that evaluates to a constant
3850 // in the inclusive range 0-30.
3851 SMLoc ExprLoc = getLexer().getLoc();
3852 int64_t AlignSizePow2;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003853 if (parseAbsoluteExpression(AlignSizePow2))
Eli Benderskyf483ff92012-12-20 19:05:53 +00003854 return true;
3855 else if (getLexer().isNot(AsmToken::EndOfStatement))
3856 return TokError("unexpected token after expression in"
3857 " '.bundle_align_mode' directive");
3858 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3859 return Error(ExprLoc,
3860 "invalid bundle alignment size (expected between 0 and 30)");
3861
3862 Lex();
3863
3864 // Because of AlignSizePow2's verified range we can safely truncate it to
3865 // unsigned.
3866 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3867 return false;
3868}
3869
Jim Grosbach4b905842013-09-20 23:08:21 +00003870/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00003871/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00003872bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003873 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00003874 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00003875
Eli Bendersky802b6282013-01-07 21:51:08 +00003876 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3877 StringRef Option;
3878 SMLoc Loc = getTok().getLoc();
3879 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00003880 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00003881
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003882 if (parseIdentifier(Option))
Eli Bendersky802b6282013-01-07 21:51:08 +00003883 return Error(Loc, kInvalidOptionError);
3884
3885 if (Option != "align_to_end")
3886 return Error(Loc, kInvalidOptionError);
3887 else if (getLexer().isNot(AsmToken::EndOfStatement))
3888 return Error(Loc,
3889 "unexpected token after '.bundle_lock' directive option");
3890 AlignToEnd = true;
3891 }
3892
Eli Benderskyf483ff92012-12-20 19:05:53 +00003893 Lex();
3894
Eli Bendersky802b6282013-01-07 21:51:08 +00003895 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00003896 return false;
3897}
3898
Jim Grosbach4b905842013-09-20 23:08:21 +00003899/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00003900/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00003901bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003902 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003903
3904 if (getLexer().isNot(AsmToken::EndOfStatement))
3905 return TokError("unexpected token in '.bundle_unlock' directive");
3906 Lex();
3907
3908 getStreamer().EmitBundleUnlock();
3909 return false;
3910}
3911
Jim Grosbach4b905842013-09-20 23:08:21 +00003912/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00003913/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003914bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003915 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00003916
3917 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003918 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00003919 return true;
3920
3921 int64_t FillExpr = 0;
3922 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3923 if (getLexer().isNot(AsmToken::Comma))
3924 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3925 Lex();
3926
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003927 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00003928 return true;
3929
3930 if (getLexer().isNot(AsmToken::EndOfStatement))
3931 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3932 }
3933
3934 Lex();
3935
3936 if (NumBytes <= 0)
Jim Grosbach4b905842013-09-20 23:08:21 +00003937 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3938 "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003939
3940 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Rafael Espindola64e1af82013-07-02 15:49:13 +00003941 getStreamer().EmitFill(NumBytes, FillExpr);
Eli Bendersky17233942013-01-15 22:59:42 +00003942
3943 return false;
3944}
3945
Jim Grosbach4b905842013-09-20 23:08:21 +00003946/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003947/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003948bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003949 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00003950 const MCExpr *Value;
3951
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003952 for (;;) {
3953 if (parseExpression(Value))
3954 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003955
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003956 if (Signed)
3957 getStreamer().EmitSLEB128Value(Value);
3958 else
3959 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00003960
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003961 if (getLexer().is(AsmToken::EndOfStatement))
3962 break;
3963
3964 if (getLexer().isNot(AsmToken::Comma))
3965 return TokError("unexpected token in directive");
3966 Lex();
3967 }
Eli Bendersky17233942013-01-15 22:59:42 +00003968
3969 return false;
3970}
3971
Jim Grosbach4b905842013-09-20 23:08:21 +00003972/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00003973/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003974bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003975 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara5508c82009-06-30 00:33:19 +00003976 for (;;) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00003977 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003978 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00003979
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003980 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003981 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003982
Jim Grosbach6f482002015-05-18 18:43:14 +00003983 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00003984
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003985 // Assembler local symbols don't make any sense here. Complain loudly.
3986 if (Sym->isTemporary())
3987 return Error(Loc, "non-local symbol required in directive");
3988
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00003989 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3990 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00003991
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003992 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00003993 break;
3994
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003995 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara5508c82009-06-30 00:33:19 +00003996 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00003997 Lex();
Daniel Dunbara5508c82009-06-30 00:33:19 +00003998 }
3999 }
4000
Sean Callanan686ed8d2010-01-19 20:22:31 +00004001 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00004002 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004003}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004004
Jim Grosbach4b905842013-09-20 23:08:21 +00004005/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004006/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004007bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004008 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00004009
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004010 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004011 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004012 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004013 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004014
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004015 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004016 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004017
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004018 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004019 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004020 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004021
4022 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004023 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004024 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004025 return true;
4026
4027 int64_t Pow2Alignment = 0;
4028 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004029 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004030 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004031 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004032 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004033 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004034
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004035 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4036 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004037 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4038
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004039 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004040 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4041 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004042 if (!isPowerOf2_64(Pow2Alignment))
4043 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4044 Pow2Alignment = Log2_64(Pow2Alignment);
4045 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004046 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004047
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004048 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00004049 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004050
Sean Callanan686ed8d2010-01-19 20:22:31 +00004051 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004052
Chris Lattner28ad7542009-07-09 17:25:12 +00004053 // NOTE: a size of zero for a .comm should create a undefined symbol
4054 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004055 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004056 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004057 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004058
Eric Christopherbc818852010-05-14 01:38:54 +00004059 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004060 // may internally end up wanting an alignment in bytes.
4061 // FIXME: Diagnose overflow.
4062 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004063 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004064 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004065
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004066 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004067 return Error(IDLoc, "invalid symbol redefinition");
4068
Chris Lattner28ad7542009-07-09 17:25:12 +00004069 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004070 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004071 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004072 return false;
4073 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004074
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004075 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004076 return false;
4077}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004078
Jim Grosbach4b905842013-09-20 23:08:21 +00004079/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004080/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004081bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004082 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004083 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004084
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004085 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004086 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby56523ce2009-07-13 23:15:14 +00004087 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004088
Sean Callanan686ed8d2010-01-19 20:22:31 +00004089 Lex();
Kevin Enderby56523ce2009-07-13 23:15:14 +00004090
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004091 if (Str.empty())
4092 Error(Loc, ".abort detected. Assembly stopping.");
4093 else
4094 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004095 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004096
4097 return false;
4098}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004099
Jim Grosbach4b905842013-09-20 23:08:21 +00004100/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004101/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004102bool AsmParser::parseDirectiveInclude() {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004103 if (getLexer().isNot(AsmToken::String))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004104 return TokError("expected string in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004105
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004106 // Allow the strings to have escaped octal character sequence.
4107 std::string Filename;
4108 if (parseEscapedString(Filename))
4109 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004110 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00004111 Lex();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004112
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004113 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004114 return TokError("unexpected token in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004115
Chris Lattner693fbb82009-07-16 06:14:39 +00004116 // Attempt to switch the lexer to the included file before consuming the end
4117 // of statement to avoid losing it when we switch.
Jim Grosbach4b905842013-09-20 23:08:21 +00004118 if (enterIncludeFile(Filename)) {
Daniel Dunbard8a18452010-07-18 18:31:45 +00004119 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner693fbb82009-07-16 06:14:39 +00004120 return true;
4121 }
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004122
4123 return false;
4124}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004125
Jim Grosbach4b905842013-09-20 23:08:21 +00004126/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00004127/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004128bool AsmParser::parseDirectiveIncbin() {
Kevin Enderby109f25c2011-12-14 21:47:48 +00004129 if (getLexer().isNot(AsmToken::String))
4130 return TokError("expected string in '.incbin' directive");
4131
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004132 // Allow the strings to have escaped octal character sequence.
4133 std::string Filename;
4134 if (parseEscapedString(Filename))
4135 return true;
Kevin Enderby109f25c2011-12-14 21:47:48 +00004136 SMLoc IncbinLoc = getLexer().getLoc();
4137 Lex();
4138
4139 if (getLexer().isNot(AsmToken::EndOfStatement))
4140 return TokError("unexpected token in '.incbin' directive");
4141
Kevin Enderby109f25c2011-12-14 21:47:48 +00004142 // Attempt to process the included file.
Jim Grosbach4b905842013-09-20 23:08:21 +00004143 if (processIncbinFile(Filename)) {
Kevin Enderby109f25c2011-12-14 21:47:48 +00004144 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4145 return true;
4146 }
4147
4148 return false;
4149}
4150
Jim Grosbach4b905842013-09-20 23:08:21 +00004151/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004152/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4153bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004154 TheCondStack.push_back(TheCondState);
4155 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004156 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004157 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004158 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004159 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004160 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004161 return true;
4162
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004163 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004164 return TokError("unexpected token in '.if' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004165
Sean Callanan686ed8d2010-01-19 20:22:31 +00004166 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004167
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004168 switch (DirKind) {
4169 default:
4170 llvm_unreachable("unsupported directive");
4171 case DK_IF:
4172 case DK_IFNE:
4173 break;
4174 case DK_IFEQ:
4175 ExprValue = ExprValue == 0;
4176 break;
4177 case DK_IFGE:
4178 ExprValue = ExprValue >= 0;
4179 break;
4180 case DK_IFGT:
4181 ExprValue = ExprValue > 0;
4182 break;
4183 case DK_IFLE:
4184 ExprValue = ExprValue <= 0;
4185 break;
4186 case DK_IFLT:
4187 ExprValue = ExprValue < 0;
4188 break;
4189 }
4190
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004191 TheCondState.CondMet = ExprValue;
4192 TheCondState.Ignore = !TheCondState.CondMet;
4193 }
4194
4195 return false;
4196}
4197
Jim Grosbach4b905842013-09-20 23:08:21 +00004198/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004199/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004200bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004201 TheCondStack.push_back(TheCondState);
4202 TheCondState.TheCond = AsmCond::IfCond;
4203
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004204 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004205 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004206 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004207 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004208
4209 if (getLexer().isNot(AsmToken::EndOfStatement))
4210 return TokError("unexpected token in '.ifb' directive");
4211
4212 Lex();
4213
4214 TheCondState.CondMet = ExpectBlank == Str.empty();
4215 TheCondState.Ignore = !TheCondState.CondMet;
4216 }
4217
4218 return false;
4219}
4220
Jim Grosbach4b905842013-09-20 23:08:21 +00004221/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004222/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004223/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004224bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004225 TheCondStack.push_back(TheCondState);
4226 TheCondState.TheCond = AsmCond::IfCond;
4227
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004228 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004229 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004230 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004231 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004232
4233 if (getLexer().isNot(AsmToken::Comma))
4234 return TokError("unexpected token in '.ifc' directive");
4235
4236 Lex();
4237
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004238 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004239
4240 if (getLexer().isNot(AsmToken::EndOfStatement))
4241 return TokError("unexpected token in '.ifc' directive");
4242
4243 Lex();
4244
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004245 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004246 TheCondState.Ignore = !TheCondState.CondMet;
4247 }
4248
4249 return false;
4250}
4251
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004252/// parseDirectiveIfeqs
4253/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004254bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004255 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004256 if (ExpectEqual)
4257 TokError("expected string parameter for '.ifeqs' directive");
4258 else
4259 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004260 eatToEndOfStatement();
4261 return true;
4262 }
4263
4264 StringRef String1 = getTok().getStringContents();
4265 Lex();
4266
4267 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004268 if (ExpectEqual)
4269 TokError("expected comma after first string for '.ifeqs' directive");
4270 else
4271 TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004272 eatToEndOfStatement();
4273 return true;
4274 }
4275
4276 Lex();
4277
4278 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004279 if (ExpectEqual)
4280 TokError("expected string parameter for '.ifeqs' directive");
4281 else
4282 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004283 eatToEndOfStatement();
4284 return true;
4285 }
4286
4287 StringRef String2 = getTok().getStringContents();
4288 Lex();
4289
4290 TheCondStack.push_back(TheCondState);
4291 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004292 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004293 TheCondState.Ignore = !TheCondState.CondMet;
4294
4295 return false;
4296}
4297
Jim Grosbach4b905842013-09-20 23:08:21 +00004298/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004299/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004300bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004301 StringRef Name;
4302 TheCondStack.push_back(TheCondState);
4303 TheCondState.TheCond = AsmCond::IfCond;
4304
4305 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004306 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004307 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004308 if (parseIdentifier(Name))
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004309 return TokError("expected identifier after '.ifdef'");
4310
4311 Lex();
4312
Jim Grosbach6f482002015-05-18 18:43:14 +00004313 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004314
4315 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004316 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004317 else
Craig Topper353eda42014-04-24 06:44:33 +00004318 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004319 TheCondState.Ignore = !TheCondState.CondMet;
4320 }
4321
4322 return false;
4323}
4324
Jim Grosbach4b905842013-09-20 23:08:21 +00004325/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004326/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004327bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004328 if (TheCondState.TheCond != AsmCond::IfCond &&
4329 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004330 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4331 " an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004332 TheCondState.TheCond = AsmCond::ElseIfCond;
4333
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004334 bool LastIgnoreState = false;
4335 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004336 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004337 if (LastIgnoreState || TheCondState.CondMet) {
4338 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004339 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004340 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004341 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004342 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004343 return true;
4344
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004345 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004346 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004347
Sean Callanan686ed8d2010-01-19 20:22:31 +00004348 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004349 TheCondState.CondMet = ExprValue;
4350 TheCondState.Ignore = !TheCondState.CondMet;
4351 }
4352
4353 return false;
4354}
4355
Jim Grosbach4b905842013-09-20 23:08:21 +00004356/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004357/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004358bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004359 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004360 return TokError("unexpected token in '.else' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004361
Sean Callanan686ed8d2010-01-19 20:22:31 +00004362 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004363
4364 if (TheCondState.TheCond != AsmCond::IfCond &&
4365 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004366 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4367 ".elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004368 TheCondState.TheCond = AsmCond::ElseCond;
4369 bool LastIgnoreState = false;
4370 if (!TheCondStack.empty())
4371 LastIgnoreState = TheCondStack.back().Ignore;
4372 if (LastIgnoreState || TheCondState.CondMet)
4373 TheCondState.Ignore = true;
4374 else
4375 TheCondState.Ignore = false;
4376
4377 return false;
4378}
4379
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004380/// parseDirectiveEnd
4381/// ::= .end
4382bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4383 if (getLexer().isNot(AsmToken::EndOfStatement))
4384 return TokError("unexpected token in '.end' directive");
4385
4386 Lex();
4387
4388 while (Lexer.isNot(AsmToken::Eof))
4389 Lex();
4390
4391 return false;
4392}
4393
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004394/// parseDirectiveError
4395/// ::= .err
4396/// ::= .error [string]
4397bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4398 if (!TheCondStack.empty()) {
4399 if (TheCondStack.back().Ignore) {
4400 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004401 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004402 }
4403 }
4404
4405 if (!WithMessage)
4406 return Error(L, ".err encountered");
4407
4408 StringRef Message = ".error directive invoked in source file";
4409 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4410 if (Lexer.isNot(AsmToken::String)) {
4411 TokError(".error argument must be a string");
4412 eatToEndOfStatement();
4413 return true;
4414 }
4415
4416 Message = getTok().getStringContents();
4417 Lex();
4418 }
4419
4420 Error(L, Message);
4421 return true;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004422}
4423
Nico Weber404012b2014-07-24 16:26:06 +00004424/// parseDirectiveWarning
4425/// ::= .warning [string]
4426bool AsmParser::parseDirectiveWarning(SMLoc L) {
4427 if (!TheCondStack.empty()) {
4428 if (TheCondStack.back().Ignore) {
4429 eatToEndOfStatement();
4430 return false;
4431 }
4432 }
4433
4434 StringRef Message = ".warning directive invoked in source file";
4435 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4436 if (Lexer.isNot(AsmToken::String)) {
4437 TokError(".warning argument must be a string");
4438 eatToEndOfStatement();
4439 return true;
4440 }
4441
4442 Message = getTok().getStringContents();
4443 Lex();
4444 }
4445
4446 Warning(L, Message);
4447 return false;
4448}
4449
Jim Grosbach4b905842013-09-20 23:08:21 +00004450/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004451/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004452bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004453 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004454 return TokError("unexpected token in '.endif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004455
Sean Callanan686ed8d2010-01-19 20:22:31 +00004456 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004457
Jim Grosbach4b905842013-09-20 23:08:21 +00004458 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004459 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4460 ".else");
4461 if (!TheCondStack.empty()) {
4462 TheCondState = TheCondStack.back();
4463 TheCondStack.pop_back();
4464 }
4465
4466 return false;
4467}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004468
Eli Bendersky17233942013-01-15 22:59:42 +00004469void AsmParser::initializeDirectiveKindMap() {
4470 DirectiveKindMap[".set"] = DK_SET;
4471 DirectiveKindMap[".equ"] = DK_EQU;
4472 DirectiveKindMap[".equiv"] = DK_EQUIV;
4473 DirectiveKindMap[".ascii"] = DK_ASCII;
4474 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4475 DirectiveKindMap[".string"] = DK_STRING;
4476 DirectiveKindMap[".byte"] = DK_BYTE;
4477 DirectiveKindMap[".short"] = DK_SHORT;
4478 DirectiveKindMap[".value"] = DK_VALUE;
4479 DirectiveKindMap[".2byte"] = DK_2BYTE;
4480 DirectiveKindMap[".long"] = DK_LONG;
4481 DirectiveKindMap[".int"] = DK_INT;
4482 DirectiveKindMap[".4byte"] = DK_4BYTE;
4483 DirectiveKindMap[".quad"] = DK_QUAD;
4484 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004485 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004486 DirectiveKindMap[".single"] = DK_SINGLE;
4487 DirectiveKindMap[".float"] = DK_FLOAT;
4488 DirectiveKindMap[".double"] = DK_DOUBLE;
4489 DirectiveKindMap[".align"] = DK_ALIGN;
4490 DirectiveKindMap[".align32"] = DK_ALIGN32;
4491 DirectiveKindMap[".balign"] = DK_BALIGN;
4492 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4493 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4494 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4495 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4496 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4497 DirectiveKindMap[".org"] = DK_ORG;
4498 DirectiveKindMap[".fill"] = DK_FILL;
4499 DirectiveKindMap[".zero"] = DK_ZERO;
4500 DirectiveKindMap[".extern"] = DK_EXTERN;
4501 DirectiveKindMap[".globl"] = DK_GLOBL;
4502 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004503 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4504 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4505 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4506 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4507 DirectiveKindMap[".reference"] = DK_REFERENCE;
4508 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4509 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4510 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4511 DirectiveKindMap[".comm"] = DK_COMM;
4512 DirectiveKindMap[".common"] = DK_COMMON;
4513 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4514 DirectiveKindMap[".abort"] = DK_ABORT;
4515 DirectiveKindMap[".include"] = DK_INCLUDE;
4516 DirectiveKindMap[".incbin"] = DK_INCBIN;
4517 DirectiveKindMap[".code16"] = DK_CODE16;
4518 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4519 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004520 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004521 DirectiveKindMap[".irp"] = DK_IRP;
4522 DirectiveKindMap[".irpc"] = DK_IRPC;
4523 DirectiveKindMap[".endr"] = DK_ENDR;
4524 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4525 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4526 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4527 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004528 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4529 DirectiveKindMap[".ifge"] = DK_IFGE;
4530 DirectiveKindMap[".ifgt"] = DK_IFGT;
4531 DirectiveKindMap[".ifle"] = DK_IFLE;
4532 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004533 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004534 DirectiveKindMap[".ifb"] = DK_IFB;
4535 DirectiveKindMap[".ifnb"] = DK_IFNB;
4536 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004537 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004538 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004539 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004540 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4541 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4542 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4543 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4544 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004545 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004546 DirectiveKindMap[".endif"] = DK_ENDIF;
4547 DirectiveKindMap[".skip"] = DK_SKIP;
4548 DirectiveKindMap[".space"] = DK_SPACE;
4549 DirectiveKindMap[".file"] = DK_FILE;
4550 DirectiveKindMap[".line"] = DK_LINE;
4551 DirectiveKindMap[".loc"] = DK_LOC;
4552 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004553 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4554 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4555 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
4556 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4557 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004558 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4559 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4560 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4561 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4562 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4563 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4564 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4565 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4566 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4567 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4568 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4569 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4570 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4571 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4572 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4573 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4574 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4575 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4576 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4577 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4578 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004579 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004580 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4581 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4582 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004583 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004584 DirectiveKindMap[".endm"] = DK_ENDM;
4585 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4586 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004587 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004588 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004589 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004590 DirectiveKindMap[".reloc"] = DK_RELOC;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004591}
4592
Jim Grosbach4b905842013-09-20 23:08:21 +00004593MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004594 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004595
Rafael Espindola34b9c512012-06-03 23:57:14 +00004596 unsigned NestLevel = 0;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004597 for (;;) {
4598 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004599 if (getLexer().is(AsmToken::Eof)) {
4600 Error(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004601 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004602 }
4603
Rafael Espindola34b9c512012-06-03 23:57:14 +00004604 if (Lexer.is(AsmToken::Identifier) &&
4605 (getTok().getIdentifier() == ".rept")) {
4606 ++NestLevel;
4607 }
4608
4609 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004610 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004611 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004612 EndToken = getTok();
4613 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004614 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4615 TokError("unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004616 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004617 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004618 break;
4619 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004620 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004621 }
4622
Rafael Espindola34b9c512012-06-03 23:57:14 +00004623 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004624 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004625 }
4626
4627 const char *BodyStart = StartToken.getLoc().getPointer();
4628 const char *BodyEnd = EndToken.getLoc().getPointer();
4629 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4630
Rafael Espindola34b9c512012-06-03 23:57:14 +00004631 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004632 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004633 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004634}
4635
Jim Grosbach4b905842013-09-20 23:08:21 +00004636void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004637 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004638 OS << ".endr\n";
4639
Rafael Espindola3560ff22014-08-27 20:03:13 +00004640 std::unique_ptr<MemoryBuffer> Instantiation =
4641 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004642
Rafael Espindola34b9c512012-06-03 23:57:14 +00004643 // Create the macro instantiation object and add to the current macro
4644 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004645 MacroInstantiation *MI = new MacroInstantiation(
4646 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004647 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004648
Rafael Espindola34b9c512012-06-03 23:57:14 +00004649 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004650 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004651 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004652 Lex();
4653}
4654
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004655/// parseDirectiveRept
4656/// ::= .rep | .rept count
4657bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004658 const MCExpr *CountExpr;
4659 SMLoc CountLoc = getTok().getLoc();
4660 if (parseExpression(CountExpr))
4661 return true;
4662
Rafael Espindola34b9c512012-06-03 23:57:14 +00004663 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004664 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004665 eatToEndOfStatement();
4666 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4667 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004668
4669 if (Count < 0)
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004670 return Error(CountLoc, "Count is negative");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004671
4672 if (Lexer.isNot(AsmToken::EndOfStatement))
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004673 return TokError("unexpected token in '" + Dir + "' directive");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004674
4675 // Eat the end of statement.
4676 Lex();
4677
4678 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004679 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00004680 if (!M)
4681 return true;
4682
4683 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4684 // to hold the macro body with substitutions.
4685 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004686 raw_svector_ostream OS(Buf);
4687 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004688 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4689 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004690 return true;
4691 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004692 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004693
4694 return false;
4695}
4696
Jim Grosbach4b905842013-09-20 23:08:21 +00004697/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004698/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004699bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004700 MCAsmMacroParameter Parameter;
Rafael Espindola768b41c2012-06-15 14:02:34 +00004701
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004702 if (parseIdentifier(Parameter.Name))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004703 return TokError("expected identifier in '.irp' directive");
4704
Rafael Espindola768b41c2012-06-15 14:02:34 +00004705 if (Lexer.isNot(AsmToken::Comma))
4706 return TokError("expected comma in '.irp' directive");
4707
4708 Lex();
4709
Eli Bendersky38274122013-01-14 23:22:36 +00004710 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004711 if (parseMacroArguments(nullptr, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004712 return true;
4713
4714 // Eat the end of statement.
4715 Lex();
4716
4717 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004718 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004719 if (!M)
4720 return true;
4721
4722 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4723 // to hold the macro body with substitutions.
4724 SmallString<256> Buf;
4725 raw_svector_ostream OS(Buf);
4726
Craig Topper84008482015-10-10 05:38:14 +00004727 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004728 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4729 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00004730 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004731 return true;
4732 }
4733
Jim Grosbach4b905842013-09-20 23:08:21 +00004734 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004735
4736 return false;
4737}
4738
Jim Grosbach4b905842013-09-20 23:08:21 +00004739/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004740/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004741bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004742 MCAsmMacroParameter Parameter;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004743
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004744 if (parseIdentifier(Parameter.Name))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004745 return TokError("expected identifier in '.irpc' directive");
4746
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004747 if (Lexer.isNot(AsmToken::Comma))
4748 return TokError("expected comma in '.irpc' directive");
4749
4750 Lex();
4751
Eli Bendersky38274122013-01-14 23:22:36 +00004752 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004753 if (parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004754 return true;
4755
4756 if (A.size() != 1 || A.front().size() != 1)
4757 return TokError("unexpected token in '.irpc' directive");
4758
4759 // Eat the end of statement.
4760 Lex();
4761
4762 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004763 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004764 if (!M)
4765 return true;
4766
4767 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4768 // to hold the macro body with substitutions.
4769 SmallString<256> Buf;
4770 raw_svector_ostream OS(Buf);
4771
4772 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004773 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00004774 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004775 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004776
Toma Tabacu217116e2015-04-27 10:50:29 +00004777 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4778 // This is undocumented, but GAS seems to support it.
4779 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004780 return true;
4781 }
4782
Jim Grosbach4b905842013-09-20 23:08:21 +00004783 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004784
4785 return false;
4786}
4787
Jim Grosbach4b905842013-09-20 23:08:21 +00004788bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004789 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00004790 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004791
4792 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00004793 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004794 assert(getLexer().is(AsmToken::EndOfStatement));
4795
Jim Grosbach4b905842013-09-20 23:08:21 +00004796 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004797 return false;
4798}
Rafael Espindola12d73d12010-09-11 16:45:15 +00004799
Jim Grosbach4b905842013-09-20 23:08:21 +00004800bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00004801 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004802 const MCExpr *Value;
4803 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004804 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004805 return true;
4806 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4807 if (!MCE)
4808 return Error(ExprLoc, "unexpected expression in _emit");
4809 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00004810 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004811 return Error(ExprLoc, "literal value out of range for directive");
4812
Craig Topper7d5b2312015-10-10 05:25:02 +00004813 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00004814 return false;
4815}
4816
Jim Grosbach4b905842013-09-20 23:08:21 +00004817bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00004818 const MCExpr *Value;
4819 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004820 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00004821 return true;
4822 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4823 if (!MCE)
4824 return Error(ExprLoc, "unexpected expression in align");
4825 uint64_t IntValue = MCE->getValue();
4826 if (!isPowerOf2_64(IntValue))
4827 return Error(ExprLoc, "literal value not a power of two greater then zero");
4828
Craig Topper7d5b2312015-10-10 05:25:02 +00004829 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00004830 return false;
4831}
4832
Chad Rosierf43fcf52013-02-13 21:27:17 +00004833// We are comparing pointers, but the pointers are relative to a single string.
4834// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00004835static int rewritesSort(const AsmRewrite *AsmRewriteA,
4836 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00004837 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4838 return -1;
4839 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4840 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004841
Chad Rosierfce4fab2013-04-08 17:43:47 +00004842 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4843 // rewrite to the same location. Make sure the SizeDirective rewrite is
4844 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4845 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00004846 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4847 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004848 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00004849
Jim Grosbach4b905842013-09-20 23:08:21 +00004850 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4851 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004852 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00004853 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00004854}
4855
Jim Grosbach4b905842013-09-20 23:08:21 +00004856bool AsmParser::parseMSInlineAsm(
4857 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4858 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4859 SmallVectorImpl<std::string> &Constraints,
4860 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4861 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00004862 SmallVector<void *, 4> InputDecls;
4863 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00004864 SmallVector<bool, 4> InputDeclsAddressOf;
4865 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00004866 SmallVector<std::string, 4> InputConstraints;
4867 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00004868 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00004869
Benjamin Kramer1a136112013-02-15 20:37:21 +00004870 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00004871
4872 // Prime the lexer.
4873 Lex();
4874
4875 // While we have input, parse each statement.
4876 unsigned InputIdx = 0;
4877 unsigned OutputIdx = 0;
4878 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004879 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004880 if (parseStatement(Info, &SI))
Chad Rosierf1f6a722012-10-19 22:57:33 +00004881 return true;
Chad Rosier8bce6642012-10-18 15:49:34 +00004882
Chad Rosier149e8e02012-12-12 22:45:52 +00004883 if (Info.ParseError)
4884 return true;
4885
Benjamin Kramer1a136112013-02-15 20:37:21 +00004886 if (Info.Opcode == ~0U)
4887 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004888
Benjamin Kramer1a136112013-02-15 20:37:21 +00004889 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00004890
Benjamin Kramer1a136112013-02-15 20:37:21 +00004891 // Build the list of clobbers, outputs and inputs.
4892 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00004893 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004894
Benjamin Kramer1a136112013-02-15 20:37:21 +00004895 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00004896 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00004897 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004898
Benjamin Kramer1a136112013-02-15 20:37:21 +00004899 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00004900 if (Operand.isReg() && !Operand.needAddressOf() &&
4901 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00004902 unsigned NumDefs = Desc.getNumDefs();
4903 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00004904 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4905 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004906 continue;
4907 }
4908
4909 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00004910 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00004911 if (SymName.empty())
4912 continue;
4913
David Blaikie960ea3f2014-06-08 16:18:35 +00004914 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00004915 if (!OpDecl)
4916 continue;
4917
4918 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00004919 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004920 if (isOutput) {
4921 ++InputIdx;
4922 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004923 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00004924 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00004925 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004926 } else {
4927 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004928 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4929 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00004930 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00004931 }
Chad Rosier8bce6642012-10-18 15:49:34 +00004932 }
Reid Kleckneree088972013-12-10 18:27:32 +00004933
4934 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00004935 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
4936 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00004937 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00004938 }
4939
4940 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00004941 NumOutputs = OutputDecls.size();
4942 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00004943
4944 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00004945 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4946 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4947 ClobberRegs.end());
4948 Clobbers.assign(ClobberRegs.size(), std::string());
4949 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4950 raw_string_ostream OS(Clobbers[I]);
4951 IP->printRegName(OS, ClobberRegs[I]);
4952 }
Chad Rosier8bce6642012-10-18 15:49:34 +00004953
4954 // Merge the various outputs and inputs. Output are expected first.
4955 if (NumOutputs || NumInputs) {
4956 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00004957 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00004958 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00004959 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00004960 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00004961 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004962 }
4963 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00004964 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00004965 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004966 }
4967 }
4968
4969 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00004970 std::string AsmStringIR;
4971 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00004972 StringRef ASMString =
4973 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4974 const char *AsmStart = ASMString.begin();
4975 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00004976 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00004977 for (const AsmRewrite &AR : AsmStrRewrites) {
4978 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00004979 if (Kind == AOK_Delete)
4980 continue;
4981
David Majnemer8114c1a2014-06-23 02:17:16 +00004982 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00004983 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00004984
Chad Rosier120eefd2013-03-19 17:32:17 +00004985 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00004986 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00004987 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00004988
Chad Rosier37e755c2012-10-23 17:43:43 +00004989 // Skip the original expression.
4990 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00004991 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00004992 continue;
4993 }
4994
Chad Rosierff10ed12013-04-12 16:26:42 +00004995 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00004996 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00004997 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004998 default:
4999 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005000 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005001 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005002 break;
5003 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005004 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005005 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005006 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005007 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005008 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005009 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005010 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005011 break;
5012 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005013 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005014 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005015 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005016 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005017 default: break;
5018 case 8: OS << "byte ptr "; break;
5019 case 16: OS << "word ptr "; break;
5020 case 32: OS << "dword ptr "; break;
5021 case 64: OS << "qword ptr "; break;
5022 case 80: OS << "xword ptr "; break;
5023 case 128: OS << "xmmword ptr "; break;
5024 case 256: OS << "ymmword ptr "; break;
5025 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005026 break;
5027 case AOK_Emit:
5028 OS << ".byte";
5029 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005030 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005031 // MS alignment directives are measured in bytes. If the native assembler
5032 // measures alignment in bytes, we can pass it straight through.
5033 OS << ".align";
5034 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5035 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005036
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005037 // Alignment is in log2 form, so print that instead and skip the original
5038 // immediate.
5039 unsigned Val = AR.Val;
5040 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005041 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005042 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5043 break;
5044 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005045 case AOK_EVEN:
5046 OS << ".even";
5047 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005048 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005049 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005050 OS.flush();
5051 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005052 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005053 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005054 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005055 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005056
Chad Rosier8bce6642012-10-18 15:49:34 +00005057 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005058 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005059 }
5060
5061 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005062 if (AsmStart != AsmEnd)
5063 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005064
5065 AsmString = OS.str();
5066 return false;
5067}
5068
Pete Cooper80d21cb2015-06-22 19:35:57 +00005069namespace llvm {
5070namespace MCParserUtils {
5071
5072/// Returns whether the given symbol is used anywhere in the given expression,
5073/// or subexpressions.
5074static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5075 switch (Value->getKind()) {
5076 case MCExpr::Binary: {
5077 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5078 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5079 isSymbolUsedInExpression(Sym, BE->getRHS());
5080 }
5081 case MCExpr::Target:
5082 case MCExpr::Constant:
5083 return false;
5084 case MCExpr::SymbolRef: {
5085 const MCSymbol &S =
5086 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5087 if (S.isVariable())
5088 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5089 return &S == Sym;
5090 }
5091 case MCExpr::Unary:
5092 return isSymbolUsedInExpression(
5093 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5094 }
5095
5096 llvm_unreachable("Unknown expr kind!");
5097}
5098
5099bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5100 MCAsmParser &Parser, MCSymbol *&Sym,
5101 const MCExpr *&Value) {
5102 MCAsmLexer &Lexer = Parser.getLexer();
5103
5104 // FIXME: Use better location, we should use proper tokens.
5105 SMLoc EqualLoc = Lexer.getLoc();
5106
5107 if (Parser.parseExpression(Value)) {
5108 Parser.TokError("missing expression");
5109 Parser.eatToEndOfStatement();
5110 return true;
5111 }
5112
5113 // Note: we don't count b as used in "a = b". This is to allow
5114 // a = b
5115 // b = c
5116
5117 if (Lexer.isNot(AsmToken::EndOfStatement))
5118 return Parser.TokError("unexpected token in assignment");
5119
5120 // Eat the end of statement marker.
5121 Parser.Lex();
5122
5123 // Validate that the LHS is allowed to be a variable (either it has not been
5124 // used as a symbol, or it is an absolute symbol).
5125 Sym = Parser.getContext().lookupSymbol(Name);
5126 if (Sym) {
5127 // Diagnose assignment to a label.
5128 //
5129 // FIXME: Diagnostics. Note the location of the definition as a label.
5130 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5131 if (isSymbolUsedInExpression(Sym, Value))
5132 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005133 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5134 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005135 ; // Allow redefinitions of undefined symbols only used in directives.
5136 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5137 ; // Allow redefinitions of variables that haven't yet been used.
5138 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5139 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5140 else if (!Sym->isVariable())
5141 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5142 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5143 return Parser.Error(EqualLoc,
5144 "invalid reassignment of non-absolute variable '" +
5145 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005146 } else if (Name == ".") {
Rafael Espindola7ae65d82015-11-04 23:59:18 +00005147 Parser.getStreamer().emitValueToOffset(Value, 0);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005148 return false;
5149 } else
5150 Sym = Parser.getContext().getOrCreateSymbol(Name);
5151
5152 Sym->setRedefinable(allow_redef);
5153
5154 return false;
5155}
5156
5157} // namespace MCParserUtils
5158} // namespace llvm
5159
Daniel Dunbar01e36072010-07-17 02:26:10 +00005160/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005161MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5162 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005163 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005164}