blob: 04d141389c923f1e815d8e1b8cddf4d86d83c4d7 [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"
Evan Cheng76792992011-07-20 05:58:47 +000031#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000032#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000033#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000034#include "llvm/MC/MCSymbol.h"
Evan Cheng11424442011-07-26 00:24:13 +000035#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +000036#include "llvm/Support/CommandLine.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000037#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000038#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000039#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000040#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000041#include "llvm/Support/raw_ostream.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000042#include <cctype>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000043#include <deque>
Chad Rosier8bce6642012-10-18 15:49:34 +000044#include <set>
45#include <string>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000046#include <vector>
Chris Lattnerb0133452009-06-21 20:16:42 +000047using namespace llvm;
48
Eric Christophera7c32732012-12-18 00:30:54 +000049MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewyckyac612272012-10-19 07:00:09 +000050
Daniel Dunbar86033402010-07-12 17:54:38 +000051namespace {
Eli Benderskya313ae62013-01-16 18:56:50 +000052/// \brief Helper types for tracking macro definitions.
53typedef std::vector<AsmToken> MCAsmMacroArgument;
54typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000055
56struct MCAsmMacroParameter {
57 StringRef Name;
58 MCAsmMacroArgument Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000059 bool Required;
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000060 bool Vararg;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000061
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000062 MCAsmMacroParameter() : Required(false), Vararg(false) {}
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000063};
64
Eli Benderskya313ae62013-01-16 18:56:50 +000065typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
66
67struct MCAsmMacro {
68 StringRef Name;
69 StringRef Body;
70 MCAsmMacroParameters Parameters;
71
72public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +000073 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
74 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +000075};
76
Daniel Dunbar43235712010-07-18 18:54:11 +000077/// \brief Helper class for storing information about an active macro
78/// instantiation.
79struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000080 /// The location of the instantiation.
81 SMLoc InstantiationLoc;
82
Daniel Dunbar40f1d852012-12-01 01:38:48 +000083 /// The buffer where parsing should resume upon instantiation completion.
84 int ExitBuffer;
85
Daniel Dunbar43235712010-07-18 18:54:11 +000086 /// The location where parsing should resume upon instantiation completion.
87 SMLoc ExitLoc;
88
Nico Weber155dccd12014-07-24 17:08:39 +000089 /// The depth of TheCondStack at the start of the instantiation.
90 size_t CondStackDepth;
91
Daniel Dunbar43235712010-07-18 18:54:11 +000092public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +000093 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +000094};
95
Eli Friedman0f4871d2012-10-22 23:58:19 +000096struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +000097 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +000098 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +000099
Jim Grosbach4b905842013-09-20 23:08:21 +0000100 /// \brief The opcode from the last parsed instruction.
Eli Friedman0f4871d2012-10-22 23:58:19 +0000101 unsigned Opcode;
102
Jim Grosbach4b905842013-09-20 23:08:21 +0000103 /// \brief Was there an error parsing the inline assembly?
Chad Rosier149e8e02012-12-12 22:45:52 +0000104 bool ParseError;
105
Eli Friedman0f4871d2012-10-22 23:58:19 +0000106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107
Craig Topper353eda42014-04-24 06:44:33 +0000108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier149e8e02012-12-12 22:45:52 +0000110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000111};
112
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000113/// \brief The concrete assembly parser instance.
114class AsmParser : public MCAsmParser {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000115 AsmParser(const AsmParser &) = delete;
116 void operator=(const AsmParser &) = delete;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000117private:
118 AsmLexer Lexer;
119 MCContext &Ctx;
120 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000121 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000122 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000123 SourceMgr::DiagHandlerTy SavedDiagHandler;
124 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000125 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000126
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000127 /// This is the current buffer index we're lexing from as managed by the
128 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000129 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000130
131 AsmCond TheCondState;
132 std::vector<AsmCond> TheCondStack;
133
Jim Grosbach4b905842013-09-20 23:08:21 +0000134 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000135 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000136 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000137 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000138
Jim Grosbach4b905842013-09-20 23:08:21 +0000139 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000140 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000141
Jim Grosbach4b905842013-09-20 23:08:21 +0000142 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000143 std::vector<MacroInstantiation*> ActiveMacros;
144
Jim Grosbach4b905842013-09-20 23:08:21 +0000145 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000146 std::deque<MCAsmMacro> MacroLikeBodies;
147
Daniel Dunbar828984f2010-07-18 18:38:02 +0000148 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000149 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000150
Toma Tabacu217116e2015-04-27 10:50:29 +0000151 /// \brief Keeps track of how many .macro's have been instantiated.
152 unsigned NumOfMacroInstantiations;
153
Daniel Dunbar43325c42010-09-09 22:42:56 +0000154 /// Flag tracking whether any errors have been encountered.
155 unsigned HadError : 1;
156
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000157 /// The values from the last parsed cpp hash file line comment if any.
158 StringRef CppHashFilename;
159 int64_t CppHashLineNumber;
160 SMLoc CppHashLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000161 unsigned CppHashBuf;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000162 /// When generating dwarf for assembly source files we need to calculate the
163 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000164 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000165 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
166 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000167 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000168 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000169
Devang Patela173ee52012-01-31 18:14:05 +0000170 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
171 unsigned AssemblerDialect;
172
Jim Grosbach4b905842013-09-20 23:08:21 +0000173 /// \brief is Darwin compatibility enabled?
Preston Gurd05500642012-09-19 20:36:12 +0000174 bool IsDarwin;
175
Jim Grosbach4b905842013-09-20 23:08:21 +0000176 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier49963552012-10-13 00:26:04 +0000177 bool ParsingInlineAsm;
178
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000179public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000180 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000181 const MCAsmInfo &MAI);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000182 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000183
Craig Topper59be68f2014-03-08 07:14:16 +0000184 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000185
Craig Topper59be68f2014-03-08 07:14:16 +0000186 void addDirectiveHandler(StringRef Directive,
187 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000188 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000189 }
190
Toma Tabacu11e14a92015-04-21 11:50:52 +0000191 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
192 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
193 }
194
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000195public:
196 /// @name MCAsmParser Interface
197 /// {
198
Craig Topper59be68f2014-03-08 07:14:16 +0000199 SourceMgr &getSourceManager() override { return SrcMgr; }
200 MCAsmLexer &getLexer() override { return Lexer; }
201 MCContext &getContext() override { return Ctx; }
202 MCStreamer &getStreamer() override { return Out; }
203 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000204 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000205 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000206 else
207 return AssemblerDialect;
208 }
Craig Topper59be68f2014-03-08 07:14:16 +0000209 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000210 AssemblerDialect = i;
211 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000212
Craig Topper59be68f2014-03-08 07:14:16 +0000213 void Note(SMLoc L, const Twine &Msg,
214 ArrayRef<SMRange> Ranges = None) override;
215 bool Warning(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None) override;
217 bool Error(SMLoc L, const Twine &Msg,
218 ArrayRef<SMRange> Ranges = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000219
Craig Topper59be68f2014-03-08 07:14:16 +0000220 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000221
Craig Topper59be68f2014-03-08 07:14:16 +0000222 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
223 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000224
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000225 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000226 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier37e755c2012-10-23 17:43:43 +0000227 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000228 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000229 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000230 const MCInstrInfo *MII, const MCInstPrinter *IP,
231 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000232
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000233 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000234 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
235 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000237 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
238 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000239 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000240
Jim Grosbach4b905842013-09-20 23:08:21 +0000241 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000242 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000243 bool parseIdentifier(StringRef &Res) override;
244 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000245
Craig Topper59be68f2014-03-08 07:14:16 +0000246 void checkForValidSection() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000247 /// }
248
249private:
Daniel Dunbare5444a82010-09-09 22:42:59 +0000250
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000251 bool parseStatement(ParseStatementInfo &Info,
252 MCAsmParserSemaCallback *SI);
Jim Grosbach4b905842013-09-20 23:08:21 +0000253 void eatToEndOfLine();
254 bool parseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000255
Jim Grosbach4b905842013-09-20 23:08:21 +0000256 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000257 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000258 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000259 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000260 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Rafael Espindola1134ab232011-06-05 02:43:45 +0000261 const SMLoc &L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000262
Eli Benderskya313ae62013-01-16 18:56:50 +0000263 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000264 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000265
266 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000267 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000268
269 /// \brief Lookup a previously defined macro.
270 /// \param Name Macro name.
271 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000272 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000273
274 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000275 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000276
277 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000278 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000279
280 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000281 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000282
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000283 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000284 ///
285 /// \param M The macro.
286 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000287 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000288
289 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000290 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000291
David Majnemer91fc4c22014-01-29 18:57:46 +0000292 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000293 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000294
295 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000296 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000297
Jim Grosbach4b905842013-09-20 23:08:21 +0000298 void printMacroInstantiations();
299 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000300 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner72845262011-10-16 05:47:55 +0000301 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000302 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000303 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000304
Jim Grosbach4b905842013-09-20 23:08:21 +0000305 /// \brief Enter the specified file. This returns true on failure.
306 bool enterIncludeFile(const std::string &Filename);
307
308 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000309 /// This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000310 bool processIncbinFile(const std::string &Filename);
Daniel Dunbar43235712010-07-18 18:54:11 +0000311
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000312 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000313 /// current token is not set; clients should ensure Lex() is called
314 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000315 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000316 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000317 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000318 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000319
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000320 /// \brief Parse up to the end of statement and a return the contents from the
321 /// current token until the end of the statement; the current token on exit
322 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000323 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000324
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000325 /// \brief Parse until the end of a statement or a comma is encountered,
326 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000327 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000328
Jim Grosbach4b905842013-09-20 23:08:21 +0000329 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000330 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000331
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000332 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
333 MCBinaryExpr::Opcode &Kind);
334
Jim Grosbach4b905842013-09-20 23:08:21 +0000335 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000338
Jim Grosbach4b905842013-09-20 23:08:21 +0000339 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000340
Eli Bendersky17233942013-01-15 22:59:42 +0000341 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000342 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000343 DK_NO_DIRECTIVE, // Placeholder
344 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
David Woodhoused6de0d92014-02-01 16:20:59 +0000345 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
346 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000347 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000348 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000349 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000350 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
351 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
352 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
353 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000354 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000355 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
356 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000357 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
358 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
359 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
360 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
361 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
362 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000363 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000364 DK_MACROS_ON, DK_MACROS_OFF,
365 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000366 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000367 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000368 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000369 };
370
Jim Grosbach4b905842013-09-20 23:08:21 +0000371 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000372 /// directives parsed by this class.
373 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000374
375 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000376 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
377 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
David Woodhoused6de0d92014-02-01 16:20:59 +0000378 bool parseDirectiveOctaValue(); // ".octa"
Jim Grosbach4b905842013-09-20 23:08:21 +0000379 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
380 bool parseDirectiveFill(); // ".fill"
381 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000382 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000383 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
384 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000385 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000386 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000387
Eli Bendersky17233942013-01-15 22:59:42 +0000388 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000389 bool parseDirectiveFile(SMLoc DirectiveLoc);
390 bool parseDirectiveLine();
391 bool parseDirectiveLoc();
392 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000393
394 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000395 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000396 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000397 bool parseDirectiveCFISections();
398 bool parseDirectiveCFIStartProc();
399 bool parseDirectiveCFIEndProc();
400 bool parseDirectiveCFIDefCfaOffset();
401 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIAdjustCfaOffset();
403 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
405 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
406 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
407 bool parseDirectiveCFIRememberState();
408 bool parseDirectiveCFIRestoreState();
409 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
410 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
411 bool parseDirectiveCFIEscape();
412 bool parseDirectiveCFISignalFrame();
413 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000414
415 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000416 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000417 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000418 bool parseDirectiveEndMacro(StringRef Directive);
419 bool parseDirectiveMacro(SMLoc DirectiveLoc);
420 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000421
Eli Benderskyf483ff92012-12-20 19:05:53 +0000422 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000423 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000424 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000425 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000426 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000427 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000428
Eli Bendersky17233942013-01-15 22:59:42 +0000429 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000430 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000431
432 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000433 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000434
Jim Grosbach4b905842013-09-20 23:08:21 +0000435 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000436 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000437 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000438
Jim Grosbach4b905842013-09-20 23:08:21 +0000439 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000440
Jim Grosbach4b905842013-09-20 23:08:21 +0000441 bool parseDirectiveAbort(); // ".abort"
442 bool parseDirectiveInclude(); // ".include"
443 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000444
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000445 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
446 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000447 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000448 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000449 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000450 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000451 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
452 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000453 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000454 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
455 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
456 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
457 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000458 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000459
Jim Grosbach4b905842013-09-20 23:08:21 +0000460 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000461 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000462
Rafael Espindola34b9c512012-06-03 23:57:14 +0000463 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000464 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
465 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000466 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000467 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000468 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
469 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
470 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000471
Chad Rosierc7f552c2013-02-12 21:33:51 +0000472 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000473 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000474 size_t Len);
475
476 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000477 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000478
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000479 // "end"
480 bool parseDirectiveEnd(SMLoc DirectiveLoc);
481
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000482 // ".err" or ".error"
483 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000484
Nico Weber404012b2014-07-24 16:26:06 +0000485 // ".warning"
486 bool parseDirectiveWarning(SMLoc DirectiveLoc);
487
Eli Bendersky17233942013-01-15 22:59:42 +0000488 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000489};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000490}
Daniel Dunbar86033402010-07-12 17:54:38 +0000491
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000492namespace llvm {
493
494extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000495extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000496extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000497
498}
499
Chris Lattnerc35681b2010-01-19 19:46:13 +0000500enum { DEFAULT_ADDRSPACE = 0 };
501
David Blaikie9f380a32015-03-16 18:06:57 +0000502AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
503 const MCAsmInfo &MAI)
504 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
505 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Alp Tokera55b95b2014-07-06 10:33:31 +0000506 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
Oliver Stannardcf6bfb12014-11-03 12:19:03 +0000507 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000508 // Save the old handler.
509 SavedDiagHandler = SrcMgr.getDiagHandler();
510 SavedDiagContext = SrcMgr.getDiagContext();
511 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000512 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000513 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000514
Daniel Dunbarc5011082010-07-12 18:12:02 +0000515 // Initialize the platform / file format parser.
David Blaikie9f380a32015-03-16 18:06:57 +0000516 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
Rafael Espindolae28610d2013-12-09 20:26:40 +0000517 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000518 PlatformParser.reset(createCOFFAsmParser());
519 break;
Rafael Espindolae28610d2013-12-09 20:26:40 +0000520 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000521 PlatformParser.reset(createDarwinAsmParser());
522 IsDarwin = true;
523 break;
Rafael Espindolae28610d2013-12-09 20:26:40 +0000524 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000525 PlatformParser.reset(createELFAsmParser());
526 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000527 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000528
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000529 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000530 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000531
532 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000533}
534
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000535AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000536 assert((HadError || ActiveMacros.empty()) &&
537 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000538}
539
Jim Grosbach4b905842013-09-20 23:08:21 +0000540void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000541 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000542 for (std::vector<MacroInstantiation *>::const_reverse_iterator
543 it = ActiveMacros.rbegin(),
544 ie = ActiveMacros.rend();
545 it != ie; ++it)
546 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000547 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000548}
549
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000550void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
551 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
552 printMacroInstantiations();
553}
554
Chris Lattnera3a06812011-10-16 04:47:35 +0000555bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000556 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Chris Lattnera3a06812011-10-16 04:47:35 +0000557 return Error(L, Msg, Ranges);
Jim Grosbach4b905842013-09-20 23:08:21 +0000558 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
559 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000560 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000561}
562
Chris Lattnera3a06812011-10-16 04:47:35 +0000563bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000564 HadError = true;
Jim Grosbach4b905842013-09-20 23:08:21 +0000565 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
566 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000567 return true;
568}
569
Jim Grosbach4b905842013-09-20 23:08:21 +0000570bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000571 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000572 unsigned NewBuf =
573 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
574 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000575 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000576
Sean Callanan7a77eae2010-01-21 00:19:58 +0000577 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000578 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000579 return false;
580}
Daniel Dunbar43235712010-07-18 18:54:11 +0000581
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000582/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000583/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000584/// returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000585bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000586 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000587 unsigned NewBuf =
588 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
589 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000590 return true;
591
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000592 // Pick up the bytes from the file and emit them.
Rafael Espindola64e1af82013-07-02 15:49:13 +0000593 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderby109f25c2011-12-14 21:47:48 +0000594 return false;
595}
596
Alp Tokera55b95b2014-07-06 10:33:31 +0000597void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
598 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000599 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
600 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000601}
602
Sean Callanan7a77eae2010-01-21 00:19:58 +0000603const AsmToken &AsmParser::Lex() {
604 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000605
Sean Callanan7a77eae2010-01-21 00:19:58 +0000606 if (tok->is(AsmToken::Eof)) {
607 // If this is the end of an included file, pop the parent file off the
608 // include stack.
609 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
610 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000611 jumpToLoc(ParentIncludeLoc);
Sean Callanan7a77eae2010-01-21 00:19:58 +0000612 tok = &Lexer.Lex();
613 }
614 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000615
Sean Callanan7a77eae2010-01-21 00:19:58 +0000616 if (tok->is(AsmToken::Error))
Daniel Dunbard8a18452010-07-18 18:31:45 +0000617 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencer530ce852010-10-09 11:00:50 +0000618
Sean Callanan7a77eae2010-01-21 00:19:58 +0000619 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000620}
621
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000622bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000623 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000624 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000625 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000626
Chris Lattner36e02122009-06-21 20:54:55 +0000627 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000628 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000629
630 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000631 AsmCond StartingCondState = TheCondState;
632
Kevin Enderby6469fc22011-11-01 22:27:22 +0000633 // If we are generating dwarf for assembly source files save the initial text
634 // section and generate a .file directive.
635 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000636 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000637 if (!Sec->getBeginSymbol()) {
638 MCSymbol *SectionStartSym = getContext().createTempSymbol();
639 getStreamer().EmitLabel(SectionStartSym);
640 Sec->setBeginSymbol(SectionStartSym);
641 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000642 bool InsertResult = getContext().addGenDwarfSection(Sec);
643 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000644 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000645 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
646 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000647 }
648
Chris Lattner73f36112009-07-02 21:53:43 +0000649 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000650 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000651 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000652 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000653 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000654
Daniel Dunbar43325c42010-09-09 22:42:56 +0000655 // We had an error, validate that one was emitted and recover by skipping to
656 // the next line.
657 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000658 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000659 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000660
661 if (TheCondState.TheCond != StartingCondState.TheCond ||
662 TheCondState.Ignore != StartingCondState.Ignore)
663 return TokError("unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000664
665 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000666 const auto &LineTables = getContext().getMCDwarfLineTables();
667 if (!LineTables.empty()) {
668 unsigned Index = 0;
669 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
670 if (File.Name.empty() && Index != 0)
671 TokError("unassigned file number: " + Twine(Index) +
672 " for .file directives");
673 ++Index;
674 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000675 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000676
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000677 // Check to see that all assembler local symbols were actually defined.
678 // Targets that don't do subsections via symbols may not want this, though,
679 // so conservatively exclude them. Only do this if we're finalizing, though,
680 // as otherwise we won't necessarilly have seen everything yet.
681 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
682 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
683 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
Jim Grosbach4b905842013-09-20 23:08:21 +0000684 e = Symbols.end();
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000685 i != e; ++i) {
686 MCSymbol *Sym = i->getValue();
687 // Variable symbols may not be marked as defined, so check those
688 // explicitly. If we know it's a variable, we have a definition for
689 // the purposes of this check.
690 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
691 // FIXME: We would really like to refer back to where the symbol was
692 // first referenced for a source location. We need to add something
693 // to track that. Currently, we just point to the end of the file.
Jim Grosbach4b905842013-09-20 23:08:21 +0000694 printMessage(
695 getLexer().getLoc(), SourceMgr::DK_Error,
696 "assembler local symbol '" + Sym->getName() + "' not defined");
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000697 }
698 }
699
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000700 // Finalize the output stream if there are no errors and if the client wants
701 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000702 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000703 Out.Finish();
704
Chris Lattner73f36112009-07-02 21:53:43 +0000705 return HadError;
Chris Lattner36e02122009-06-21 20:54:55 +0000706}
707
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000708void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000709 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbare5444a82010-09-09 22:42:59 +0000710 TokError("expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000711 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000712 }
713}
714
Jim Grosbach4b905842013-09-20 23:08:21 +0000715/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000716void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000717 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000718 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000719
Chris Lattnere5074c42009-06-22 01:29:09 +0000720 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000721 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000722 Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000723}
724
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000725StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000726 const char *Start = getTok().getLoc().getPointer();
727
Jim Grosbach4b905842013-09-20 23:08:21 +0000728 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000729 Lex();
730
731 const char *End = getTok().getLoc().getPointer();
732 return StringRef(Start, End - Start);
733}
Chris Lattner78db3622009-06-22 05:51:26 +0000734
Jim Grosbach4b905842013-09-20 23:08:21 +0000735StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000736 const char *Start = getTok().getLoc().getPointer();
737
738 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000739 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000740 Lex();
741
742 const char *End = getTok().getLoc().getPointer();
743 return StringRef(Start, End - Start);
744}
745
Jim Grosbach4b905842013-09-20 23:08:21 +0000746/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000747/// NOTE: This assumes the leading '(' has already been consumed.
748///
749/// parenexpr ::= expr)
750///
Jim Grosbach4b905842013-09-20 23:08:21 +0000751bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
752 if (parseExpression(Res))
753 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000754 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000755 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000756 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000757 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000758 return false;
759}
Chris Lattner78db3622009-06-22 05:51:26 +0000760
Jim Grosbach4b905842013-09-20 23:08:21 +0000761/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000762/// NOTE: This assumes the leading '[' has already been consumed.
763///
764/// bracketexpr ::= expr]
765///
Jim Grosbach4b905842013-09-20 23:08:21 +0000766bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
767 if (parseExpression(Res))
768 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000769 if (Lexer.isNot(AsmToken::RBrac))
770 return TokError("expected ']' in brackets expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000771 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000772 Lex();
773 return false;
774}
775
Jim Grosbach4b905842013-09-20 23:08:21 +0000776/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000777/// primaryexpr ::= (parenexpr
778/// primaryexpr ::= symbol
779/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000780/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000781/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000782bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000783 SMLoc FirstTokenLoc = getLexer().getLoc();
784 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
785 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000786 default:
787 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000788 // If we have an error assume that we've already handled it.
789 case AsmToken::Error:
790 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000791 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000792 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000793 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000794 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000795 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000796 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000797 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000798 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000799 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000800 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000801 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000802 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000803 if (FirstTokenKind == AsmToken::Dollar) {
804 if (Lexer.getMAI().getDollarIsPC()) {
805 // This is a '$' reference, which references the current PC. Emit a
806 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000807 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000808 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000809 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000810 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000811 EndLoc = FirstTokenLoc;
812 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000813 }
814 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000815 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000816 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000817 // Parse symbol variant
818 std::pair<StringRef, StringRef> Split;
819 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000820 if (FirstTokenKind == AsmToken::String) {
821 if (Lexer.is(AsmToken::At)) {
822 Lexer.Lex(); // eat @
823 SMLoc AtLoc = getLexer().getLoc();
824 StringRef VName;
825 if (parseIdentifier(VName))
826 return Error(AtLoc, "expected symbol variant after '@'");
827
828 Split = std::make_pair(Identifier, VName);
829 }
830 } else {
831 Split = Identifier.split('@');
832 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000833 } else if (Lexer.is(AsmToken::LParen)) {
834 Lexer.Lex(); // eat (
835 StringRef VName;
836 parseIdentifier(VName);
837 if (Lexer.isNot(AsmToken::RParen)) {
838 return Error(Lexer.getTok().getLoc(),
839 "unexpected token in variant, expected ')'");
840 }
841 Lexer.Lex(); // eat )
842 Split = std::make_pair(Identifier, VName);
843 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000844
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000845 EndLoc = SMLoc::getFromPointer(Identifier.end());
846
Daniel Dunbard20cda02009-10-16 01:34:54 +0000847 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000848 StringRef SymbolName = Identifier;
849 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000850
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000851 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000852 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000853 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000854 if (Variant != MCSymbolRefExpr::VK_Invalid) {
855 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000856 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000857 Variant = MCSymbolRefExpr::VK_None;
858 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000859 return Error(SMLoc::getFromPointer(Split.second.begin()),
860 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000861 }
862 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000863
Jim Grosbach6f482002015-05-18 18:43:14 +0000864 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000865
Daniel Dunbard20cda02009-10-16 01:34:54 +0000866 // If this is an absolute variable reference, substitute it now to preserve
867 // semantics in the face of reassignment.
Daniel Dunbar7a989da2010-05-05 17:41:00 +0000868 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000869 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000870 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000871
Daniel Dunbar7a989da2010-05-05 17:41:00 +0000872 Res = Sym->getVariableValue();
Daniel Dunbard20cda02009-10-16 01:34:54 +0000873 return false;
874 }
875
876 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000877 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +0000878 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +0000879 }
David Woodhousef42a6662014-02-01 16:20:54 +0000880 case AsmToken::BigNum:
881 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +0000882 case AsmToken::Integer: {
883 SMLoc Loc = getTok().getLoc();
884 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000885 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000886 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000887 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +0000888 // Look for 'b' or 'f' following an Integer as a directional label
889 if (Lexer.getKind() == AsmToken::Identifier) {
890 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +0000891 // Lookup the symbol variant if used.
892 std::pair<StringRef, StringRef> Split = IDVal.split('@');
893 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
894 if (Split.first.size() != IDVal.size()) {
895 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +0000896 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +0000897 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000898 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +0000899 }
Jim Grosbach4b905842013-09-20 23:08:21 +0000900 if (IDVal == "f" || IDVal == "b") {
901 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +0000902 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +0000903 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +0000904 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderby0510b482010-05-17 23:08:19 +0000905 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000906 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +0000907 Lex(); // Eat identifier.
908 }
909 }
Chris Lattner78db3622009-06-22 05:51:26 +0000910 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +0000911 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000912 case AsmToken::Real: {
913 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +0000914 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000915 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000916 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000917 Lex(); // Eat token.
918 return false;
919 }
Chris Lattner6b55cb92010-04-14 04:40:28 +0000920 case AsmToken::Dot: {
921 // This is a '.' reference, which references the current PC. Emit a
922 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000923 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000924 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000925 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000926 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000927 Lex(); // Eat identifier.
928 return false;
929 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000930 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000931 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +0000932 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000933 case AsmToken::LBrac:
934 if (!PlatformParser->HasBracketExpressions())
935 return TokError("brackets expression not supported on this target");
936 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +0000937 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000938 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000939 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000940 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000941 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000942 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000943 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000944 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000945 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000946 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000947 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000948 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000949 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000950 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000951 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000952 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000953 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000954 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000955 return false;
Chris Lattner78db3622009-06-22 05:51:26 +0000956 }
957}
Chris Lattner7fdbce72009-06-22 06:32:03 +0000958
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000959bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +0000960 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000961 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +0000962}
963
Daniel Dunbar55f16672010-09-17 02:47:07 +0000964const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +0000965AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000966 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +0000967 // Ask the target implementation about this expression first.
968 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
969 if (NewE)
970 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000971 // Recurse over the given expression, rebuilding it to apply the given variant
972 // if there is exactly one symbol.
973 switch (E->getKind()) {
974 case MCExpr::Target:
975 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +0000976 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000977
978 case MCExpr::SymbolRef: {
979 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
980
981 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000982 TokError("invalid variant on expression '" + getTok().getIdentifier() +
983 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000984 return E;
985 }
986
Jim Grosbach13760bd2015-05-30 01:25:56 +0000987 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +0000988 }
989
990 case MCExpr::Unary: {
991 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +0000992 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +0000993 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +0000994 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000995 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +0000996 }
997
998 case MCExpr::Binary: {
999 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001000 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1001 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001002
1003 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001004 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001005
Jim Grosbach4b905842013-09-20 23:08:21 +00001006 if (!LHS)
1007 LHS = BE->getLHS();
1008 if (!RHS)
1009 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001010
Jim Grosbach13760bd2015-05-30 01:25:56 +00001011 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001012 }
1013 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001014
Craig Toppera2886c22012-02-07 05:05:23 +00001015 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001016}
1017
Jim Grosbach4b905842013-09-20 23:08:21 +00001018/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001019///
Jim Grosbachbd164242011-08-20 16:24:13 +00001020/// expr ::= expr &&,|| expr -> lowest.
1021/// expr ::= expr |,^,&,! expr
1022/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1023/// expr ::= expr <<,>> expr
1024/// expr ::= expr +,- expr
1025/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001026/// expr ::= primaryexpr
1027///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001028bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001029 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001030 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001031 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001032 return true;
1033
Daniel Dunbar55f16672010-09-17 02:47:07 +00001034 // As a special case, we support 'a op b @ modifier' by rewriting the
1035 // expression to include the modifier. This is inefficient, but in general we
1036 // expect users to use 'a@modifier op b'.
1037 if (Lexer.getKind() == AsmToken::At) {
1038 Lex();
1039
1040 if (Lexer.isNot(AsmToken::Identifier))
1041 return TokError("unexpected symbol modifier following '@'");
1042
1043 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001044 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001045 if (Variant == MCSymbolRefExpr::VK_Invalid)
1046 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1047
Jim Grosbach4b905842013-09-20 23:08:21 +00001048 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001049 if (!ModifiedRes) {
1050 return TokError("invalid modifier '" + getTok().getIdentifier() +
1051 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001052 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001053
Daniel Dunbar55f16672010-09-17 02:47:07 +00001054 Res = ModifiedRes;
1055 Lex();
1056 }
1057
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001058 // Try to constant fold it up front, if possible.
1059 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001060 if (Res->evaluateAsAbsolute(Value))
1061 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001062
1063 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001064}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001065
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001066bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001067 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001068 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001069}
1070
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001071bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1072 SMLoc &EndLoc) {
1073 if (parseParenExpr(Res, EndLoc))
1074 return true;
1075
1076 for (; ParenDepth > 0; --ParenDepth) {
1077 if (parseBinOpRHS(1, Res, EndLoc))
1078 return true;
1079
1080 // We don't Lex() the last RParen.
1081 // This is the same behavior as parseParenExpression().
1082 if (ParenDepth - 1 > 0) {
1083 if (Lexer.isNot(AsmToken::RParen))
1084 return TokError("expected ')' in parentheses expression");
1085 EndLoc = Lexer.getTok().getEndLoc();
1086 Lex();
1087 }
1088 }
1089 return false;
1090}
1091
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001092bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001093 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001094
Daniel Dunbar75630b32009-06-30 02:10:03 +00001095 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001096 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001097 return true;
1098
Jim Grosbach13760bd2015-05-30 01:25:56 +00001099 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001100 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001101
1102 return false;
1103}
1104
Ahmed Bougacha457852f2015-04-28 00:17:39 +00001105unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1106 MCBinaryExpr::Opcode &Kind) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001107 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001108 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001109 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001110
Jim Grosbach4b905842013-09-20 23:08:21 +00001111 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001112 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001113 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001114 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001115 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001116 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001117 return 1;
1118
Jim Grosbach4b905842013-09-20 23:08:21 +00001119 // Low Precedence: |, &, ^
1120 //
1121 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001122 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001123 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001124 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001125 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001126 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001127 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001128 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001129 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001130 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001131
Jim Grosbach4b905842013-09-20 23:08:21 +00001132 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001133 case AsmToken::EqualEqual:
1134 Kind = MCBinaryExpr::EQ;
1135 return 3;
1136 case AsmToken::ExclaimEqual:
1137 case AsmToken::LessGreater:
1138 Kind = MCBinaryExpr::NE;
1139 return 3;
1140 case AsmToken::Less:
1141 Kind = MCBinaryExpr::LT;
1142 return 3;
1143 case AsmToken::LessEqual:
1144 Kind = MCBinaryExpr::LTE;
1145 return 3;
1146 case AsmToken::Greater:
1147 Kind = MCBinaryExpr::GT;
1148 return 3;
1149 case AsmToken::GreaterEqual:
1150 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001151 return 3;
1152
Jim Grosbach4b905842013-09-20 23:08:21 +00001153 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001154 case AsmToken::LessLess:
1155 Kind = MCBinaryExpr::Shl;
1156 return 4;
1157 case AsmToken::GreaterGreater:
Ahmed Bougacha177c1482015-04-28 00:21:32 +00001158 Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001159 return 4;
1160
Jim Grosbach4b905842013-09-20 23:08:21 +00001161 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001162 case AsmToken::Plus:
1163 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001164 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001165 case AsmToken::Minus:
1166 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001167 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001168
Jim Grosbach4b905842013-09-20 23:08:21 +00001169 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001170 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001171 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001172 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001173 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001174 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001175 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001176 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001177 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001178 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001179 }
1180}
1181
Jim Grosbach4b905842013-09-20 23:08:21 +00001182/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001183/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001184bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001185 SMLoc &EndLoc) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001186 while (1) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001187 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001188 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001189
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001190 // If the next token is lower precedence than we are allowed to eat, return
1191 // successfully with what we ate already.
1192 if (TokPrec < Precedence)
1193 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001194
Sean Callanan686ed8d2010-01-19 20:22:31 +00001195 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001196
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001197 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001198 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001199 if (parsePrimaryExpr(RHS, EndLoc))
1200 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001201
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001202 // If BinOp binds less tightly with RHS than the operator after RHS, let
1203 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001204 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001205 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001206 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1207 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001208
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001209 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001210 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001211 }
1212}
1213
Chris Lattner36e02122009-06-21 20:54:55 +00001214/// ParseStatement:
1215/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001216/// ::= Label* Directive ...Operands... EndOfStatement
1217/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001218bool AsmParser::parseStatement(ParseStatementInfo &Info,
1219 MCAsmParserSemaCallback *SI) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001220 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001221 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001222 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001223 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001224 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001225
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001226 // Statements always start with an identifier or are a full line comment.
Sean Callanan936b0d32010-01-19 21:44:56 +00001227 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001228 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001229 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001230 int64_t LocalLabelVal = -1;
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001231 // A full line comment is a '#' as the first token.
Kevin Enderby72553612011-09-13 23:45:18 +00001232 if (Lexer.is(AsmToken::Hash))
Jim Grosbach4b905842013-09-20 23:08:21 +00001233 return parseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar3f561042011-03-25 17:47:14 +00001234
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001235 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001236 if (Lexer.is(AsmToken::Integer)) {
1237 LocalLabelVal = getTok().getIntVal();
1238 if (LocalLabelVal < 0) {
1239 if (!TheCondState.Ignore)
1240 return TokError("unexpected token at start of statement");
1241 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001242 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001243 IDVal = getTok().getString();
1244 Lex(); // Consume the integer token to be used as an identifier token.
1245 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001246 if (!TheCondState.Ignore)
1247 return TokError("unexpected token at start of statement");
Kevin Enderby0510b482010-05-17 23:08:19 +00001248 }
1249 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001250 } else if (Lexer.is(AsmToken::Dot)) {
1251 // Treat '.' as a valid identifier in this context.
1252 Lex();
1253 IDVal = ".";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001254 } else if (parseIdentifier(IDVal)) {
Chris Lattner926885c2010-04-17 18:14:27 +00001255 if (!TheCondState.Ignore)
1256 return TokError("unexpected token at start of statement");
1257 IDVal = "";
1258 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001259
Chris Lattner926885c2010-04-17 18:14:27 +00001260 // Handle conditional assembly here before checking for skipping. We
1261 // have to do this so that .endif isn't skipped in a ".if 0" block for
1262 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001263 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001264 DirectiveKindMap.find(IDVal);
1265 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1266 ? DK_NO_DIRECTIVE
1267 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001268 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001269 default:
1270 break;
1271 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001272 case DK_IFEQ:
1273 case DK_IFGE:
1274 case DK_IFGT:
1275 case DK_IFLE:
1276 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001277 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001278 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001279 case DK_IFB:
1280 return parseDirectiveIfb(IDLoc, true);
1281 case DK_IFNB:
1282 return parseDirectiveIfb(IDLoc, false);
1283 case DK_IFC:
1284 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001285 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001286 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001287 case DK_IFNC:
1288 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001289 case DK_IFNES:
1290 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001291 case DK_IFDEF:
1292 return parseDirectiveIfdef(IDLoc, true);
1293 case DK_IFNDEF:
1294 case DK_IFNOTDEF:
1295 return parseDirectiveIfdef(IDLoc, false);
1296 case DK_ELSEIF:
1297 return parseDirectiveElseIf(IDLoc);
1298 case DK_ELSE:
1299 return parseDirectiveElse(IDLoc);
1300 case DK_ENDIF:
1301 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001302 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001303
Eli Bendersky88024712013-01-16 19:32:36 +00001304 // Ignore the statement if in the middle of inactive conditional
1305 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001306 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001307 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001308 return false;
1309 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001310
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001311 // FIXME: Recurse on local labels?
1312
1313 // See what kind of statement we have.
1314 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001315 case AsmToken::Colon: {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001316 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001317
Chris Lattner36e02122009-06-21 20:54:55 +00001318 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001319 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001320
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001321 // Diagnose attempt to use '.' as a label.
1322 if (IDVal == ".")
1323 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1324
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001325 // Diagnose attempt to use a variable as a label.
1326 //
1327 // FIXME: Diagnostics. Note the location of the definition as a label.
1328 // FIXME: This doesn't diagnose assignment to a symbol which has been
1329 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001330 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001331 if (LocalLabelVal == -1) {
1332 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001333 StringRef RewrittenLabel =
1334 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1335 assert(RewrittenLabel.size() &&
1336 "We should have an internal name here.");
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001337 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1338 IDVal.size(), RewrittenLabel));
1339 IDVal = RewrittenLabel;
1340 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001341 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001342 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001343 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001344
1345 Sym->redefineIfPossible();
1346
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001347 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001348 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001349
Daniel Dunbare73b2672009-08-26 22:13:22 +00001350 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001351 if (!ParsingInlineAsm)
1352 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001353
Kevin Enderbye7739d42011-12-09 18:09:40 +00001354 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001355 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001356 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001357 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1358 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001359
Tim Northover1744d0a2013-10-25 12:49:50 +00001360 getTargetParser().onLabelParsed(Sym);
1361
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001362 // Consume any end of statement token, if present, to avoid spurious
1363 // AddBlankLine calls().
1364 if (Lexer.is(AsmToken::EndOfStatement)) {
1365 Lex();
1366 if (Lexer.is(AsmToken::Eof))
1367 return false;
1368 }
1369
Eli Friedman0f4871d2012-10-22 23:58:19 +00001370 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001371 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001372
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001373 case AsmToken::Equal:
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001374 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001375 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001376
Jim Grosbach4b905842013-09-20 23:08:21 +00001377 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001378
1379 default: // Normal instruction or directive.
1380 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001381 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001382
1383 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001384 if (areMacrosEnabled())
1385 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1386 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001387 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001388
Michael J. Spencer530ce852010-10-09 11:00:50 +00001389 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001390
Eli Bendersky17233942013-01-15 22:59:42 +00001391 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001392 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001393 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001394 //
Eli Bendersky17233942013-01-15 22:59:42 +00001395 // 1. The target-specific assembly parser. Some directives are target
1396 // specific or may potentially behave differently on certain targets.
1397 // 2. Asm parser extensions. For example, platform-specific parsers
1398 // (like the ELF parser) register themselves as extensions.
1399 // 3. The generic directive parser implemented by this class. These are
1400 // all the directives that behave in a target and platform independent
1401 // manner, or at least have a default behavior that's shared between
1402 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001403
Eli Bendersky17233942013-01-15 22:59:42 +00001404 // First query the target-specific parser. It will return 'true' if it
1405 // isn't interested in this directive.
Akira Hatanakad3590752012-07-05 19:09:33 +00001406 if (!getTargetParser().ParseDirective(ID))
1407 return false;
1408
Alp Tokercb402912014-01-24 17:20:08 +00001409 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001410 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001411 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1412 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001413 if (Handler.first)
1414 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1415
1416 // Finally, if no one else is interested in this directive, it must be
1417 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001418 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001419 default:
1420 break;
1421 case DK_SET:
1422 case DK_EQU:
1423 return parseDirectiveSet(IDVal, true);
1424 case DK_EQUIV:
1425 return parseDirectiveSet(IDVal, false);
1426 case DK_ASCII:
1427 return parseDirectiveAscii(IDVal, false);
1428 case DK_ASCIZ:
1429 case DK_STRING:
1430 return parseDirectiveAscii(IDVal, true);
1431 case DK_BYTE:
1432 return parseDirectiveValue(1);
1433 case DK_SHORT:
1434 case DK_VALUE:
1435 case DK_2BYTE:
1436 return parseDirectiveValue(2);
1437 case DK_LONG:
1438 case DK_INT:
1439 case DK_4BYTE:
1440 return parseDirectiveValue(4);
1441 case DK_QUAD:
1442 case DK_8BYTE:
1443 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001444 case DK_OCTA:
1445 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001446 case DK_SINGLE:
1447 case DK_FLOAT:
1448 return parseDirectiveRealValue(APFloat::IEEEsingle);
1449 case DK_DOUBLE:
1450 return parseDirectiveRealValue(APFloat::IEEEdouble);
1451 case DK_ALIGN: {
1452 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1453 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1454 }
1455 case DK_ALIGN32: {
1456 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1457 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1458 }
1459 case DK_BALIGN:
1460 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1461 case DK_BALIGNW:
1462 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1463 case DK_BALIGNL:
1464 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1465 case DK_P2ALIGN:
1466 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1467 case DK_P2ALIGNW:
1468 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1469 case DK_P2ALIGNL:
1470 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1471 case DK_ORG:
1472 return parseDirectiveOrg();
1473 case DK_FILL:
1474 return parseDirectiveFill();
1475 case DK_ZERO:
1476 return parseDirectiveZero();
1477 case DK_EXTERN:
1478 eatToEndOfStatement(); // .extern is the default, ignore it.
1479 return false;
1480 case DK_GLOBL:
1481 case DK_GLOBAL:
1482 return parseDirectiveSymbolAttribute(MCSA_Global);
1483 case DK_LAZY_REFERENCE:
1484 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1485 case DK_NO_DEAD_STRIP:
1486 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1487 case DK_SYMBOL_RESOLVER:
1488 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1489 case DK_PRIVATE_EXTERN:
1490 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1491 case DK_REFERENCE:
1492 return parseDirectiveSymbolAttribute(MCSA_Reference);
1493 case DK_WEAK_DEFINITION:
1494 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1495 case DK_WEAK_REFERENCE:
1496 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1497 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1498 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1499 case DK_COMM:
1500 case DK_COMMON:
1501 return parseDirectiveComm(/*IsLocal=*/false);
1502 case DK_LCOMM:
1503 return parseDirectiveComm(/*IsLocal=*/true);
1504 case DK_ABORT:
1505 return parseDirectiveAbort();
1506 case DK_INCLUDE:
1507 return parseDirectiveInclude();
1508 case DK_INCBIN:
1509 return parseDirectiveIncbin();
1510 case DK_CODE16:
1511 case DK_CODE16GCC:
1512 return TokError(Twine(IDVal) + " not supported yet");
1513 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001514 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001515 case DK_IRP:
1516 return parseDirectiveIrp(IDLoc);
1517 case DK_IRPC:
1518 return parseDirectiveIrpc(IDLoc);
1519 case DK_ENDR:
1520 return parseDirectiveEndr(IDLoc);
1521 case DK_BUNDLE_ALIGN_MODE:
1522 return parseDirectiveBundleAlignMode();
1523 case DK_BUNDLE_LOCK:
1524 return parseDirectiveBundleLock();
1525 case DK_BUNDLE_UNLOCK:
1526 return parseDirectiveBundleUnlock();
1527 case DK_SLEB128:
1528 return parseDirectiveLEB128(true);
1529 case DK_ULEB128:
1530 return parseDirectiveLEB128(false);
1531 case DK_SPACE:
1532 case DK_SKIP:
1533 return parseDirectiveSpace(IDVal);
1534 case DK_FILE:
1535 return parseDirectiveFile(IDLoc);
1536 case DK_LINE:
1537 return parseDirectiveLine();
1538 case DK_LOC:
1539 return parseDirectiveLoc();
1540 case DK_STABS:
1541 return parseDirectiveStabs();
1542 case DK_CFI_SECTIONS:
1543 return parseDirectiveCFISections();
1544 case DK_CFI_STARTPROC:
1545 return parseDirectiveCFIStartProc();
1546 case DK_CFI_ENDPROC:
1547 return parseDirectiveCFIEndProc();
1548 case DK_CFI_DEF_CFA:
1549 return parseDirectiveCFIDefCfa(IDLoc);
1550 case DK_CFI_DEF_CFA_OFFSET:
1551 return parseDirectiveCFIDefCfaOffset();
1552 case DK_CFI_ADJUST_CFA_OFFSET:
1553 return parseDirectiveCFIAdjustCfaOffset();
1554 case DK_CFI_DEF_CFA_REGISTER:
1555 return parseDirectiveCFIDefCfaRegister(IDLoc);
1556 case DK_CFI_OFFSET:
1557 return parseDirectiveCFIOffset(IDLoc);
1558 case DK_CFI_REL_OFFSET:
1559 return parseDirectiveCFIRelOffset(IDLoc);
1560 case DK_CFI_PERSONALITY:
1561 return parseDirectiveCFIPersonalityOrLsda(true);
1562 case DK_CFI_LSDA:
1563 return parseDirectiveCFIPersonalityOrLsda(false);
1564 case DK_CFI_REMEMBER_STATE:
1565 return parseDirectiveCFIRememberState();
1566 case DK_CFI_RESTORE_STATE:
1567 return parseDirectiveCFIRestoreState();
1568 case DK_CFI_SAME_VALUE:
1569 return parseDirectiveCFISameValue(IDLoc);
1570 case DK_CFI_RESTORE:
1571 return parseDirectiveCFIRestore(IDLoc);
1572 case DK_CFI_ESCAPE:
1573 return parseDirectiveCFIEscape();
1574 case DK_CFI_SIGNAL_FRAME:
1575 return parseDirectiveCFISignalFrame();
1576 case DK_CFI_UNDEFINED:
1577 return parseDirectiveCFIUndefined(IDLoc);
1578 case DK_CFI_REGISTER:
1579 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001580 case DK_CFI_WINDOW_SAVE:
1581 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001582 case DK_MACROS_ON:
1583 case DK_MACROS_OFF:
1584 return parseDirectiveMacrosOnOff(IDVal);
1585 case DK_MACRO:
1586 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001587 case DK_EXITM:
1588 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001589 case DK_ENDM:
1590 case DK_ENDMACRO:
1591 return parseDirectiveEndMacro(IDVal);
1592 case DK_PURGEM:
1593 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001594 case DK_END:
1595 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001596 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001597 return parseDirectiveError(IDLoc, false);
1598 case DK_ERROR:
1599 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001600 case DK_WARNING:
1601 return parseDirectiveWarning(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00001602 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001603
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001604 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001605 }
Chris Lattner36e02122009-06-21 20:54:55 +00001606
Chad Rosierc7f552c2013-02-12 21:33:51 +00001607 // __asm _emit or __asm __emit
1608 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1609 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001610 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001611
1612 // __asm align
1613 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001614 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001615
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001616 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001617
Chris Lattner7cbfa442010-05-19 23:34:33 +00001618 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001619 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001620 ParseInstructionInfo IInfo(Info.AsmRewrites);
Jim Grosbach4b905842013-09-20 23:08:21 +00001621 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001622 Info.ParsedOperands);
Chad Rosier149e8e02012-12-12 22:45:52 +00001623 Info.ParseError = HadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001624
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001625 // Dump the parsed representation, if requested.
1626 if (getShowParsedOperands()) {
1627 SmallString<256> Str;
1628 raw_svector_ostream OS(Str);
1629 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001630 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001631 if (i != 0)
1632 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001633 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001634 }
1635 OS << "]";
1636
Jim Grosbach4b905842013-09-20 23:08:21 +00001637 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001638 }
1639
Oliver Stannard8b273082014-06-19 15:52:37 +00001640 // If we are generating dwarf for the current section then generate a .loc
1641 // directive for the instruction.
Kevin Enderby6469fc22011-11-01 22:27:22 +00001642 if (!HadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001643 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001644 getStreamer().getCurrentSection().first)) {
1645 unsigned Line;
1646 if (ActiveMacros.empty())
1647 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1648 else
Frederic Riss16238d92015-06-25 21:57:33 +00001649 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1650 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001651
Eli Bendersky88024712013-01-16 19:32:36 +00001652 // If we previously parsed a cpp hash file line comment then make sure the
1653 // current Dwarf File is for the CppHashFilename if not then emit the
1654 // Dwarf File table for it and adjust the line number for the .loc.
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001655 if (CppHashFilename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001656 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1657 0, StringRef(), CppHashFilename);
1658 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001659
Jim Grosbach4b905842013-09-20 23:08:21 +00001660 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1661 // cache with the different Loc from the call above we save the last
1662 // info we queried here with SrcMgr.FindLineNumber().
1663 unsigned CppHashLocLineNo;
1664 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1665 CppHashLocLineNo = LastQueryLine;
1666 else {
1667 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1668 LastQueryLine = CppHashLocLineNo;
1669 LastQueryIDLoc = CppHashLoc;
1670 LastQueryBuffer = CppHashBuf;
1671 }
1672 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00001673 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001674
Jim Grosbach4b905842013-09-20 23:08:21 +00001675 getStreamer().EmitDwarfLocDirective(
1676 getContext().getGenDwarfFileNumber(), Line, 0,
1677 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1678 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00001679 }
1680
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00001681 // If parsing succeeded, match the instruction.
Chad Rosier49963552012-10-13 00:26:04 +00001682 if (!HadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00001683 uint64_t ErrorInfo;
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001684 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1685 Info.ParsedOperands, Out,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00001686 ErrorInfo, ParsingInlineAsm);
Chad Rosier49963552012-10-13 00:26:04 +00001687 }
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001688
Chris Lattnera2a9d162010-09-11 16:18:25 +00001689 // Don't skip the rest of the line, the instruction parser is responsible for
1690 // that.
1691 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00001692}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00001693
Jim Grosbach4b905842013-09-20 23:08:21 +00001694/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
Kevin Enderby72553612011-09-13 23:45:18 +00001695/// since they may not be able to be tokenized to get to the end of line token.
Jim Grosbach4b905842013-09-20 23:08:21 +00001696void AsmParser::eatToEndOfLine() {
Rafael Espindolae0d09082011-10-19 18:48:52 +00001697 if (!Lexer.is(AsmToken::EndOfStatement))
1698 Lexer.LexUntilEndOfLine();
Jim Grosbach4b905842013-09-20 23:08:21 +00001699 // Eat EOL.
1700 Lex();
Kevin Enderby72553612011-09-13 23:45:18 +00001701}
1702
Jim Grosbach4b905842013-09-20 23:08:21 +00001703/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00001704/// ::= # number "filename"
1705/// or just as a full line comment if it doesn't have a number and a string.
Jim Grosbach4b905842013-09-20 23:08:21 +00001706bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
Kevin Enderby72553612011-09-13 23:45:18 +00001707 Lex(); // Eat the hash token.
1708
1709 if (getLexer().isNot(AsmToken::Integer)) {
1710 // Consume the line since in cases it is not a well-formed line directive,
1711 // as if were simply a full line comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001712 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001713 return false;
1714 }
1715
1716 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00001717 Lex();
1718
1719 if (getLexer().isNot(AsmToken::String)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001720 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001721 return false;
1722 }
1723
1724 StringRef Filename = getTok().getString();
1725 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00001726 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00001727
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001728 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1729 CppHashLoc = L;
1730 CppHashFilename = Filename;
1731 CppHashLineNumber = LineNumber;
Kevin Enderby27121c12012-11-05 21:55:41 +00001732 CppHashBuf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00001733
1734 // Ignore any trailing characters, they're just comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001735 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001736 return false;
1737}
1738
Jim Grosbach4b905842013-09-20 23:08:21 +00001739/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001740/// for the Filename and LineNo if any in the diagnostic.
1741void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001742 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001743 raw_ostream &OS = errs();
1744
1745 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1746 const SMLoc &DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00001747 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1748 unsigned CppHashBuf =
1749 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001750
Jim Grosbach4b905842013-09-20 23:08:21 +00001751 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001752 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00001753 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1754 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1755 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001756 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1757 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001758 }
1759
Eric Christophera7c32732012-12-18 00:30:54 +00001760 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001761 // manager changed or buffer changed (like in a nested include) then just
1762 // print the normal diagnostic using its Filename and LineNo.
Jim Grosbach4b905842013-09-20 23:08:21 +00001763 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001764 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001765 if (Parser->SavedDiagHandler)
1766 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1767 else
Craig Topper353eda42014-04-24 06:44:33 +00001768 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001769 return;
1770 }
1771
Eric Christophera7c32732012-12-18 00:30:54 +00001772 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001773 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1774 // the diagnostic.
Jakub Staszakec2ffa92013-09-16 22:03:38 +00001775 const std::string &Filename = Parser->CppHashFilename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001776
1777 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1778 int CppHashLocLineNo =
1779 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001780 int LineNo =
1781 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001782
Jim Grosbach4b905842013-09-20 23:08:21 +00001783 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1784 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00001785 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001786
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001787 if (Parser->SavedDiagHandler)
1788 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1789 else
Craig Topper353eda42014-04-24 06:44:33 +00001790 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001791}
1792
Rafael Espindola2c064482012-08-21 18:29:30 +00001793// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1794// difference being that that function accepts '@' as part of identifiers and
1795// we can't do that. AsmLexer.cpp should probably be changed to handle
1796// '@' as a special case when needed.
1797static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001798 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1799 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00001800}
1801
Rafael Espindola34b9c512012-06-03 23:57:14 +00001802bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00001803 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00001804 ArrayRef<MCAsmMacroArgument> A,
1805 bool EnableAtPseudoVariable, const SMLoc &L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001806 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001807 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00001808 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00001809 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001810
Preston Gurd05500642012-09-19 20:36:12 +00001811 // A macro without parameters is handled differently on Darwin:
1812 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001813 while (!Body.empty()) {
1814 // Scan for the next substitution.
1815 std::size_t End = Body.size(), Pos = 0;
1816 for (; Pos != End; ++Pos) {
1817 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00001818 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001819 // This macro has no parameters, look for $0, $1, etc.
1820 if (Body[Pos] != '$' || Pos + 1 == End)
1821 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001822
Rafael Espindola1134ab232011-06-05 02:43:45 +00001823 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00001824 if (Next == '$' || Next == 'n' ||
1825 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00001826 break;
1827 } else {
1828 // This macro has parameters, look for \foo, \bar, etc.
1829 if (Body[Pos] == '\\' && Pos + 1 != End)
1830 break;
1831 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001832 }
1833
1834 // Add the prefix.
1835 OS << Body.slice(0, Pos);
1836
1837 // Check if we reached the end.
1838 if (Pos == End)
1839 break;
1840
Benjamin Kramer513e7442014-02-20 13:36:32 +00001841 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001842 switch (Body[Pos + 1]) {
1843 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00001844 case '$':
1845 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001846 break;
1847
Jim Grosbach4b905842013-09-20 23:08:21 +00001848 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00001849 case 'n':
1850 OS << A.size();
1851 break;
1852
Jim Grosbach4b905842013-09-20 23:08:21 +00001853 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00001854 default: {
1855 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00001856 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00001857 if (Index >= A.size())
1858 break;
1859
1860 // Otherwise substitute with the token values, with spaces eliminated.
Eli Benderskya7b905e2013-01-14 19:00:26 +00001861 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Jim Grosbach4b905842013-09-20 23:08:21 +00001862 ie = A[Index].end();
1863 it != ie; ++it)
Rafael Espindola1134ab232011-06-05 02:43:45 +00001864 OS << it->getString();
1865 break;
1866 }
1867 }
1868 Pos += 2;
1869 } else {
1870 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00001871
1872 // Check for the \@ pseudo-variable.
1873 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00001874 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00001875 else
1876 while (isIdentifierChar(Body[I]) && I + 1 != End)
1877 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00001878
Jim Grosbach4b905842013-09-20 23:08:21 +00001879 const char *Begin = Body.data() + Pos + 1;
1880 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00001881 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00001882
Toma Tabacu217116e2015-04-27 10:50:29 +00001883 if (Argument == "@") {
1884 OS << NumOfMacroInstantiations;
1885 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00001886 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00001887 for (; Index < NParameters; ++Index)
1888 if (Parameters[Index].Name == Argument)
1889 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00001890
Toma Tabacu217116e2015-04-27 10:50:29 +00001891 if (Index == NParameters) {
1892 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1893 Pos += 3;
1894 else {
1895 OS << '\\' << Argument;
1896 Pos = I;
1897 }
1898 } else {
1899 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1900 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1901 ie = A[Index].end();
1902 it != ie; ++it)
1903 // We expect no quotes around the string's contents when
1904 // parsing for varargs.
1905 if (it->getKind() != AsmToken::String || VarargParameter)
1906 OS << it->getString();
1907 else
1908 OS << it->getStringContents();
1909
1910 Pos += 1 + Argument.size();
1911 }
Preston Gurd05500642012-09-19 20:36:12 +00001912 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00001913 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001914 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00001915 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001916 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001917
Rafael Espindola1134ab232011-06-05 02:43:45 +00001918 return false;
1919}
Daniel Dunbar43235712010-07-18 18:54:11 +00001920
Nico Weber2a8f9222014-07-24 16:29:04 +00001921MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00001922 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00001923 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00001924 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00001925
Jim Grosbach4b905842013-09-20 23:08:21 +00001926static bool isOperator(AsmToken::TokenKind kind) {
1927 switch (kind) {
1928 default:
1929 return false;
1930 case AsmToken::Plus:
1931 case AsmToken::Minus:
1932 case AsmToken::Tilde:
1933 case AsmToken::Slash:
1934 case AsmToken::Star:
1935 case AsmToken::Dot:
1936 case AsmToken::Equal:
1937 case AsmToken::EqualEqual:
1938 case AsmToken::Pipe:
1939 case AsmToken::PipePipe:
1940 case AsmToken::Caret:
1941 case AsmToken::Amp:
1942 case AsmToken::AmpAmp:
1943 case AsmToken::Exclaim:
1944 case AsmToken::ExclaimEqual:
1945 case AsmToken::Percent:
1946 case AsmToken::Less:
1947 case AsmToken::LessEqual:
1948 case AsmToken::LessLess:
1949 case AsmToken::LessGreater:
1950 case AsmToken::Greater:
1951 case AsmToken::GreaterEqual:
1952 case AsmToken::GreaterGreater:
1953 return true;
Preston Gurd05500642012-09-19 20:36:12 +00001954 }
1955}
1956
David Majnemer16252452014-01-29 00:07:39 +00001957namespace {
1958class AsmLexerSkipSpaceRAII {
1959public:
1960 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1961 Lexer.setSkipSpace(SkipSpace);
1962 }
1963
1964 ~AsmLexerSkipSpaceRAII() {
1965 Lexer.setSkipSpace(true);
1966 }
1967
1968private:
1969 AsmLexer &Lexer;
1970};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001971}
David Majnemer16252452014-01-29 00:07:39 +00001972
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001973bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1974
1975 if (Vararg) {
1976 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1977 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001978 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001979 }
1980 return false;
1981 }
1982
Rafael Espindola768b41c2012-06-15 14:02:34 +00001983 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00001984 unsigned AddTokens = 0;
1985
David Majnemer16252452014-01-29 00:07:39 +00001986 // Darwin doesn't use spaces to delmit arguments.
1987 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00001988
1989 for (;;) {
David Majnemer16252452014-01-29 00:07:39 +00001990 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00001991 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00001992
David Majnemer91fc4c22014-01-29 18:57:46 +00001993 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
Preston Gurd05500642012-09-19 20:36:12 +00001994 break;
Preston Gurd05500642012-09-19 20:36:12 +00001995
1996 if (Lexer.is(AsmToken::Space)) {
1997 Lex(); // Eat spaces
1998
1999 // Spaces can delimit parameters, but could also be part an expression.
2000 // If the token after a space is an operator, add the token and the next
2001 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002002 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002003 if (isOperator(Lexer.getKind())) {
Preston Gurd05500642012-09-19 20:36:12 +00002004 // Check to see whether the token is used as an operator,
2005 // or part of an identifier
Jordan Rosee8f1eae2013-01-07 19:00:49 +00002006 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd05500642012-09-19 20:36:12 +00002007 if (*NextChar == ' ')
2008 AddTokens = 2;
2009 }
2010
2011 if (!AddTokens && ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002012 break;
2013 }
2014 }
2015 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002016
Jim Grosbach4b905842013-09-20 23:08:21 +00002017 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002018 // to be able to fill in the remaining default parameter values
2019 if (Lexer.is(AsmToken::EndOfStatement))
2020 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002021
2022 // Adjust the current parentheses level.
2023 if (Lexer.is(AsmToken::LParen))
2024 ++ParenLevel;
2025 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2026 --ParenLevel;
2027
2028 // Append the token to the current argument list.
2029 MA.push_back(getTok());
Preston Gurd05500642012-09-19 20:36:12 +00002030 if (AddTokens)
2031 AddTokens--;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002032 Lex();
2033 }
Preston Gurd05500642012-09-19 20:36:12 +00002034
Rafael Espindola768b41c2012-06-15 14:02:34 +00002035 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002036 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002037 return false;
2038}
2039
2040// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002041bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002042 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002043 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002044 bool NamedParametersFound = false;
2045 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002046
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002047 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002048 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002049
Rafael Espindola768b41c2012-06-15 14:02:34 +00002050 // Parse two kinds of macro invocations:
2051 // - macros defined without any parameters accept an arbitrary number of them
2052 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002053 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002054 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2055 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002056 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002057 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002058
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002059 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002060 if (parseIdentifier(FA.Name)) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002061 Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002062 eatToEndOfStatement();
2063 return true;
2064 }
2065
2066 if (!Lexer.is(AsmToken::Equal)) {
2067 TokError("expected '=' after formal parameter identifier");
2068 eatToEndOfStatement();
2069 return true;
2070 }
2071 Lex();
2072
2073 NamedParametersFound = true;
2074 }
2075
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002076 if (NamedParametersFound && FA.Name.empty()) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002077 Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002078 eatToEndOfStatement();
2079 return true;
2080 }
2081
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002082 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2083 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002084 return true;
2085
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002086 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002087 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002088 unsigned FAI = 0;
2089 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002090 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002091 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002092
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002093 if (FAI >= NParameters) {
Oliver Stannard8b273082014-06-19 15:52:37 +00002094 assert(M && "expected macro to be defined");
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002095 Error(IDLoc,
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002096 "parameter named '" + FA.Name + "' does not exist for macro '" +
Saleem Abdulrasool3f44cd72014-03-17 17:13:57 +00002097 M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002098 return true;
2099 }
2100 PI = FAI;
2101 }
2102
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002103 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002104 if (A.size() <= PI)
2105 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002106 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002107
2108 if (FALocs.size() <= PI)
2109 FALocs.resize(PI + 1);
2110
2111 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002112 }
Jim Grosbach206661622012-07-30 22:44:17 +00002113
Preston Gurd242ed3152012-09-19 20:29:04 +00002114 // At the end of the statement, fill in remaining arguments that have
2115 // default values. If there aren't any, then the next argument is
2116 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002117 if (Lexer.is(AsmToken::EndOfStatement)) {
2118 bool Failure = false;
2119 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2120 if (A[FAI].empty()) {
2121 if (M->Parameters[FAI].Required) {
2122 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2123 "missing value for required parameter "
2124 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2125 Failure = true;
2126 }
2127
2128 if (!M->Parameters[FAI].Value.empty())
2129 A[FAI] = M->Parameters[FAI].Value;
2130 }
2131 }
2132 return Failure;
2133 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002134
2135 if (Lexer.is(AsmToken::Comma))
2136 Lex();
2137 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002138
2139 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002140}
2141
Jim Grosbach4b905842013-09-20 23:08:21 +00002142const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002143 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2144 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002145}
2146
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002147void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2148 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002149}
2150
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002151void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002152
Jim Grosbach4b905842013-09-20 23:08:21 +00002153bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbar43235712010-07-18 18:54:11 +00002154 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2155 // this, although we should protect against infinite loops.
2156 if (ActiveMacros.size() == 20)
2157 return TokError("macros cannot be nested more than 20 levels deep");
2158
Eli Bendersky38274122013-01-14 23:22:36 +00002159 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002160 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002161 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002162
Rafael Espindola1134ab232011-06-05 02:43:45 +00002163 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2164 // to hold the macro body with substitutions.
2165 SmallString<256> Buf;
2166 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002167 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002168
Toma Tabacu217116e2015-04-27 10:50:29 +00002169 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002170 return true;
2171
Eli Bendersky38274122013-01-14 23:22:36 +00002172 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002173 // instantiation.
2174 OS << ".endmacro\n";
2175
Rafael Espindola3560ff22014-08-27 20:03:13 +00002176 std::unique_ptr<MemoryBuffer> Instantiation =
2177 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002178
Daniel Dunbar43235712010-07-18 18:54:11 +00002179 // Create the macro instantiation object and add to the current macro
2180 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002181 MacroInstantiation *MI = new MacroInstantiation(
2182 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002183 ActiveMacros.push_back(MI);
2184
Toma Tabacu217116e2015-04-27 10:50:29 +00002185 ++NumOfMacroInstantiations;
2186
Daniel Dunbar43235712010-07-18 18:54:11 +00002187 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002188 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002189 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002190 Lex();
2191
2192 return false;
2193}
2194
Jim Grosbach4b905842013-09-20 23:08:21 +00002195void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002196 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002197 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002198 Lex();
2199
2200 // Pop the instantiation entry.
2201 delete ActiveMacros.back();
2202 ActiveMacros.pop_back();
2203}
2204
Jim Grosbach4b905842013-09-20 23:08:21 +00002205bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002206 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002207 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002208 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002209 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2210 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002211 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002212
Pete Cooper80d21cb2015-06-22 19:35:57 +00002213 if (!Sym) {
2214 // In the case where we parse an expression starting with a '.', we will
2215 // not generate an error, nor will we create a symbol. In this case we
2216 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002217 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002218 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002219
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002220 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002221 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002222 if (NoDeadStrip)
2223 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2224
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002225 return false;
2226}
2227
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002228/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002229/// ::= identifier
2230/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002231bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002232 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002233 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2234 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002235 // handle this as a context dependent token, instead we detect adjacent tokens
2236 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002237 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2238 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002239
Hans Wennborgce69d772013-10-18 20:46:28 +00002240 // Consume the prefix character, and check for a following identifier.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002241 Lex();
2242 if (Lexer.isNot(AsmToken::Identifier))
2243 return true;
2244
Hans Wennborgce69d772013-10-18 20:46:28 +00002245 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2246 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002247 return true;
2248
2249 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002250 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002251 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002252 Lex();
2253 return false;
2254 }
2255
Jim Grosbach4b905842013-09-20 23:08:21 +00002256 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002257 return true;
2258
Sean Callanan936b0d32010-01-19 21:44:56 +00002259 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002260
Sean Callanan686ed8d2010-01-19 20:22:31 +00002261 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002262
2263 return false;
2264}
2265
Jim Grosbach4b905842013-09-20 23:08:21 +00002266/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002267/// ::= .equ identifier ',' expression
2268/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002269/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002270bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002271 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002272
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002273 if (parseIdentifier(Name))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002274 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencer530ce852010-10-09 11:00:50 +00002275
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002276 if (getLexer().isNot(AsmToken::Comma))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002277 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002278 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002279
Jim Grosbach4b905842013-09-20 23:08:21 +00002280 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002281}
2282
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002283bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002284 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002285
2286 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002287 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002288 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2289 if (Str[i] != '\\') {
2290 Data += Str[i];
2291 continue;
2292 }
2293
2294 // Recognize escaped characters. Note that this escape semantics currently
2295 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2296 ++i;
2297 if (i == e)
2298 return TokError("unexpected backslash at end of string");
2299
2300 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002301 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002302 // Consume up to three octal characters.
2303 unsigned Value = Str[i] - '0';
2304
Jim Grosbach4b905842013-09-20 23:08:21 +00002305 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002306 ++i;
2307 Value = Value * 8 + (Str[i] - '0');
2308
Jim Grosbach4b905842013-09-20 23:08:21 +00002309 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002310 ++i;
2311 Value = Value * 8 + (Str[i] - '0');
2312 }
2313 }
2314
2315 if (Value > 255)
2316 return TokError("invalid octal escape sequence (out of range)");
2317
Jim Grosbach4b905842013-09-20 23:08:21 +00002318 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002319 continue;
2320 }
2321
2322 // Otherwise recognize individual escapes.
2323 switch (Str[i]) {
2324 default:
2325 // Just reject invalid escape sequences for now.
2326 return TokError("invalid escape sequence (unrecognized character)");
2327
2328 case 'b': Data += '\b'; break;
2329 case 'f': Data += '\f'; break;
2330 case 'n': Data += '\n'; break;
2331 case 'r': Data += '\r'; break;
2332 case 't': Data += '\t'; break;
2333 case '"': Data += '"'; break;
2334 case '\\': Data += '\\'; break;
2335 }
2336 }
2337
2338 return false;
2339}
2340
Jim Grosbach4b905842013-09-20 23:08:21 +00002341/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002342/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002343bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002344 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002345 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002346
Daniel Dunbara10e5192009-06-24 23:30:00 +00002347 for (;;) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002348 if (getLexer().isNot(AsmToken::String))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002349 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002350
Daniel Dunbaref668c12009-08-14 18:19:52 +00002351 std::string Data;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002352 if (parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002353 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002354
Rafael Espindola64e1af82013-07-02 15:49:13 +00002355 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002356 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002357 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002358
Sean Callanan686ed8d2010-01-19 20:22:31 +00002359 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002360
2361 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002362 break;
2363
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002364 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002365 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002366 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002367 }
2368 }
2369
Sean Callanan686ed8d2010-01-19 20:22:31 +00002370 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002371 return false;
2372}
2373
Jim Grosbach4b905842013-09-20 23:08:21 +00002374/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002375/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002376bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002377 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002378 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002379
Daniel Dunbara10e5192009-06-24 23:30:00 +00002380 for (;;) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002381 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002382 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002383 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002384 return true;
2385
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002386 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002387 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2388 assert(Size <= 8 && "Invalid size");
2389 uint64_t IntValue = MCE->getValue();
2390 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2391 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002392 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002393 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002394 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002395
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002396 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002397 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002398
Daniel Dunbara10e5192009-06-24 23:30:00 +00002399 // FIXME: Improve diagnostic.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002400 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002401 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002402 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002403 }
2404 }
2405
Sean Callanan686ed8d2010-01-19 20:22:31 +00002406 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002407 return false;
2408}
2409
David Woodhoused6de0d92014-02-01 16:20:59 +00002410/// ParseDirectiveOctaValue
2411/// ::= .octa [ hexconstant (, hexconstant)* ]
2412bool AsmParser::parseDirectiveOctaValue() {
2413 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2414 checkForValidSection();
2415
2416 for (;;) {
2417 if (Lexer.getKind() == AsmToken::Error)
2418 return true;
2419 if (Lexer.getKind() != AsmToken::Integer &&
2420 Lexer.getKind() != AsmToken::BigNum)
2421 return TokError("unknown token in expression");
2422
2423 SMLoc ExprLoc = getLexer().getLoc();
2424 APInt IntValue = getTok().getAPIntVal();
2425 Lex();
2426
2427 uint64_t hi, lo;
2428 if (IntValue.isIntN(64)) {
2429 hi = 0;
2430 lo = IntValue.getZExtValue();
2431 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002432 // It might actually have more than 128 bits, but the top ones are zero.
2433 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002434 lo = IntValue.getLoBits(64).getZExtValue();
2435 } else
2436 return Error(ExprLoc, "literal value out of range for directive");
2437
2438 if (MAI.isLittleEndian()) {
2439 getStreamer().EmitIntValue(lo, 8);
2440 getStreamer().EmitIntValue(hi, 8);
2441 } else {
2442 getStreamer().EmitIntValue(hi, 8);
2443 getStreamer().EmitIntValue(lo, 8);
2444 }
2445
2446 if (getLexer().is(AsmToken::EndOfStatement))
2447 break;
2448
2449 // FIXME: Improve diagnostic.
2450 if (getLexer().isNot(AsmToken::Comma))
2451 return TokError("unexpected token in directive");
2452 Lex();
2453 }
2454 }
2455
2456 Lex();
2457 return false;
2458}
2459
Jim Grosbach4b905842013-09-20 23:08:21 +00002460/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002461/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002462bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002463 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002464 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002465
2466 for (;;) {
2467 // We don't truly support arithmetic on floating point expressions, so we
2468 // have to manually parse unary prefixes.
2469 bool IsNeg = false;
2470 if (getLexer().is(AsmToken::Minus)) {
2471 Lex();
2472 IsNeg = true;
2473 } else if (getLexer().is(AsmToken::Plus))
2474 Lex();
2475
Michael J. Spencer530ce852010-10-09 11:00:50 +00002476 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002477 getLexer().isNot(AsmToken::Real) &&
2478 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002479 return TokError("unexpected token in directive");
2480
2481 // Convert to an APFloat.
2482 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002483 StringRef IDVal = getTok().getString();
2484 if (getLexer().is(AsmToken::Identifier)) {
2485 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2486 Value = APFloat::getInf(Semantics);
2487 else if (!IDVal.compare_lower("nan"))
2488 Value = APFloat::getNaN(Semantics, false, ~0);
2489 else
2490 return TokError("invalid floating point literal");
2491 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002492 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002493 return TokError("invalid floating point literal");
2494 if (IsNeg)
2495 Value.changeSign();
2496
2497 // Consume the numeric token.
2498 Lex();
2499
2500 // Emit the value as an integer.
2501 APInt AsInt = Value.bitcastToAPInt();
2502 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002503 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002504
2505 if (getLexer().is(AsmToken::EndOfStatement))
2506 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002507
Daniel Dunbar2af16532010-09-24 01:59:56 +00002508 if (getLexer().isNot(AsmToken::Comma))
2509 return TokError("unexpected token in directive");
2510 Lex();
2511 }
2512 }
2513
2514 Lex();
2515 return false;
2516}
2517
Jim Grosbach4b905842013-09-20 23:08:21 +00002518/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002519/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002520bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002521 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002522
2523 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002524 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002525 return true;
2526
Rafael Espindolab91bac62010-10-05 19:42:57 +00002527 int64_t Val = 0;
2528 if (getLexer().is(AsmToken::Comma)) {
2529 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002530 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002531 return true;
2532 }
2533
Rafael Espindola922e3f42010-09-16 15:03:59 +00002534 if (getLexer().isNot(AsmToken::EndOfStatement))
2535 return TokError("unexpected token in '.zero' directive");
2536
2537 Lex();
2538
Rafael Espindola64e1af82013-07-02 15:49:13 +00002539 getStreamer().EmitFill(NumBytes, Val);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002540
2541 return false;
2542}
2543
Jim Grosbach4b905842013-09-20 23:08:21 +00002544/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002545/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002546bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002547 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002548
David Majnemer522d3db2014-02-01 07:19:38 +00002549 SMLoc RepeatLoc = getLexer().getLoc();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002550 int64_t NumValues;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002551 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002552 return true;
2553
David Majnemer522d3db2014-02-01 07:19:38 +00002554 if (NumValues < 0) {
2555 Warning(RepeatLoc,
2556 "'.fill' directive with negative repeat count has no effect");
2557 NumValues = 0;
2558 }
2559
Roman Divackye33098f2013-09-24 17:44:41 +00002560 int64_t FillSize = 1;
2561 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002562
David Majnemer522d3db2014-02-01 07:19:38 +00002563 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002564 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2565 if (getLexer().isNot(AsmToken::Comma))
2566 return TokError("unexpected token in '.fill' directive");
2567 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002568
David Majnemer522d3db2014-02-01 07:19:38 +00002569 SizeLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002570 if (parseAbsoluteExpression(FillSize))
2571 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002572
Roman Divackye33098f2013-09-24 17:44:41 +00002573 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2574 if (getLexer().isNot(AsmToken::Comma))
2575 return TokError("unexpected token in '.fill' directive");
2576 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002577
David Majnemer522d3db2014-02-01 07:19:38 +00002578 ExprLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002579 if (parseAbsoluteExpression(FillExpr))
2580 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002581
Roman Divackye33098f2013-09-24 17:44:41 +00002582 if (getLexer().isNot(AsmToken::EndOfStatement))
2583 return TokError("unexpected token in '.fill' directive");
2584
2585 Lex();
2586 }
2587 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002588
David Majnemer522d3db2014-02-01 07:19:38 +00002589 if (FillSize < 0) {
2590 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2591 NumValues = 0;
2592 }
2593 if (FillSize > 8) {
2594 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2595 FillSize = 8;
2596 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002597
David Majnemer522d3db2014-02-01 07:19:38 +00002598 if (!isUInt<32>(FillExpr) && FillSize > 4)
2599 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2600
Alexey Samsonov1b0713c2014-09-02 17:25:29 +00002601 if (NumValues > 0) {
2602 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2603 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2604 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2605 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2606 if (NonZeroFillSize < FillSize)
2607 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2608 }
David Majnemer522d3db2014-02-01 07:19:38 +00002609 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002610
2611 return false;
2612}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002613
Jim Grosbach4b905842013-09-20 23:08:21 +00002614/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002615/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002616bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002617 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002618
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002619 const MCExpr *Offset;
Jim Grosbachb5912772012-01-27 00:37:08 +00002620 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002621 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002622 return true;
2623
2624 // Parse optional fill expression.
2625 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002626 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2627 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002628 return TokError("unexpected token in '.org' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002629 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00002630
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002631 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002632 return true;
2633
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002634 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002635 return TokError("unexpected token in '.org' directive");
2636 }
2637
Sean Callanan686ed8d2010-01-19 20:22:31 +00002638 Lex();
Daniel Dunbar75630b32009-06-30 02:10:03 +00002639
Jim Grosbachb5912772012-01-27 00:37:08 +00002640 // Only limited forms of relocatable expressions are accepted here, it
2641 // has to be relative to the current section. The streamer will return
2642 // 'true' if the expression wasn't evaluatable.
2643 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2644 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002645
2646 return false;
2647}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002648
Jim Grosbach4b905842013-09-20 23:08:21 +00002649/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002650/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002651bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002652 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002653
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002654 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002655 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002656 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002657 return true;
2658
2659 SMLoc MaxBytesLoc;
2660 bool HasFillExpr = false;
2661 int64_t FillExpr = 0;
2662 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002663 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2664 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002665 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002666 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002667
2668 // The fill expression can be omitted while specifying a maximum number of
2669 // alignment bytes, e.g:
2670 // .align 3,,4
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002671 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002672 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002673 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002674 return true;
2675 }
2676
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002677 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2678 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002679 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002680 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002681
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002682 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002683 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002684 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002685
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002686 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002687 return TokError("unexpected token in directive");
2688 }
2689 }
2690
Sean Callanan686ed8d2010-01-19 20:22:31 +00002691 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002692
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002693 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002694 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002695
2696 // Compute alignment in bytes.
2697 if (IsPow2) {
2698 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002699 if (Alignment >= 32) {
2700 Error(AlignmentLoc, "invalid alignment value");
2701 Alignment = 31;
2702 }
2703
Benjamin Kramer63951ad2009-09-06 09:35:10 +00002704 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002705 } else {
2706 // Reject alignments that aren't a power of two, for gas compatibility.
2707 if (!isPowerOf2_64(Alignment))
2708 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002709 }
2710
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002711 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002712 if (MaxBytesLoc.isValid()) {
2713 if (MaxBytesToFill < 1) {
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002714 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00002715 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00002716 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002717 }
2718
2719 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00002720 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00002721 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002722 MaxBytesToFill = 0;
2723 }
2724 }
2725
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002726 // Check whether we should use optimal code alignment for this .align
2727 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00002728 const MCSection *Section = getStreamer().getCurrentSection().first;
2729 assert(Section && "must have section to emit alignment");
2730 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002731 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2732 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002733 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002734 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00002735 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00002736 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2737 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002738 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002739
2740 return false;
2741}
2742
Jim Grosbach4b905842013-09-20 23:08:21 +00002743/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00002744/// ::= .file [number] filename
2745/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00002746bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00002747 // FIXME: I'm not sure what this is.
2748 int64_t FileNumber = -1;
2749 SMLoc FileNumberLoc = getLexer().getLoc();
2750 if (getLexer().is(AsmToken::Integer)) {
2751 FileNumber = getTok().getIntVal();
2752 Lex();
2753
2754 if (FileNumber < 1)
2755 return TokError("file number less than one");
2756 }
2757
2758 if (getLexer().isNot(AsmToken::String))
2759 return TokError("unexpected token in '.file' directive");
2760
2761 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002762 // Allow the strings to have escaped octal character sequence.
2763 std::string Path = getTok().getString();
2764 if (parseEscapedString(Path))
2765 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00002766 Lex();
2767
2768 StringRef Directory;
2769 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002770 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002771 if (getLexer().is(AsmToken::String)) {
2772 if (FileNumber == -1)
2773 return TokError("explicit path specified, but no file number");
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002774 if (parseEscapedString(FilenameData))
2775 return true;
2776 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002777 Directory = Path;
2778 Lex();
2779 } else {
2780 Filename = Path;
2781 }
2782
2783 if (getLexer().isNot(AsmToken::EndOfStatement))
2784 return TokError("unexpected token in '.file' directive");
2785
2786 if (FileNumber == -1)
2787 getStreamer().EmitFileDirective(Filename);
2788 else {
David Blaikiedc3f01e2015-03-09 01:57:13 +00002789 if (getContext().getGenDwarfForAssembly())
Jim Grosbach4b905842013-09-20 23:08:21 +00002790 Error(DirectiveLoc,
2791 "input can't have .file dwarf directives when -g is "
2792 "used to generate dwarf debug info for assembly code");
Eli Bendersky17233942013-01-15 22:59:42 +00002793
David Blaikiec714ef42014-03-17 01:52:11 +00002794 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2795 0)
Eli Bendersky17233942013-01-15 22:59:42 +00002796 Error(FileNumberLoc, "file number already allocated");
2797 }
2798
2799 return false;
2800}
2801
Jim Grosbach4b905842013-09-20 23:08:21 +00002802/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00002803/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00002804bool AsmParser::parseDirectiveLine() {
Eli Bendersky17233942013-01-15 22:59:42 +00002805 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2806 if (getLexer().isNot(AsmToken::Integer))
2807 return TokError("unexpected token in '.line' directive");
2808
2809 int64_t LineNumber = getTok().getIntVal();
Jim Grosbach4b905842013-09-20 23:08:21 +00002810 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00002811 Lex();
2812
2813 // FIXME: Do something with the .line.
2814 }
2815
2816 if (getLexer().isNot(AsmToken::EndOfStatement))
2817 return TokError("unexpected token in '.line' directive");
2818
2819 return false;
2820}
2821
Jim Grosbach4b905842013-09-20 23:08:21 +00002822/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00002823/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2824/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2825/// The first number is a file number, must have been previously assigned with
2826/// a .file directive, the second number is the line number and optionally the
2827/// third number is a column position (zero if not specified). The remaining
2828/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00002829bool AsmParser::parseDirectiveLoc() {
Eli Bendersky17233942013-01-15 22:59:42 +00002830 if (getLexer().isNot(AsmToken::Integer))
2831 return TokError("unexpected token in '.loc' directive");
2832 int64_t FileNumber = getTok().getIntVal();
2833 if (FileNumber < 1)
2834 return TokError("file number less than one in '.loc' directive");
2835 if (!getContext().isValidDwarfFileNumber(FileNumber))
2836 return TokError("unassigned file number in '.loc' directive");
2837 Lex();
2838
2839 int64_t LineNumber = 0;
2840 if (getLexer().is(AsmToken::Integer)) {
2841 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00002842 if (LineNumber < 0)
2843 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00002844 Lex();
2845 }
2846
2847 int64_t ColumnPos = 0;
2848 if (getLexer().is(AsmToken::Integer)) {
2849 ColumnPos = getTok().getIntVal();
2850 if (ColumnPos < 0)
2851 return TokError("column position less than zero in '.loc' directive");
2852 Lex();
2853 }
2854
2855 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2856 unsigned Isa = 0;
2857 int64_t Discriminator = 0;
2858 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2859 for (;;) {
2860 if (getLexer().is(AsmToken::EndOfStatement))
2861 break;
2862
2863 StringRef Name;
2864 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002865 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00002866 return TokError("unexpected token in '.loc' directive");
2867
2868 if (Name == "basic_block")
2869 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2870 else if (Name == "prologue_end")
2871 Flags |= DWARF2_FLAG_PROLOGUE_END;
2872 else if (Name == "epilogue_begin")
2873 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2874 else if (Name == "is_stmt") {
2875 Loc = getTok().getLoc();
2876 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002877 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00002878 return true;
2879 // The expression must be the constant 0 or 1.
2880 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2881 int Value = MCE->getValue();
2882 if (Value == 0)
2883 Flags &= ~DWARF2_FLAG_IS_STMT;
2884 else if (Value == 1)
2885 Flags |= DWARF2_FLAG_IS_STMT;
2886 else
2887 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00002888 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00002889 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2890 }
Craig Topperf15655b2013-04-22 04:22:40 +00002891 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00002892 Loc = getTok().getLoc();
2893 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002894 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00002895 return true;
2896 // The expression must be a constant greater or equal to 0.
2897 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2898 int Value = MCE->getValue();
2899 if (Value < 0)
2900 return Error(Loc, "isa number less than zero");
2901 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00002902 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00002903 return Error(Loc, "isa number not a constant value");
2904 }
Craig Topperf15655b2013-04-22 04:22:40 +00002905 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002906 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00002907 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00002908 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00002909 return Error(Loc, "unknown sub-directive in '.loc' directive");
2910 }
2911
2912 if (getLexer().is(AsmToken::EndOfStatement))
2913 break;
2914 }
2915 }
2916
2917 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2918 Isa, Discriminator, StringRef());
2919
2920 return false;
2921}
2922
Jim Grosbach4b905842013-09-20 23:08:21 +00002923/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00002924/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00002925bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00002926 return TokError("unsupported directive '.stabs'");
2927}
2928
Jim Grosbach4b905842013-09-20 23:08:21 +00002929/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00002930/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00002931bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00002932 StringRef Name;
2933 bool EH = false;
2934 bool Debug = false;
2935
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002936 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00002937 return TokError("Expected an identifier");
2938
2939 if (Name == ".eh_frame")
2940 EH = true;
2941 else if (Name == ".debug_frame")
2942 Debug = true;
2943
2944 if (getLexer().is(AsmToken::Comma)) {
2945 Lex();
2946
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002947 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00002948 return TokError("Expected an identifier");
2949
2950 if (Name == ".eh_frame")
2951 EH = true;
2952 else if (Name == ".debug_frame")
2953 Debug = true;
2954 }
2955
2956 getStreamer().EmitCFISections(EH, Debug);
2957 return false;
2958}
2959
Jim Grosbach4b905842013-09-20 23:08:21 +00002960/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00002961/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00002962bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00002963 StringRef Simple;
2964 if (getLexer().isNot(AsmToken::EndOfStatement))
2965 if (parseIdentifier(Simple) || Simple != "simple")
2966 return TokError("unexpected token in .cfi_startproc directive");
2967
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00002968 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00002969 return false;
2970}
2971
Jim Grosbach4b905842013-09-20 23:08:21 +00002972/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00002973/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00002974bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00002975 getStreamer().EmitCFIEndProc();
2976 return false;
2977}
2978
Jim Grosbach4b905842013-09-20 23:08:21 +00002979/// \brief parse register name or number.
2980bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00002981 SMLoc DirectiveLoc) {
2982 unsigned RegNo;
2983
2984 if (getLexer().isNot(AsmToken::Integer)) {
2985 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2986 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00002987 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00002988 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002989 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00002990
2991 return false;
2992}
2993
Jim Grosbach4b905842013-09-20 23:08:21 +00002994/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00002995/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00002996bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00002997 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00002998 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00002999 return true;
3000
3001 if (getLexer().isNot(AsmToken::Comma))
3002 return TokError("unexpected token in directive");
3003 Lex();
3004
3005 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003006 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003007 return true;
3008
3009 getStreamer().EmitCFIDefCfa(Register, Offset);
3010 return false;
3011}
3012
Jim Grosbach4b905842013-09-20 23:08:21 +00003013/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003014/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003015bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003016 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003017 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003018 return true;
3019
3020 getStreamer().EmitCFIDefCfaOffset(Offset);
3021 return false;
3022}
3023
Jim Grosbach4b905842013-09-20 23:08:21 +00003024/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003025/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003026bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003027 int64_t Register1 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003028 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003029 return true;
3030
3031 if (getLexer().isNot(AsmToken::Comma))
3032 return TokError("unexpected token in directive");
3033 Lex();
3034
3035 int64_t Register2 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003036 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003037 return true;
3038
3039 getStreamer().EmitCFIRegister(Register1, Register2);
3040 return false;
3041}
3042
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003043/// parseDirectiveCFIWindowSave
3044/// ::= .cfi_window_save
3045bool AsmParser::parseDirectiveCFIWindowSave() {
3046 getStreamer().EmitCFIWindowSave();
3047 return false;
3048}
3049
Jim Grosbach4b905842013-09-20 23:08:21 +00003050/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003051/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003052bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003053 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003054 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003055 return true;
3056
3057 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3058 return false;
3059}
3060
Jim Grosbach4b905842013-09-20 23:08:21 +00003061/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003062/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003063bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003064 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003065 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003066 return true;
3067
3068 getStreamer().EmitCFIDefCfaRegister(Register);
3069 return false;
3070}
3071
Jim Grosbach4b905842013-09-20 23:08:21 +00003072/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003073/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003074bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003075 int64_t Register = 0;
3076 int64_t Offset = 0;
3077
Jim Grosbach4b905842013-09-20 23:08:21 +00003078 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003079 return true;
3080
3081 if (getLexer().isNot(AsmToken::Comma))
3082 return TokError("unexpected token in directive");
3083 Lex();
3084
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003085 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003086 return true;
3087
3088 getStreamer().EmitCFIOffset(Register, Offset);
3089 return false;
3090}
3091
Jim Grosbach4b905842013-09-20 23:08:21 +00003092/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003093/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003094bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003095 int64_t Register = 0;
3096
Jim Grosbach4b905842013-09-20 23:08:21 +00003097 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003098 return true;
3099
3100 if (getLexer().isNot(AsmToken::Comma))
3101 return TokError("unexpected token in directive");
3102 Lex();
3103
3104 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003105 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003106 return true;
3107
3108 getStreamer().EmitCFIRelOffset(Register, Offset);
3109 return false;
3110}
3111
3112static bool isValidEncoding(int64_t Encoding) {
3113 if (Encoding & ~0xff)
3114 return false;
3115
3116 if (Encoding == dwarf::DW_EH_PE_omit)
3117 return true;
3118
3119 const unsigned Format = Encoding & 0xf;
3120 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3121 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3122 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3123 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3124 return false;
3125
3126 const unsigned Application = Encoding & 0x70;
3127 if (Application != dwarf::DW_EH_PE_absptr &&
3128 Application != dwarf::DW_EH_PE_pcrel)
3129 return false;
3130
3131 return true;
3132}
3133
Jim Grosbach4b905842013-09-20 23:08:21 +00003134/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003135/// IsPersonality true for cfi_personality, false for cfi_lsda
3136/// ::= .cfi_personality encoding, [symbol_name]
3137/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003138bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003139 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003140 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003141 return true;
3142 if (Encoding == dwarf::DW_EH_PE_omit)
3143 return false;
3144
3145 if (!isValidEncoding(Encoding))
3146 return TokError("unsupported encoding.");
3147
3148 if (getLexer().isNot(AsmToken::Comma))
3149 return TokError("unexpected token in directive");
3150 Lex();
3151
3152 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003153 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003154 return TokError("expected identifier in directive");
3155
Jim Grosbach6f482002015-05-18 18:43:14 +00003156 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003157
3158 if (IsPersonality)
3159 getStreamer().EmitCFIPersonality(Sym, Encoding);
3160 else
3161 getStreamer().EmitCFILsda(Sym, Encoding);
3162 return false;
3163}
3164
Jim Grosbach4b905842013-09-20 23:08:21 +00003165/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003166/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003167bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003168 getStreamer().EmitCFIRememberState();
3169 return false;
3170}
3171
Jim Grosbach4b905842013-09-20 23:08:21 +00003172/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003173/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003174bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003175 getStreamer().EmitCFIRestoreState();
3176 return false;
3177}
3178
Jim Grosbach4b905842013-09-20 23:08:21 +00003179/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003180/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003181bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003182 int64_t Register = 0;
3183
Jim Grosbach4b905842013-09-20 23:08:21 +00003184 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003185 return true;
3186
3187 getStreamer().EmitCFISameValue(Register);
3188 return false;
3189}
3190
Jim Grosbach4b905842013-09-20 23:08:21 +00003191/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003192/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003193bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003194 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003195 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003196 return true;
3197
3198 getStreamer().EmitCFIRestore(Register);
3199 return false;
3200}
3201
Jim Grosbach4b905842013-09-20 23:08:21 +00003202/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003203/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003204bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003205 std::string Values;
3206 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003207 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003208 return true;
3209
3210 Values.push_back((uint8_t)CurrValue);
3211
3212 while (getLexer().is(AsmToken::Comma)) {
3213 Lex();
3214
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003215 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003216 return true;
3217
3218 Values.push_back((uint8_t)CurrValue);
3219 }
3220
3221 getStreamer().EmitCFIEscape(Values);
3222 return false;
3223}
3224
Jim Grosbach4b905842013-09-20 23:08:21 +00003225/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003226/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003227bool AsmParser::parseDirectiveCFISignalFrame() {
Eli Bendersky17233942013-01-15 22:59:42 +00003228 if (getLexer().isNot(AsmToken::EndOfStatement))
3229 return Error(getLexer().getLoc(),
3230 "unexpected token in '.cfi_signal_frame'");
3231
3232 getStreamer().EmitCFISignalFrame();
3233 return false;
3234}
3235
Jim Grosbach4b905842013-09-20 23:08:21 +00003236/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003237/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003238bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003239 int64_t Register = 0;
3240
Jim Grosbach4b905842013-09-20 23:08:21 +00003241 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003242 return true;
3243
3244 getStreamer().EmitCFIUndefined(Register);
3245 return false;
3246}
3247
Jim Grosbach4b905842013-09-20 23:08:21 +00003248/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003249/// ::= .macros_on
3250/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003251bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003252 if (getLexer().isNot(AsmToken::EndOfStatement))
3253 return Error(getLexer().getLoc(),
3254 "unexpected token in '" + Directive + "' directive");
3255
Jim Grosbach4b905842013-09-20 23:08:21 +00003256 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003257 return false;
3258}
3259
Jim Grosbach4b905842013-09-20 23:08:21 +00003260/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003261/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003262bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003263 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003264 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003265 return TokError("expected identifier in '.macro' directive");
3266
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003267 if (getLexer().is(AsmToken::Comma))
3268 Lex();
3269
Eli Bendersky17233942013-01-15 22:59:42 +00003270 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003271 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003272
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003273 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003274 return Error(Lexer.getLoc(),
3275 "Vararg parameter '" + Parameters.back().Name +
3276 "' should be last one in the list of parameters.");
3277
David Majnemer91fc4c22014-01-29 18:57:46 +00003278 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003279 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003280 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003281
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003282 if (Lexer.is(AsmToken::Colon)) {
3283 Lex(); // consume ':'
3284
3285 SMLoc QualLoc;
3286 StringRef Qualifier;
3287
3288 QualLoc = Lexer.getLoc();
3289 if (parseIdentifier(Qualifier))
3290 return Error(QualLoc, "missing parameter qualifier for "
3291 "'" + Parameter.Name + "' in macro '" + Name + "'");
3292
3293 if (Qualifier == "req")
3294 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003295 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003296 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003297 else
3298 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3299 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3300 }
3301
David Majnemer91fc4c22014-01-29 18:57:46 +00003302 if (getLexer().is(AsmToken::Equal)) {
3303 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003304
3305 SMLoc ParamLoc;
3306
3307 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003308 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003309 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003310
3311 if (Parameter.Required)
3312 Warning(ParamLoc, "pointless default value for required parameter "
3313 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003314 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003315
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003316 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003317
3318 if (getLexer().is(AsmToken::Comma))
3319 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003320 }
3321
3322 // Eat the end of statement.
3323 Lex();
3324
3325 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003326 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003327
3328 // Lex the macro definition.
3329 for (;;) {
3330 // Check whether we have reached the end of the file.
3331 if (getLexer().is(AsmToken::Eof))
3332 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3333
3334 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003335 if (getLexer().is(AsmToken::Identifier)) {
3336 if (getTok().getIdentifier() == ".endm" ||
3337 getTok().getIdentifier() == ".endmacro") {
3338 if (MacroDepth == 0) { // Outermost macro.
3339 EndToken = getTok();
3340 Lex();
3341 if (getLexer().isNot(AsmToken::EndOfStatement))
3342 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3343 "' directive");
3344 break;
3345 } else {
3346 // Otherwise we just found the end of an inner macro.
3347 --MacroDepth;
3348 }
3349 } else if (getTok().getIdentifier() == ".macro") {
3350 // We allow nested macros. Those aren't instantiated until the outermost
3351 // macro is expanded so just ignore them for now.
3352 ++MacroDepth;
3353 }
Eli Bendersky17233942013-01-15 22:59:42 +00003354 }
3355
3356 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003357 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003358 }
3359
Jim Grosbach4b905842013-09-20 23:08:21 +00003360 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003361 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3362 }
3363
3364 const char *BodyStart = StartToken.getLoc().getPointer();
3365 const char *BodyEnd = EndToken.getLoc().getPointer();
3366 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003367 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003368 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003369 return false;
3370}
3371
Jim Grosbach4b905842013-09-20 23:08:21 +00003372/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003373///
3374/// With the support added for named parameters there may be code out there that
3375/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003376/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003377/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003378/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003379/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3380/// warning that the positional parameter found in body which have no effect.
3381/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003382/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003383/// intended or change the macro to use the named parameters. It is possible
3384/// this warning will trigger when the none of the named parameters are used
3385/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003386void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003387 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003388 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003389 // If this macro is not defined with named parameters the warning we are
3390 // checking for here doesn't apply.
3391 unsigned NParameters = Parameters.size();
3392 if (NParameters == 0)
3393 return;
3394
3395 bool NamedParametersFound = false;
3396 bool PositionalParametersFound = false;
3397
3398 // Look at the body of the macro for use of both the named parameters and what
3399 // are likely to be positional parameters. This is what expandMacro() is
3400 // doing when it finds the parameters in the body.
3401 while (!Body.empty()) {
3402 // Scan for the next possible parameter.
3403 std::size_t End = Body.size(), Pos = 0;
3404 for (; Pos != End; ++Pos) {
3405 // Check for a substitution or escape.
3406 // This macro is defined with parameters, look for \foo, \bar, etc.
3407 if (Body[Pos] == '\\' && Pos + 1 != End)
3408 break;
3409
3410 // This macro should have parameters, but look for $0, $1, ..., $n too.
3411 if (Body[Pos] != '$' || Pos + 1 == End)
3412 continue;
3413 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00003414 if (Next == '$' || Next == 'n' ||
3415 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00003416 break;
3417 }
3418
3419 // Check if we reached the end.
3420 if (Pos == End)
3421 break;
3422
3423 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00003424 switch (Body[Pos + 1]) {
3425 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00003426 case '$':
3427 break;
3428
Jim Grosbach4b905842013-09-20 23:08:21 +00003429 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00003430 case 'n':
3431 PositionalParametersFound = true;
3432 break;
3433
Jim Grosbach4b905842013-09-20 23:08:21 +00003434 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00003435 default: {
3436 PositionalParametersFound = true;
3437 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00003438 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003439 }
3440 Pos += 2;
3441 } else {
3442 unsigned I = Pos + 1;
3443 while (isIdentifierChar(Body[I]) && I + 1 != End)
3444 ++I;
3445
Jim Grosbach4b905842013-09-20 23:08:21 +00003446 const char *Begin = Body.data() + Pos + 1;
3447 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00003448 unsigned Index = 0;
3449 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003450 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00003451 break;
3452
3453 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00003454 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3455 Pos += 3;
3456 else {
3457 Pos = I;
3458 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003459 } else {
3460 NamedParametersFound = true;
3461 Pos += 1 + Argument.size();
3462 }
3463 }
3464 // Update the scan point.
3465 Body = Body.substr(Pos);
3466 }
3467
3468 if (!NamedParametersFound && PositionalParametersFound)
3469 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3470 "used in macro body, possible positional parameter "
3471 "found in body which will have no effect");
3472}
3473
Nico Weber155dccd12014-07-24 17:08:39 +00003474/// parseDirectiveExitMacro
3475/// ::= .exitm
3476bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3477 if (getLexer().isNot(AsmToken::EndOfStatement))
3478 return TokError("unexpected token in '" + Directive + "' directive");
3479
3480 if (!isInsideMacroInstantiation())
3481 return TokError("unexpected '" + Directive + "' in file, "
3482 "no current macro definition");
3483
3484 // Exit all conditionals that are active in the current macro.
3485 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3486 TheCondState = TheCondStack.back();
3487 TheCondStack.pop_back();
3488 }
3489
3490 handleMacroExit();
3491 return false;
3492}
3493
Jim Grosbach4b905842013-09-20 23:08:21 +00003494/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003495/// ::= .endm
3496/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00003497bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003498 if (getLexer().isNot(AsmToken::EndOfStatement))
3499 return TokError("unexpected token in '" + Directive + "' directive");
3500
3501 // If we are inside a macro instantiation, terminate the current
3502 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00003503 if (isInsideMacroInstantiation()) {
3504 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00003505 return false;
3506 }
3507
3508 // Otherwise, this .endmacro is a stray entry in the file; well formed
3509 // .endmacro directives are handled during the macro definition parsing.
3510 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00003511 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00003512}
3513
Jim Grosbach4b905842013-09-20 23:08:21 +00003514/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003515/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00003516bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003517 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003518 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003519 return TokError("expected identifier in '.purgem' directive");
3520
3521 if (getLexer().isNot(AsmToken::EndOfStatement))
3522 return TokError("unexpected token in '.purgem' directive");
3523
Jim Grosbach4b905842013-09-20 23:08:21 +00003524 if (!lookupMacro(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003525 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3526
Jim Grosbach4b905842013-09-20 23:08:21 +00003527 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003528 return false;
3529}
Eli Benderskyf483ff92012-12-20 19:05:53 +00003530
Jim Grosbach4b905842013-09-20 23:08:21 +00003531/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00003532/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003533bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003534 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003535
3536 // Expect a single argument: an expression that evaluates to a constant
3537 // in the inclusive range 0-30.
3538 SMLoc ExprLoc = getLexer().getLoc();
3539 int64_t AlignSizePow2;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003540 if (parseAbsoluteExpression(AlignSizePow2))
Eli Benderskyf483ff92012-12-20 19:05:53 +00003541 return true;
3542 else if (getLexer().isNot(AsmToken::EndOfStatement))
3543 return TokError("unexpected token after expression in"
3544 " '.bundle_align_mode' directive");
3545 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3546 return Error(ExprLoc,
3547 "invalid bundle alignment size (expected between 0 and 30)");
3548
3549 Lex();
3550
3551 // Because of AlignSizePow2's verified range we can safely truncate it to
3552 // unsigned.
3553 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3554 return false;
3555}
3556
Jim Grosbach4b905842013-09-20 23:08:21 +00003557/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00003558/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00003559bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003560 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00003561 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00003562
Eli Bendersky802b6282013-01-07 21:51:08 +00003563 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3564 StringRef Option;
3565 SMLoc Loc = getTok().getLoc();
3566 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00003567 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00003568
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003569 if (parseIdentifier(Option))
Eli Bendersky802b6282013-01-07 21:51:08 +00003570 return Error(Loc, kInvalidOptionError);
3571
3572 if (Option != "align_to_end")
3573 return Error(Loc, kInvalidOptionError);
3574 else if (getLexer().isNot(AsmToken::EndOfStatement))
3575 return Error(Loc,
3576 "unexpected token after '.bundle_lock' directive option");
3577 AlignToEnd = true;
3578 }
3579
Eli Benderskyf483ff92012-12-20 19:05:53 +00003580 Lex();
3581
Eli Bendersky802b6282013-01-07 21:51:08 +00003582 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00003583 return false;
3584}
3585
Jim Grosbach4b905842013-09-20 23:08:21 +00003586/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00003587/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00003588bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003589 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003590
3591 if (getLexer().isNot(AsmToken::EndOfStatement))
3592 return TokError("unexpected token in '.bundle_unlock' directive");
3593 Lex();
3594
3595 getStreamer().EmitBundleUnlock();
3596 return false;
3597}
3598
Jim Grosbach4b905842013-09-20 23:08:21 +00003599/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00003600/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003601bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003602 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00003603
3604 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003605 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00003606 return true;
3607
3608 int64_t FillExpr = 0;
3609 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3610 if (getLexer().isNot(AsmToken::Comma))
3611 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3612 Lex();
3613
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003614 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00003615 return true;
3616
3617 if (getLexer().isNot(AsmToken::EndOfStatement))
3618 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3619 }
3620
3621 Lex();
3622
3623 if (NumBytes <= 0)
Jim Grosbach4b905842013-09-20 23:08:21 +00003624 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3625 "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003626
3627 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Rafael Espindola64e1af82013-07-02 15:49:13 +00003628 getStreamer().EmitFill(NumBytes, FillExpr);
Eli Bendersky17233942013-01-15 22:59:42 +00003629
3630 return false;
3631}
3632
Jim Grosbach4b905842013-09-20 23:08:21 +00003633/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003634/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003635bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003636 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00003637 const MCExpr *Value;
3638
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003639 for (;;) {
3640 if (parseExpression(Value))
3641 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003642
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003643 if (Signed)
3644 getStreamer().EmitSLEB128Value(Value);
3645 else
3646 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00003647
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003648 if (getLexer().is(AsmToken::EndOfStatement))
3649 break;
3650
3651 if (getLexer().isNot(AsmToken::Comma))
3652 return TokError("unexpected token in directive");
3653 Lex();
3654 }
Eli Bendersky17233942013-01-15 22:59:42 +00003655
3656 return false;
3657}
3658
Jim Grosbach4b905842013-09-20 23:08:21 +00003659/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00003660/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003661bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003662 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara5508c82009-06-30 00:33:19 +00003663 for (;;) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00003664 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003665 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00003666
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003667 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003668 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003669
Jim Grosbach6f482002015-05-18 18:43:14 +00003670 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00003671
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003672 // Assembler local symbols don't make any sense here. Complain loudly.
3673 if (Sym->isTemporary())
3674 return Error(Loc, "non-local symbol required in directive");
3675
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00003676 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3677 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00003678
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003679 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00003680 break;
3681
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003682 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara5508c82009-06-30 00:33:19 +00003683 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00003684 Lex();
Daniel Dunbara5508c82009-06-30 00:33:19 +00003685 }
3686 }
3687
Sean Callanan686ed8d2010-01-19 20:22:31 +00003688 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00003689 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00003690}
Chris Lattnera1e11f52009-07-07 20:30:46 +00003691
Jim Grosbach4b905842013-09-20 23:08:21 +00003692/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00003693/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003694bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003695 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00003696
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003697 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00003698 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003699 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003700 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003701
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00003702 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00003703 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00003704
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003705 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003706 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00003707 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00003708
3709 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003710 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003711 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003712 return true;
3713
3714 int64_t Pow2Alignment = 0;
3715 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003716 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00003717 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003718 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003719 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003720 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003721
Benjamin Kramer68b9f052012-09-07 21:08:01 +00003722 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3723 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00003724 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3725
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00003726 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00003727 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3728 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00003729 if (!isPowerOf2_64(Pow2Alignment))
3730 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3731 Pow2Alignment = Log2_64(Pow2Alignment);
3732 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00003733 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00003734
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003735 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00003736 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003737
Sean Callanan686ed8d2010-01-19 20:22:31 +00003738 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00003739
Chris Lattner28ad7542009-07-09 17:25:12 +00003740 // NOTE: a size of zero for a .comm should create a undefined symbol
3741 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00003742 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00003743 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00003744 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00003745
Eric Christopherbc818852010-05-14 01:38:54 +00003746 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00003747 // may internally end up wanting an alignment in bytes.
3748 // FIXME: Diagnose overflow.
3749 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00003750 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00003751 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00003752
Daniel Dunbar6860ac72009-08-22 07:22:36 +00003753 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00003754 return Error(IDLoc, "invalid symbol redefinition");
3755
Chris Lattner28ad7542009-07-09 17:25:12 +00003756 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00003757 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00003758 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00003759 return false;
3760 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00003761
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003762 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00003763 return false;
3764}
Chris Lattner07cadaf2009-07-10 22:20:30 +00003765
Jim Grosbach4b905842013-09-20 23:08:21 +00003766/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00003767/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003768bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00003769 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003770 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00003771
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003772 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003773 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby56523ce2009-07-13 23:15:14 +00003774 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00003775
Sean Callanan686ed8d2010-01-19 20:22:31 +00003776 Lex();
Kevin Enderby56523ce2009-07-13 23:15:14 +00003777
Daniel Dunbareb6bb322009-07-27 23:20:52 +00003778 if (Str.empty())
3779 Error(Loc, ".abort detected. Assembly stopping.");
3780 else
3781 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00003782 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00003783
3784 return false;
3785}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00003786
Jim Grosbach4b905842013-09-20 23:08:21 +00003787/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003788/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00003789bool AsmParser::parseDirectiveInclude() {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003790 if (getLexer().isNot(AsmToken::String))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003791 return TokError("expected string in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003792
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003793 // Allow the strings to have escaped octal character sequence.
3794 std::string Filename;
3795 if (parseEscapedString(Filename))
3796 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003797 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00003798 Lex();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003799
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003800 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003801 return TokError("unexpected token in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003802
Chris Lattner693fbb82009-07-16 06:14:39 +00003803 // Attempt to switch the lexer to the included file before consuming the end
3804 // of statement to avoid losing it when we switch.
Jim Grosbach4b905842013-09-20 23:08:21 +00003805 if (enterIncludeFile(Filename)) {
Daniel Dunbard8a18452010-07-18 18:31:45 +00003806 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner693fbb82009-07-16 06:14:39 +00003807 return true;
3808 }
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003809
3810 return false;
3811}
Kevin Enderby09ea5702009-07-15 15:30:11 +00003812
Jim Grosbach4b905842013-09-20 23:08:21 +00003813/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00003814/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00003815bool AsmParser::parseDirectiveIncbin() {
Kevin Enderby109f25c2011-12-14 21:47:48 +00003816 if (getLexer().isNot(AsmToken::String))
3817 return TokError("expected string in '.incbin' directive");
3818
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003819 // Allow the strings to have escaped octal character sequence.
3820 std::string Filename;
3821 if (parseEscapedString(Filename))
3822 return true;
Kevin Enderby109f25c2011-12-14 21:47:48 +00003823 SMLoc IncbinLoc = getLexer().getLoc();
3824 Lex();
3825
3826 if (getLexer().isNot(AsmToken::EndOfStatement))
3827 return TokError("unexpected token in '.incbin' directive");
3828
Kevin Enderby109f25c2011-12-14 21:47:48 +00003829 // Attempt to process the included file.
Jim Grosbach4b905842013-09-20 23:08:21 +00003830 if (processIncbinFile(Filename)) {
Kevin Enderby109f25c2011-12-14 21:47:48 +00003831 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3832 return true;
3833 }
3834
3835 return false;
3836}
3837
Jim Grosbach4b905842013-09-20 23:08:21 +00003838/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00003839/// ::= .if{,eq,ge,gt,le,lt,ne} expression
3840bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003841 TheCondStack.push_back(TheCondState);
3842 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003843 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003844 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003845 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003846 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003847 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003848 return true;
3849
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003850 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003851 return TokError("unexpected token in '.if' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003852
Sean Callanan686ed8d2010-01-19 20:22:31 +00003853 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003854
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00003855 switch (DirKind) {
3856 default:
3857 llvm_unreachable("unsupported directive");
3858 case DK_IF:
3859 case DK_IFNE:
3860 break;
3861 case DK_IFEQ:
3862 ExprValue = ExprValue == 0;
3863 break;
3864 case DK_IFGE:
3865 ExprValue = ExprValue >= 0;
3866 break;
3867 case DK_IFGT:
3868 ExprValue = ExprValue > 0;
3869 break;
3870 case DK_IFLE:
3871 ExprValue = ExprValue <= 0;
3872 break;
3873 case DK_IFLT:
3874 ExprValue = ExprValue < 0;
3875 break;
3876 }
3877
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003878 TheCondState.CondMet = ExprValue;
3879 TheCondState.Ignore = !TheCondState.CondMet;
3880 }
3881
3882 return false;
3883}
3884
Jim Grosbach4b905842013-09-20 23:08:21 +00003885/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003886/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00003887bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003888 TheCondStack.push_back(TheCondState);
3889 TheCondState.TheCond = AsmCond::IfCond;
3890
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003891 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003892 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003893 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003894 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003895
3896 if (getLexer().isNot(AsmToken::EndOfStatement))
3897 return TokError("unexpected token in '.ifb' directive");
3898
3899 Lex();
3900
3901 TheCondState.CondMet = ExpectBlank == Str.empty();
3902 TheCondState.Ignore = !TheCondState.CondMet;
3903 }
3904
3905 return false;
3906}
3907
Jim Grosbach4b905842013-09-20 23:08:21 +00003908/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003909/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00003910/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00003911bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003912 TheCondStack.push_back(TheCondState);
3913 TheCondState.TheCond = AsmCond::IfCond;
3914
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003915 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003916 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003917 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00003918 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003919
3920 if (getLexer().isNot(AsmToken::Comma))
3921 return TokError("unexpected token in '.ifc' directive");
3922
3923 Lex();
3924
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003925 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003926
3927 if (getLexer().isNot(AsmToken::EndOfStatement))
3928 return TokError("unexpected token in '.ifc' directive");
3929
3930 Lex();
3931
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00003932 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003933 TheCondState.Ignore = !TheCondState.CondMet;
3934 }
3935
3936 return false;
3937}
3938
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003939/// parseDirectiveIfeqs
3940/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00003941bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003942 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00003943 if (ExpectEqual)
3944 TokError("expected string parameter for '.ifeqs' directive");
3945 else
3946 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003947 eatToEndOfStatement();
3948 return true;
3949 }
3950
3951 StringRef String1 = getTok().getStringContents();
3952 Lex();
3953
3954 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00003955 if (ExpectEqual)
3956 TokError("expected comma after first string for '.ifeqs' directive");
3957 else
3958 TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003959 eatToEndOfStatement();
3960 return true;
3961 }
3962
3963 Lex();
3964
3965 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00003966 if (ExpectEqual)
3967 TokError("expected string parameter for '.ifeqs' directive");
3968 else
3969 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003970 eatToEndOfStatement();
3971 return true;
3972 }
3973
3974 StringRef String2 = getTok().getStringContents();
3975 Lex();
3976
3977 TheCondStack.push_back(TheCondState);
3978 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00003979 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003980 TheCondState.Ignore = !TheCondState.CondMet;
3981
3982 return false;
3983}
3984
Jim Grosbach4b905842013-09-20 23:08:21 +00003985/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003986/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00003987bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00003988 StringRef Name;
3989 TheCondStack.push_back(TheCondState);
3990 TheCondState.TheCond = AsmCond::IfCond;
3991
3992 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003993 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00003994 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003995 if (parseIdentifier(Name))
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00003996 return TokError("expected identifier after '.ifdef'");
3997
3998 Lex();
3999
Jim Grosbach6f482002015-05-18 18:43:14 +00004000 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004001
4002 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004003 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004004 else
Craig Topper353eda42014-04-24 06:44:33 +00004005 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004006 TheCondState.Ignore = !TheCondState.CondMet;
4007 }
4008
4009 return false;
4010}
4011
Jim Grosbach4b905842013-09-20 23:08:21 +00004012/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004013/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004014bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004015 if (TheCondState.TheCond != AsmCond::IfCond &&
4016 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004017 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4018 " an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004019 TheCondState.TheCond = AsmCond::ElseIfCond;
4020
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004021 bool LastIgnoreState = false;
4022 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004023 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004024 if (LastIgnoreState || TheCondState.CondMet) {
4025 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004026 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004027 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004028 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004029 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004030 return true;
4031
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004032 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004033 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004034
Sean Callanan686ed8d2010-01-19 20:22:31 +00004035 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004036 TheCondState.CondMet = ExprValue;
4037 TheCondState.Ignore = !TheCondState.CondMet;
4038 }
4039
4040 return false;
4041}
4042
Jim Grosbach4b905842013-09-20 23:08:21 +00004043/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004044/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004045bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004046 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004047 return TokError("unexpected token in '.else' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004048
Sean Callanan686ed8d2010-01-19 20:22:31 +00004049 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004050
4051 if (TheCondState.TheCond != AsmCond::IfCond &&
4052 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004053 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4054 ".elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004055 TheCondState.TheCond = AsmCond::ElseCond;
4056 bool LastIgnoreState = false;
4057 if (!TheCondStack.empty())
4058 LastIgnoreState = TheCondStack.back().Ignore;
4059 if (LastIgnoreState || TheCondState.CondMet)
4060 TheCondState.Ignore = true;
4061 else
4062 TheCondState.Ignore = false;
4063
4064 return false;
4065}
4066
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004067/// parseDirectiveEnd
4068/// ::= .end
4069bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4070 if (getLexer().isNot(AsmToken::EndOfStatement))
4071 return TokError("unexpected token in '.end' directive");
4072
4073 Lex();
4074
4075 while (Lexer.isNot(AsmToken::Eof))
4076 Lex();
4077
4078 return false;
4079}
4080
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004081/// parseDirectiveError
4082/// ::= .err
4083/// ::= .error [string]
4084bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4085 if (!TheCondStack.empty()) {
4086 if (TheCondStack.back().Ignore) {
4087 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004088 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004089 }
4090 }
4091
4092 if (!WithMessage)
4093 return Error(L, ".err encountered");
4094
4095 StringRef Message = ".error directive invoked in source file";
4096 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4097 if (Lexer.isNot(AsmToken::String)) {
4098 TokError(".error argument must be a string");
4099 eatToEndOfStatement();
4100 return true;
4101 }
4102
4103 Message = getTok().getStringContents();
4104 Lex();
4105 }
4106
4107 Error(L, Message);
4108 return true;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004109}
4110
Nico Weber404012b2014-07-24 16:26:06 +00004111/// parseDirectiveWarning
4112/// ::= .warning [string]
4113bool AsmParser::parseDirectiveWarning(SMLoc L) {
4114 if (!TheCondStack.empty()) {
4115 if (TheCondStack.back().Ignore) {
4116 eatToEndOfStatement();
4117 return false;
4118 }
4119 }
4120
4121 StringRef Message = ".warning directive invoked in source file";
4122 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4123 if (Lexer.isNot(AsmToken::String)) {
4124 TokError(".warning argument must be a string");
4125 eatToEndOfStatement();
4126 return true;
4127 }
4128
4129 Message = getTok().getStringContents();
4130 Lex();
4131 }
4132
4133 Warning(L, Message);
4134 return false;
4135}
4136
Jim Grosbach4b905842013-09-20 23:08:21 +00004137/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004138/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004139bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004140 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004141 return TokError("unexpected token in '.endif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004142
Sean Callanan686ed8d2010-01-19 20:22:31 +00004143 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004144
Jim Grosbach4b905842013-09-20 23:08:21 +00004145 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004146 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4147 ".else");
4148 if (!TheCondStack.empty()) {
4149 TheCondState = TheCondStack.back();
4150 TheCondStack.pop_back();
4151 }
4152
4153 return false;
4154}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004155
Eli Bendersky17233942013-01-15 22:59:42 +00004156void AsmParser::initializeDirectiveKindMap() {
4157 DirectiveKindMap[".set"] = DK_SET;
4158 DirectiveKindMap[".equ"] = DK_EQU;
4159 DirectiveKindMap[".equiv"] = DK_EQUIV;
4160 DirectiveKindMap[".ascii"] = DK_ASCII;
4161 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4162 DirectiveKindMap[".string"] = DK_STRING;
4163 DirectiveKindMap[".byte"] = DK_BYTE;
4164 DirectiveKindMap[".short"] = DK_SHORT;
4165 DirectiveKindMap[".value"] = DK_VALUE;
4166 DirectiveKindMap[".2byte"] = DK_2BYTE;
4167 DirectiveKindMap[".long"] = DK_LONG;
4168 DirectiveKindMap[".int"] = DK_INT;
4169 DirectiveKindMap[".4byte"] = DK_4BYTE;
4170 DirectiveKindMap[".quad"] = DK_QUAD;
4171 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004172 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004173 DirectiveKindMap[".single"] = DK_SINGLE;
4174 DirectiveKindMap[".float"] = DK_FLOAT;
4175 DirectiveKindMap[".double"] = DK_DOUBLE;
4176 DirectiveKindMap[".align"] = DK_ALIGN;
4177 DirectiveKindMap[".align32"] = DK_ALIGN32;
4178 DirectiveKindMap[".balign"] = DK_BALIGN;
4179 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4180 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4181 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4182 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4183 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4184 DirectiveKindMap[".org"] = DK_ORG;
4185 DirectiveKindMap[".fill"] = DK_FILL;
4186 DirectiveKindMap[".zero"] = DK_ZERO;
4187 DirectiveKindMap[".extern"] = DK_EXTERN;
4188 DirectiveKindMap[".globl"] = DK_GLOBL;
4189 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004190 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4191 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4192 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4193 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4194 DirectiveKindMap[".reference"] = DK_REFERENCE;
4195 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4196 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4197 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4198 DirectiveKindMap[".comm"] = DK_COMM;
4199 DirectiveKindMap[".common"] = DK_COMMON;
4200 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4201 DirectiveKindMap[".abort"] = DK_ABORT;
4202 DirectiveKindMap[".include"] = DK_INCLUDE;
4203 DirectiveKindMap[".incbin"] = DK_INCBIN;
4204 DirectiveKindMap[".code16"] = DK_CODE16;
4205 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4206 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004207 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004208 DirectiveKindMap[".irp"] = DK_IRP;
4209 DirectiveKindMap[".irpc"] = DK_IRPC;
4210 DirectiveKindMap[".endr"] = DK_ENDR;
4211 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4212 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4213 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4214 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004215 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4216 DirectiveKindMap[".ifge"] = DK_IFGE;
4217 DirectiveKindMap[".ifgt"] = DK_IFGT;
4218 DirectiveKindMap[".ifle"] = DK_IFLE;
4219 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004220 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004221 DirectiveKindMap[".ifb"] = DK_IFB;
4222 DirectiveKindMap[".ifnb"] = DK_IFNB;
4223 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004224 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004225 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004226 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004227 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4228 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4229 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4230 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4231 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004232 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004233 DirectiveKindMap[".endif"] = DK_ENDIF;
4234 DirectiveKindMap[".skip"] = DK_SKIP;
4235 DirectiveKindMap[".space"] = DK_SPACE;
4236 DirectiveKindMap[".file"] = DK_FILE;
4237 DirectiveKindMap[".line"] = DK_LINE;
4238 DirectiveKindMap[".loc"] = DK_LOC;
4239 DirectiveKindMap[".stabs"] = DK_STABS;
4240 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4241 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4242 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4243 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4244 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4245 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4246 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4247 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4248 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4249 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4250 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4251 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4252 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4253 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4254 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4255 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4256 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4257 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4258 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4259 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4260 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004261 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004262 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4263 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4264 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004265 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004266 DirectiveKindMap[".endm"] = DK_ENDM;
4267 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4268 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004269 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004270 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004271 DirectiveKindMap[".warning"] = DK_WARNING;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004272}
4273
Jim Grosbach4b905842013-09-20 23:08:21 +00004274MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004275 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004276
Rafael Espindola34b9c512012-06-03 23:57:14 +00004277 unsigned NestLevel = 0;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004278 for (;;) {
4279 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004280 if (getLexer().is(AsmToken::Eof)) {
4281 Error(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004282 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004283 }
4284
Rafael Espindola34b9c512012-06-03 23:57:14 +00004285 if (Lexer.is(AsmToken::Identifier) &&
4286 (getTok().getIdentifier() == ".rept")) {
4287 ++NestLevel;
4288 }
4289
4290 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004291 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004292 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004293 EndToken = getTok();
4294 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004295 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4296 TokError("unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004297 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004298 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004299 break;
4300 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004301 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004302 }
4303
Rafael Espindola34b9c512012-06-03 23:57:14 +00004304 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004305 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004306 }
4307
4308 const char *BodyStart = StartToken.getLoc().getPointer();
4309 const char *BodyEnd = EndToken.getLoc().getPointer();
4310 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4311
Rafael Espindola34b9c512012-06-03 23:57:14 +00004312 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004313 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004314 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004315}
4316
Jim Grosbach4b905842013-09-20 23:08:21 +00004317void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004318 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004319 OS << ".endr\n";
4320
Rafael Espindola3560ff22014-08-27 20:03:13 +00004321 std::unique_ptr<MemoryBuffer> Instantiation =
4322 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004323
Rafael Espindola34b9c512012-06-03 23:57:14 +00004324 // Create the macro instantiation object and add to the current macro
4325 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004326 MacroInstantiation *MI = new MacroInstantiation(
4327 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004328 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004329
Rafael Espindola34b9c512012-06-03 23:57:14 +00004330 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004331 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004332 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004333 Lex();
4334}
4335
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004336/// parseDirectiveRept
4337/// ::= .rep | .rept count
4338bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004339 const MCExpr *CountExpr;
4340 SMLoc CountLoc = getTok().getLoc();
4341 if (parseExpression(CountExpr))
4342 return true;
4343
Rafael Espindola34b9c512012-06-03 23:57:14 +00004344 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004345 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004346 eatToEndOfStatement();
4347 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4348 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004349
4350 if (Count < 0)
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004351 return Error(CountLoc, "Count is negative");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004352
4353 if (Lexer.isNot(AsmToken::EndOfStatement))
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004354 return TokError("unexpected token in '" + Dir + "' directive");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004355
4356 // Eat the end of statement.
4357 Lex();
4358
4359 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004360 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00004361 if (!M)
4362 return true;
4363
4364 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4365 // to hold the macro body with substitutions.
4366 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004367 raw_svector_ostream OS(Buf);
4368 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004369 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4370 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004371 return true;
4372 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004373 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004374
4375 return false;
4376}
4377
Jim Grosbach4b905842013-09-20 23:08:21 +00004378/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004379/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004380bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004381 MCAsmMacroParameter Parameter;
Rafael Espindola768b41c2012-06-15 14:02:34 +00004382
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004383 if (parseIdentifier(Parameter.Name))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004384 return TokError("expected identifier in '.irp' directive");
4385
Rafael Espindola768b41c2012-06-15 14:02:34 +00004386 if (Lexer.isNot(AsmToken::Comma))
4387 return TokError("expected comma in '.irp' directive");
4388
4389 Lex();
4390
Eli Bendersky38274122013-01-14 23:22:36 +00004391 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004392 if (parseMacroArguments(nullptr, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004393 return true;
4394
4395 // Eat the end of statement.
4396 Lex();
4397
4398 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004399 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004400 if (!M)
4401 return true;
4402
4403 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4404 // to hold the macro body with substitutions.
4405 SmallString<256> Buf;
4406 raw_svector_ostream OS(Buf);
4407
Eli Bendersky38274122013-01-14 23:22:36 +00004408 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004409 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4410 // This is undocumented, but GAS seems to support it.
4411 if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004412 return true;
4413 }
4414
Jim Grosbach4b905842013-09-20 23:08:21 +00004415 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004416
4417 return false;
4418}
4419
Jim Grosbach4b905842013-09-20 23:08:21 +00004420/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004421/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004422bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004423 MCAsmMacroParameter Parameter;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004424
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004425 if (parseIdentifier(Parameter.Name))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004426 return TokError("expected identifier in '.irpc' directive");
4427
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004428 if (Lexer.isNot(AsmToken::Comma))
4429 return TokError("expected comma in '.irpc' directive");
4430
4431 Lex();
4432
Eli Bendersky38274122013-01-14 23:22:36 +00004433 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004434 if (parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004435 return true;
4436
4437 if (A.size() != 1 || A.front().size() != 1)
4438 return TokError("unexpected token in '.irpc' directive");
4439
4440 // Eat the end of statement.
4441 Lex();
4442
4443 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004444 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004445 if (!M)
4446 return true;
4447
4448 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4449 // to hold the macro body with substitutions.
4450 SmallString<256> Buf;
4451 raw_svector_ostream OS(Buf);
4452
4453 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004454 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00004455 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004456 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004457
Toma Tabacu217116e2015-04-27 10:50:29 +00004458 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4459 // This is undocumented, but GAS seems to support it.
4460 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004461 return true;
4462 }
4463
Jim Grosbach4b905842013-09-20 23:08:21 +00004464 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004465
4466 return false;
4467}
4468
Jim Grosbach4b905842013-09-20 23:08:21 +00004469bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004470 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00004471 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004472
4473 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00004474 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004475 assert(getLexer().is(AsmToken::EndOfStatement));
4476
Jim Grosbach4b905842013-09-20 23:08:21 +00004477 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004478 return false;
4479}
Rafael Espindola12d73d12010-09-11 16:45:15 +00004480
Jim Grosbach4b905842013-09-20 23:08:21 +00004481bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00004482 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004483 const MCExpr *Value;
4484 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004485 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004486 return true;
4487 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4488 if (!MCE)
4489 return Error(ExprLoc, "unexpected expression in _emit");
4490 uint64_t IntValue = MCE->getValue();
4491 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4492 return Error(ExprLoc, "literal value out of range for directive");
4493
Chad Rosierc7f552c2013-02-12 21:33:51 +00004494 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4495 return false;
4496}
4497
Jim Grosbach4b905842013-09-20 23:08:21 +00004498bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00004499 const MCExpr *Value;
4500 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004501 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00004502 return true;
4503 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4504 if (!MCE)
4505 return Error(ExprLoc, "unexpected expression in align");
4506 uint64_t IntValue = MCE->getValue();
4507 if (!isPowerOf2_64(IntValue))
4508 return Error(ExprLoc, "literal value not a power of two greater then zero");
4509
Jim Grosbach4b905842013-09-20 23:08:21 +00004510 Info.AsmRewrites->push_back(
4511 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
Eli Friedman0f4871d2012-10-22 23:58:19 +00004512 return false;
4513}
4514
Chad Rosierf43fcf52013-02-13 21:27:17 +00004515// We are comparing pointers, but the pointers are relative to a single string.
4516// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00004517static int rewritesSort(const AsmRewrite *AsmRewriteA,
4518 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00004519 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4520 return -1;
4521 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4522 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004523
Chad Rosierfce4fab2013-04-08 17:43:47 +00004524 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4525 // rewrite to the same location. Make sure the SizeDirective rewrite is
4526 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4527 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00004528 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4529 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004530 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00004531
Jim Grosbach4b905842013-09-20 23:08:21 +00004532 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4533 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004534 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00004535 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00004536}
4537
Jim Grosbach4b905842013-09-20 23:08:21 +00004538bool AsmParser::parseMSInlineAsm(
4539 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4540 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4541 SmallVectorImpl<std::string> &Constraints,
4542 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4543 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00004544 SmallVector<void *, 4> InputDecls;
4545 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00004546 SmallVector<bool, 4> InputDeclsAddressOf;
4547 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00004548 SmallVector<std::string, 4> InputConstraints;
4549 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00004550 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00004551
Benjamin Kramer1a136112013-02-15 20:37:21 +00004552 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00004553
4554 // Prime the lexer.
4555 Lex();
4556
4557 // While we have input, parse each statement.
4558 unsigned InputIdx = 0;
4559 unsigned OutputIdx = 0;
4560 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004561 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004562 if (parseStatement(Info, &SI))
Chad Rosierf1f6a722012-10-19 22:57:33 +00004563 return true;
Chad Rosier8bce6642012-10-18 15:49:34 +00004564
Chad Rosier149e8e02012-12-12 22:45:52 +00004565 if (Info.ParseError)
4566 return true;
4567
Benjamin Kramer1a136112013-02-15 20:37:21 +00004568 if (Info.Opcode == ~0U)
4569 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004570
Benjamin Kramer1a136112013-02-15 20:37:21 +00004571 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00004572
Benjamin Kramer1a136112013-02-15 20:37:21 +00004573 // Build the list of clobbers, outputs and inputs.
4574 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00004575 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004576
Benjamin Kramer1a136112013-02-15 20:37:21 +00004577 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00004578 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00004579 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004580
Benjamin Kramer1a136112013-02-15 20:37:21 +00004581 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00004582 if (Operand.isReg() && !Operand.needAddressOf() &&
4583 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00004584 unsigned NumDefs = Desc.getNumDefs();
4585 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00004586 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4587 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004588 continue;
4589 }
4590
4591 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00004592 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00004593 if (SymName.empty())
4594 continue;
4595
David Blaikie960ea3f2014-06-08 16:18:35 +00004596 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00004597 if (!OpDecl)
4598 continue;
4599
4600 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00004601 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004602 if (isOutput) {
4603 ++InputIdx;
4604 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004605 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00004606 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Chad Rosiere81309b2013-04-09 17:53:49 +00004607 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer1a136112013-02-15 20:37:21 +00004608 } else {
4609 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004610 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4611 InputConstraints.push_back(Operand.getConstraint().str());
Chad Rosiere81309b2013-04-09 17:53:49 +00004612 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosier8bce6642012-10-18 15:49:34 +00004613 }
Chad Rosier8bce6642012-10-18 15:49:34 +00004614 }
Reid Kleckneree088972013-12-10 18:27:32 +00004615
4616 // Consider implicit defs to be clobbers. Think of cpuid and push.
David Majnemer8114c1a2014-06-23 02:17:16 +00004617 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4618 Desc.getNumImplicitDefs());
4619 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00004620 }
4621
4622 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00004623 NumOutputs = OutputDecls.size();
4624 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00004625
4626 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00004627 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4628 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4629 ClobberRegs.end());
4630 Clobbers.assign(ClobberRegs.size(), std::string());
4631 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4632 raw_string_ostream OS(Clobbers[I]);
4633 IP->printRegName(OS, ClobberRegs[I]);
4634 }
Chad Rosier8bce6642012-10-18 15:49:34 +00004635
4636 // Merge the various outputs and inputs. Output are expected first.
4637 if (NumOutputs || NumInputs) {
4638 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00004639 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00004640 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00004641 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00004642 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00004643 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004644 }
4645 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00004646 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00004647 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004648 }
4649 }
4650
4651 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00004652 std::string AsmStringIR;
4653 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00004654 StringRef ASMString =
4655 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4656 const char *AsmStart = ASMString.begin();
4657 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00004658 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00004659 for (const AsmRewrite &AR : AsmStrRewrites) {
4660 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00004661 if (Kind == AOK_Delete)
4662 continue;
4663
David Majnemer8114c1a2014-06-23 02:17:16 +00004664 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00004665 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00004666
Chad Rosier120eefd2013-03-19 17:32:17 +00004667 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00004668 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00004669 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00004670
Chad Rosier37e755c2012-10-23 17:43:43 +00004671 // Skip the original expression.
4672 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00004673 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00004674 continue;
4675 }
4676
Chad Rosierff10ed12013-04-12 16:26:42 +00004677 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00004678 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00004679 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004680 default:
4681 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00004682 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00004683 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00004684 break;
4685 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00004686 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00004687 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004688 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00004689 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004690 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00004691 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00004692 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00004693 break;
4694 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00004695 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00004696 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00004697 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00004698 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00004699 default: break;
4700 case 8: OS << "byte ptr "; break;
4701 case 16: OS << "word ptr "; break;
4702 case 32: OS << "dword ptr "; break;
4703 case 64: OS << "qword ptr "; break;
4704 case 80: OS << "xword ptr "; break;
4705 case 128: OS << "xmmword ptr "; break;
4706 case 256: OS << "ymmword ptr "; break;
4707 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00004708 break;
4709 case AOK_Emit:
4710 OS << ".byte";
4711 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00004712 case AOK_Align: {
David Majnemer8114c1a2014-06-23 02:17:16 +00004713 unsigned Val = AR.Val;
Chad Rosierc7f552c2013-02-12 21:33:51 +00004714 OS << ".align " << Val;
4715
4716 // Skip the original immediate.
Benjamin Kramer1a136112013-02-15 20:37:21 +00004717 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00004718 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4719 break;
4720 }
Chad Rosierf0e87202012-10-25 20:41:34 +00004721 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00004722 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00004723 OS.flush();
4724 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00004725 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00004726 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00004727 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00004728 }
Chad Rosier0f48c552012-10-19 20:57:14 +00004729
Chad Rosier8bce6642012-10-18 15:49:34 +00004730 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00004731 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00004732 }
4733
4734 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00004735 if (AsmStart != AsmEnd)
4736 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00004737
4738 AsmString = OS.str();
4739 return false;
4740}
4741
Pete Cooper80d21cb2015-06-22 19:35:57 +00004742namespace llvm {
4743namespace MCParserUtils {
4744
4745/// Returns whether the given symbol is used anywhere in the given expression,
4746/// or subexpressions.
4747static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
4748 switch (Value->getKind()) {
4749 case MCExpr::Binary: {
4750 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
4751 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
4752 isSymbolUsedInExpression(Sym, BE->getRHS());
4753 }
4754 case MCExpr::Target:
4755 case MCExpr::Constant:
4756 return false;
4757 case MCExpr::SymbolRef: {
4758 const MCSymbol &S =
4759 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
4760 if (S.isVariable())
4761 return isSymbolUsedInExpression(Sym, S.getVariableValue());
4762 return &S == Sym;
4763 }
4764 case MCExpr::Unary:
4765 return isSymbolUsedInExpression(
4766 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
4767 }
4768
4769 llvm_unreachable("Unknown expr kind!");
4770}
4771
4772bool parseAssignmentExpression(StringRef Name, bool allow_redef,
4773 MCAsmParser &Parser, MCSymbol *&Sym,
4774 const MCExpr *&Value) {
4775 MCAsmLexer &Lexer = Parser.getLexer();
4776
4777 // FIXME: Use better location, we should use proper tokens.
4778 SMLoc EqualLoc = Lexer.getLoc();
4779
4780 if (Parser.parseExpression(Value)) {
4781 Parser.TokError("missing expression");
4782 Parser.eatToEndOfStatement();
4783 return true;
4784 }
4785
4786 // Note: we don't count b as used in "a = b". This is to allow
4787 // a = b
4788 // b = c
4789
4790 if (Lexer.isNot(AsmToken::EndOfStatement))
4791 return Parser.TokError("unexpected token in assignment");
4792
4793 // Eat the end of statement marker.
4794 Parser.Lex();
4795
4796 // Validate that the LHS is allowed to be a variable (either it has not been
4797 // used as a symbol, or it is an absolute symbol).
4798 Sym = Parser.getContext().lookupSymbol(Name);
4799 if (Sym) {
4800 // Diagnose assignment to a label.
4801 //
4802 // FIXME: Diagnostics. Note the location of the definition as a label.
4803 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
4804 if (isSymbolUsedInExpression(Sym, Value))
4805 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
4806 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
4807 ; // Allow redefinitions of undefined symbols only used in directives.
4808 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
4809 ; // Allow redefinitions of variables that haven't yet been used.
4810 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
4811 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
4812 else if (!Sym->isVariable())
4813 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
4814 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
4815 return Parser.Error(EqualLoc,
4816 "invalid reassignment of non-absolute variable '" +
4817 Name + "'");
4818
4819 // Don't count these checks as uses.
4820 Sym->setUsed(false);
4821 } else if (Name == ".") {
4822 if (Parser.getStreamer().EmitValueToOffset(Value, 0)) {
4823 Parser.Error(EqualLoc, "expected absolute expression");
4824 Parser.eatToEndOfStatement();
4825 return true;
4826 }
4827 return false;
4828 } else
4829 Sym = Parser.getContext().getOrCreateSymbol(Name);
4830
4831 Sym->setRedefinable(allow_redef);
4832
4833 return false;
4834}
4835
4836} // namespace MCParserUtils
4837} // namespace llvm
4838
Daniel Dunbar01e36072010-07-17 02:26:10 +00004839/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00004840MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4841 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00004842 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00004843}