blob: 6c11a821d4c17862b25f45af8fbb2dd83692526c [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"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/STLExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000021#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000023#include "llvm/ADT/Twine.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000024#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000025#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000026#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000027#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000028#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000029#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000030#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000031#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000033#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000034#include "llvm/MC/MCParser/AsmCond.h"
35#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000036#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000037#include "llvm/MC/MCParser/MCAsmParser.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000038#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000039#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000040#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000041#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000042#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000043#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000044#include "llvm/MC/MCSymbol.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000045#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000046#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000047#include "llvm/Support/CommandLine.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000048#include "llvm/Support/Dwarf.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000049#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000050#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000051#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000052#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000053#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000054#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000055#include <algorithm>
56#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000057#include <cctype>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000058#include <cstddef>
59#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000060#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000061#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000062#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000063#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000064#include <tuple>
65#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000066#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000067
Chris Lattnerb0133452009-06-21 20:16:42 +000068using namespace llvm;
69
Eric Christophera7c32732012-12-18 00:30:54 +000070MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewyckyac612272012-10-19 07:00:09 +000071
Davide Italiano7c9fc732016-07-27 05:51:56 +000072static cl::opt<unsigned> AsmMacroMaxNestingDepth(
73 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
74 cl::desc("The maximum nesting depth allowed for assembly macros."));
75
Daniel Dunbar86033402010-07-12 17:54:38 +000076namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000077
Eli Benderskya313ae62013-01-16 18:56:50 +000078/// \brief Helper types for tracking macro definitions.
79typedef std::vector<AsmToken> MCAsmMacroArgument;
80typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000081
82struct MCAsmMacroParameter {
83 StringRef Name;
84 MCAsmMacroArgument Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000085 bool Required;
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000086 bool Vararg;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000087
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000088 MCAsmMacroParameter() : Required(false), Vararg(false) {}
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000089};
90
Eli Benderskya313ae62013-01-16 18:56:50 +000091typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
92
93struct MCAsmMacro {
94 StringRef Name;
95 StringRef Body;
96 MCAsmMacroParameters Parameters;
97
98public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +000099 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
100 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +0000101};
102
Daniel Dunbar43235712010-07-18 18:54:11 +0000103/// \brief Helper class for storing information about an active macro
104/// instantiation.
105struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +0000106 /// The location of the instantiation.
107 SMLoc InstantiationLoc;
108
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000109 /// The buffer where parsing should resume upon instantiation completion.
110 int ExitBuffer;
111
Daniel Dunbar43235712010-07-18 18:54:11 +0000112 /// The location where parsing should resume upon instantiation completion.
113 SMLoc ExitLoc;
114
Nico Weber155dccd12014-07-24 17:08:39 +0000115 /// The depth of TheCondStack at the start of the instantiation.
116 size_t CondStackDepth;
117
Daniel Dunbar43235712010-07-18 18:54:11 +0000118public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000119 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000120};
121
Eli Friedman0f4871d2012-10-22 23:58:19 +0000122struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000123 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000124 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000125
Jim Grosbach4b905842013-09-20 23:08:21 +0000126 /// \brief The opcode from the last parsed instruction.
Eli Friedman0f4871d2012-10-22 23:58:19 +0000127 unsigned Opcode;
128
Jim Grosbach4b905842013-09-20 23:08:21 +0000129 /// \brief Was there an error parsing the inline assembly?
Chad Rosier149e8e02012-12-12 22:45:52 +0000130 bool ParseError;
131
Eli Friedman0f4871d2012-10-22 23:58:19 +0000132 SmallVectorImpl<AsmRewrite> *AsmRewrites;
133
Craig Topper353eda42014-04-24 06:44:33 +0000134 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000135 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier149e8e02012-12-12 22:45:52 +0000136 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000137};
138
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000139/// \brief The concrete assembly parser instance.
140class AsmParser : public MCAsmParser {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000141 AsmParser(const AsmParser &) = delete;
142 void operator=(const AsmParser &) = delete;
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000143
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000144private:
145 AsmLexer Lexer;
146 MCContext &Ctx;
147 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000148 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000149 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000150 SourceMgr::DiagHandlerTy SavedDiagHandler;
151 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000152 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000153
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000154 /// This is the current buffer index we're lexing from as managed by the
155 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000156 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000157
158 AsmCond TheCondState;
159 std::vector<AsmCond> TheCondStack;
160
Jim Grosbach4b905842013-09-20 23:08:21 +0000161 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000162 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000163 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000164 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000165
Jim Grosbach4b905842013-09-20 23:08:21 +0000166 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000167 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000168
Jim Grosbach4b905842013-09-20 23:08:21 +0000169 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000170 std::vector<MacroInstantiation*> ActiveMacros;
171
Jim Grosbach4b905842013-09-20 23:08:21 +0000172 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000173 std::deque<MCAsmMacro> MacroLikeBodies;
174
Daniel Dunbar828984f2010-07-18 18:38:02 +0000175 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000176 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000177
Toma Tabacu217116e2015-04-27 10:50:29 +0000178 /// \brief Keeps track of how many .macro's have been instantiated.
179 unsigned NumOfMacroInstantiations;
180
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000181 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000182 struct CppHashInfoTy {
183 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000184 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000185 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000186 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000187 };
188 CppHashInfoTy CppHashInfo;
189
190 /// \brief List of forward directional labels for diagnosis at the end.
191 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
192
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000193 /// When generating dwarf for assembly source files we need to calculate the
194 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000195 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000196 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
197 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000198 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000199 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000200
Devang Patela173ee52012-01-31 18:14:05 +0000201 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
202 unsigned AssemblerDialect;
203
Jim Grosbach4b905842013-09-20 23:08:21 +0000204 /// \brief is Darwin compatibility enabled?
Preston Gurd05500642012-09-19 20:36:12 +0000205 bool IsDarwin;
206
Jim Grosbach4b905842013-09-20 23:08:21 +0000207 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier49963552012-10-13 00:26:04 +0000208 bool ParsingInlineAsm;
209
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000210public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000211 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000212 const MCAsmInfo &MAI);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000213 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000214
Craig Topper59be68f2014-03-08 07:14:16 +0000215 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000216
Craig Topper59be68f2014-03-08 07:14:16 +0000217 void addDirectiveHandler(StringRef Directive,
218 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000219 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000220 }
221
Toma Tabacu11e14a92015-04-21 11:50:52 +0000222 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
223 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
224 }
225
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000226public:
227 /// @name MCAsmParser Interface
228 /// {
229
Craig Topper59be68f2014-03-08 07:14:16 +0000230 SourceMgr &getSourceManager() override { return SrcMgr; }
231 MCAsmLexer &getLexer() override { return Lexer; }
232 MCContext &getContext() override { return Ctx; }
233 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000234
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000235 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
236
Craig Topper59be68f2014-03-08 07:14:16 +0000237 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000238 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000239 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000240 else
241 return AssemblerDialect;
242 }
Craig Topper59be68f2014-03-08 07:14:16 +0000243 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000244 AssemblerDialect = i;
245 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000246
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000247 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
248 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
249 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000250
Craig Topper59be68f2014-03-08 07:14:16 +0000251 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000252
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000253 void setParsingInlineAsm(bool V) override {
254 ParsingInlineAsm = V;
255 Lexer.setParsingMSInlineAsm(V);
256 }
Craig Topper59be68f2014-03-08 07:14:16 +0000257 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000258
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000259 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000260 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier37e755c2012-10-23 17:43:43 +0000261 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000262 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000263 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000264 const MCInstrInfo *MII, const MCInstPrinter *IP,
265 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000266
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000267 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000268 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
269 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
270 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000271 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
272 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000273 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000274
Jim Grosbach4b905842013-09-20 23:08:21 +0000275 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000276 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000277 bool parseIdentifier(StringRef &Res) override;
278 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000279
Craig Topper59be68f2014-03-08 07:14:16 +0000280 void checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000281
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000282 /// }
283
284private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000285 bool parseStatement(ParseStatementInfo &Info,
286 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000287 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000288 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000289
Jim Grosbach4b905842013-09-20 23:08:21 +0000290 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000291 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000292 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000293 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000294 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000295 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000296
Eli Benderskya313ae62013-01-16 18:56:50 +0000297 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000298 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000299
300 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000301 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000302
303 /// \brief Lookup a previously defined macro.
304 /// \param Name Macro name.
305 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000306 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000307
308 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000309 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000310
311 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000312 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000313
314 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000315 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000316
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000317 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000318 ///
319 /// \param M The macro.
320 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000321 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000322
323 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000324 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000325
David Majnemer91fc4c22014-01-29 18:57:46 +0000326 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000327 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000328
329 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000330 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000331
Jim Grosbach4b905842013-09-20 23:08:21 +0000332 void printMacroInstantiations();
333 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000334 SMRange Range = None) const {
335 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000336 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000337 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000338 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000339
Jim Grosbach4b905842013-09-20 23:08:21 +0000340 /// \brief Enter the specified file. This returns true on failure.
341 bool enterIncludeFile(const std::string &Filename);
342
343 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000344 /// This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000345 bool processIncbinFile(const std::string &Filename);
Daniel Dunbar43235712010-07-18 18:54:11 +0000346
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000347 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000348 /// current token is not set; clients should ensure Lex() is called
349 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000350 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000351 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000352 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000353 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000354
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000355 /// \brief Parse up to the end of statement and a return the contents from the
356 /// current token until the end of the statement; the current token on exit
357 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000358 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000359
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000360 /// \brief Parse until the end of a statement or a comma is encountered,
361 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000362 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000363
Jim Grosbach4b905842013-09-20 23:08:21 +0000364 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000365 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000366
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000367 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
368 MCBinaryExpr::Opcode &Kind);
369
Jim Grosbach4b905842013-09-20 23:08:21 +0000370 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
371 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
372 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000373
Jim Grosbach4b905842013-09-20 23:08:21 +0000374 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000375
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000376 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
377 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
378
Eli Bendersky17233942013-01-15 22:59:42 +0000379 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000380 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000381 DK_NO_DIRECTIVE, // Placeholder
382 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000383 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000384 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
Petr Hosek731bb9c2016-08-23 21:34:53 +0000385 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
David Woodhoused6de0d92014-02-01 16:20:59 +0000386 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000387 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000388 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000389 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000390 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000391 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000392 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
393 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000394 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000395 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
396 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000397 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000398 DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE,
399 DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE,
400 DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000401 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
402 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
403 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
404 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
405 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000406 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000407 DK_MACROS_ON, DK_MACROS_OFF,
408 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000409 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000410 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000411 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000412 };
413
Jim Grosbach4b905842013-09-20 23:08:21 +0000414 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000415 /// directives parsed by this class.
416 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000417
418 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000419 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000420 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Jim Grosbach4b905842013-09-20 23:08:21 +0000421 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
David Woodhoused6de0d92014-02-01 16:20:59 +0000422 bool parseDirectiveOctaValue(); // ".octa"
Jim Grosbach4b905842013-09-20 23:08:21 +0000423 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
424 bool parseDirectiveFill(); // ".fill"
425 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000426 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000427 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
428 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000429 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000430 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000431
Eli Bendersky17233942013-01-15 22:59:42 +0000432 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000433 bool parseDirectiveFile(SMLoc DirectiveLoc);
434 bool parseDirectiveLine();
435 bool parseDirectiveLoc();
436 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000437
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000438 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
439 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000440 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000441 bool parseDirectiveCVFuncId();
442 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000443 bool parseDirectiveCVLoc();
444 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000445 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000446 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000447 bool parseDirectiveCVStringTable();
448 bool parseDirectiveCVFileChecksums();
449
Eli Bendersky17233942013-01-15 22:59:42 +0000450 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000451 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000452 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000453 bool parseDirectiveCFISections();
454 bool parseDirectiveCFIStartProc();
455 bool parseDirectiveCFIEndProc();
456 bool parseDirectiveCFIDefCfaOffset();
457 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
458 bool parseDirectiveCFIAdjustCfaOffset();
459 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
460 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
461 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
462 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
463 bool parseDirectiveCFIRememberState();
464 bool parseDirectiveCFIRestoreState();
465 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
466 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
467 bool parseDirectiveCFIEscape();
468 bool parseDirectiveCFISignalFrame();
469 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000470
471 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000472 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000473 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000474 bool parseDirectiveEndMacro(StringRef Directive);
475 bool parseDirectiveMacro(SMLoc DirectiveLoc);
476 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000477
Eli Benderskyf483ff92012-12-20 19:05:53 +0000478 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000479 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000480 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000481 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000482 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000483 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000484
Eli Bendersky17233942013-01-15 22:59:42 +0000485 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000486 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000487
488 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000489 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000490
Jim Grosbach4b905842013-09-20 23:08:21 +0000491 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000492 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000493 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000494
Jim Grosbach4b905842013-09-20 23:08:21 +0000495 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000496
Jim Grosbach4b905842013-09-20 23:08:21 +0000497 bool parseDirectiveAbort(); // ".abort"
498 bool parseDirectiveInclude(); // ".include"
499 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000500
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000501 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
502 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000503 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000504 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000505 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000506 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000507 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
508 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000509 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000510 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
511 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
512 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
513 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000514 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000515
Jim Grosbach4b905842013-09-20 23:08:21 +0000516 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000517 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000518
Rafael Espindola34b9c512012-06-03 23:57:14 +0000519 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000520 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
521 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000522 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000523 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000524 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
525 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
526 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000527
Chad Rosierc7f552c2013-02-12 21:33:51 +0000528 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000529 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000530 size_t Len);
531
532 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000533 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000534
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000535 // "end"
536 bool parseDirectiveEnd(SMLoc DirectiveLoc);
537
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000538 // ".err" or ".error"
539 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000540
Nico Weber404012b2014-07-24 16:26:06 +0000541 // ".warning"
542 bool parseDirectiveWarning(SMLoc DirectiveLoc);
543
Eli Bendersky17233942013-01-15 22:59:42 +0000544 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000545};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000546
547} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000548
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000549namespace llvm {
550
551extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000552extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000553extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000554
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000555} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000556
Chris Lattnerc35681b2010-01-19 19:46:13 +0000557enum { DEFAULT_ADDRSPACE = 0 };
558
David Blaikie9f380a32015-03-16 18:06:57 +0000559AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
560 const MCAsmInfo &MAI)
561 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
562 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000563 MacrosEnabledFlag(true), CppHashInfo(), AssemblerDialect(~0U),
564 IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000565 // Save the old handler.
566 SavedDiagHandler = SrcMgr.getDiagHandler();
567 SavedDiagContext = SrcMgr.getDiagContext();
568 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000569 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000570 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000571
Daniel Dunbarc5011082010-07-12 18:12:02 +0000572 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000573 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
574 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000575 PlatformParser.reset(createCOFFAsmParser());
576 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000577 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000578 PlatformParser.reset(createDarwinAsmParser());
579 IsDarwin = true;
580 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000581 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000582 PlatformParser.reset(createELFAsmParser());
583 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000584 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000585
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000586 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000587 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000588
589 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000590}
591
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000592AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000593 assert((HadError || ActiveMacros.empty()) &&
594 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000595}
596
Jim Grosbach4b905842013-09-20 23:08:21 +0000597void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000598 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000599 for (std::vector<MacroInstantiation *>::const_reverse_iterator
600 it = ActiveMacros.rbegin(),
601 ie = ActiveMacros.rend();
602 it != ie; ++it)
603 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000604 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000605}
606
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000607void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
608 printPendingErrors();
609 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000610 printMacroInstantiations();
611}
612
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000613bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000614 if(getTargetParser().getTargetOptions().MCNoWarn)
615 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000616 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000617 return Error(L, Msg, Range);
618 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000619 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000620 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000621}
622
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000623bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000624 HadError = true;
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000625 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000626 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000627 return true;
628}
629
Jim Grosbach4b905842013-09-20 23:08:21 +0000630bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000631 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000632 unsigned NewBuf =
633 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
634 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000635 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000636
Sean Callanan7a77eae2010-01-21 00:19:58 +0000637 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000638 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000639 return false;
640}
Daniel Dunbar43235712010-07-18 18:54:11 +0000641
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000642/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000643/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000644/// returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000645bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000646 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000647 unsigned NewBuf =
648 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
649 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000650 return true;
651
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000652 // Pick up the bytes from the file and emit them.
Rafael Espindola64e1af82013-07-02 15:49:13 +0000653 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderby109f25c2011-12-14 21:47:48 +0000654 return false;
655}
656
Alp Tokera55b95b2014-07-06 10:33:31 +0000657void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
658 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000659 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
660 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000661}
662
Sean Callanan7a77eae2010-01-21 00:19:58 +0000663const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000664 if (Lexer.getTok().is(AsmToken::Error))
665 Error(Lexer.getErrLoc(), Lexer.getErr());
666
Nirav Dave53a72f42016-07-11 12:42:14 +0000667 // if it's a end of statement with a comment in it
668 if (getTok().is(AsmToken::EndOfStatement)) {
669 // if this is a line comment output it.
670 if (getTok().getString().front() != '\n' &&
671 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
672 Out.addExplicitComment(Twine(getTok().getString()));
673 }
674
Sean Callanan7a77eae2010-01-21 00:19:58 +0000675 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000676
677 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000678 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000679 if (MAI.preserveAsmComments())
680 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000681 tok = &Lexer.Lex();
682 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000683
Sean Callanan7a77eae2010-01-21 00:19:58 +0000684 if (tok->is(AsmToken::Eof)) {
685 // If this is the end of an included file, pop the parent file off the
686 // include stack.
687 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
688 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000689 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000690 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000691 }
692 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000693
Sean Callanan7a77eae2010-01-21 00:19:58 +0000694 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000695}
696
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000697bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000698 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000699 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000700 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000701
Chris Lattner36e02122009-06-21 20:54:55 +0000702 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000703 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000704
705 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000706 AsmCond StartingCondState = TheCondState;
707
Kevin Enderby6469fc22011-11-01 22:27:22 +0000708 // If we are generating dwarf for assembly source files save the initial text
709 // section and generate a .file directive.
710 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000711 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000712 if (!Sec->getBeginSymbol()) {
713 MCSymbol *SectionStartSym = getContext().createTempSymbol();
714 getStreamer().EmitLabel(SectionStartSym);
715 Sec->setBeginSymbol(SectionStartSym);
716 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000717 bool InsertResult = getContext().addGenDwarfSection(Sec);
718 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000719 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000720 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
721 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000722 }
723
Chris Lattner73f36112009-07-02 21:53:43 +0000724 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000725 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000726 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000727 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000728 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000729
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000730 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
731 // for printing ErrMsg via Lex() only if no (presumably better) parser error
732 // exists.
733 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000734 Lex();
735 }
736
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000737 // parseStatement returned true so may need to emit an error.
738 printPendingErrors();
739
740 // Skipping to the next line if needed.
741 if (!getLexer().isAtStartOfStatement())
742 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000743 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000744
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000745 // All errors should have been emitted.
746 assert(!hasPendingError() && "unexpected error from parseStatement");
747
Oliver Stannard21718282016-07-26 14:19:47 +0000748 getTargetParser().flushPendingInstructions(getStreamer());
749
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000750 if (TheCondState.TheCond != StartingCondState.TheCond ||
751 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000752 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000753 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000754 const auto &LineTables = getContext().getMCDwarfLineTables();
755 if (!LineTables.empty()) {
756 unsigned Index = 0;
757 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
758 if (File.Name.empty() && Index != 0)
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000759 printError(getTok().getLoc(), "unassigned file number: " +
760 Twine(Index) +
761 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000762 ++Index;
763 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000764 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000765
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000766 // Check to see that all assembler local symbols were actually defined.
767 // Targets that don't do subsections via symbols may not want this, though,
768 // so conservatively exclude them. Only do this if we're finalizing, though,
769 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000770 if (!NoFinalize) {
771 if (MAI.hasSubsectionsViaSymbols()) {
772 for (const auto &TableEntry : getContext().getSymbols()) {
773 MCSymbol *Sym = TableEntry.getValue();
774 // Variable symbols may not be marked as defined, so check those
775 // explicitly. If we know it's a variable, we have a definition for
776 // the purposes of this check.
777 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
778 // FIXME: We would really like to refer back to where the symbol was
779 // first referenced for a source location. We need to add something
780 // to track that. Currently, we just point to the end of the file.
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000781 printError(getTok().getLoc(), "assembler local symbol '" +
782 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000783 }
784 }
785
786 // Temporary symbols like the ones for directional jumps don't go in the
787 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000788 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
789 if (std::get<2>(LocSym)->isUndefined()) {
790 // Reset the state of any "# line file" directives we've seen to the
791 // context as it was at the diagnostic site.
792 CppHashInfo = std::get<1>(LocSym);
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000793 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000794 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000795 }
796 }
797
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000798 // Finalize the output stream if there are no errors and if the client wants
799 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000800 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000801 Out.Finish();
802
Oliver Stannard07b43d32015-11-17 09:58:07 +0000803 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000804}
805
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000806void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000807 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +0000808 printError(getTok().getLoc(),
809 "expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000810 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000811 }
812}
813
Jim Grosbach4b905842013-09-20 23:08:21 +0000814/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000815void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000816 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000817 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000818
Chris Lattnere5074c42009-06-22 01:29:09 +0000819 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000820 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000821 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000822}
823
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000824StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000825 const char *Start = getTok().getLoc().getPointer();
826
Jim Grosbach4b905842013-09-20 23:08:21 +0000827 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000828 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000829
830 const char *End = getTok().getLoc().getPointer();
831 return StringRef(Start, End - Start);
832}
Chris Lattner78db3622009-06-22 05:51:26 +0000833
Jim Grosbach4b905842013-09-20 23:08:21 +0000834StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000835 const char *Start = getTok().getLoc().getPointer();
836
837 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000838 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000839 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000840
841 const char *End = getTok().getLoc().getPointer();
842 return StringRef(Start, End - Start);
843}
844
Jim Grosbach4b905842013-09-20 23:08:21 +0000845/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000846/// NOTE: This assumes the leading '(' has already been consumed.
847///
848/// parenexpr ::= expr)
849///
Jim Grosbach4b905842013-09-20 23:08:21 +0000850bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
851 if (parseExpression(Res))
852 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000853 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000854 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000855 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000856 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000857 return false;
858}
Chris Lattner78db3622009-06-22 05:51:26 +0000859
Jim Grosbach4b905842013-09-20 23:08:21 +0000860/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000861/// NOTE: This assumes the leading '[' has already been consumed.
862///
863/// bracketexpr ::= expr]
864///
Jim Grosbach4b905842013-09-20 23:08:21 +0000865bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
866 if (parseExpression(Res))
867 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000868 EndLoc = getTok().getEndLoc();
869 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
870 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000871 return false;
872}
873
Jim Grosbach4b905842013-09-20 23:08:21 +0000874/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000875/// primaryexpr ::= (parenexpr
876/// primaryexpr ::= symbol
877/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000878/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000879/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000880bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000881 SMLoc FirstTokenLoc = getLexer().getLoc();
882 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
883 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000884 default:
885 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000886 // If we have an error assume that we've already handled it.
887 case AsmToken::Error:
888 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000889 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000890 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000891 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000892 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000893 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000894 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000895 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000896 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000897 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000898 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000899 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000900 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000901 if (FirstTokenKind == AsmToken::Dollar) {
902 if (Lexer.getMAI().getDollarIsPC()) {
903 // This is a '$' reference, which references the current PC. Emit a
904 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000905 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000906 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000907 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000908 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000909 EndLoc = FirstTokenLoc;
910 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000911 }
912 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000913 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000914 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000915 // Parse symbol variant
916 std::pair<StringRef, StringRef> Split;
917 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000918 if (FirstTokenKind == AsmToken::String) {
919 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000920 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000921 SMLoc AtLoc = getLexer().getLoc();
922 StringRef VName;
923 if (parseIdentifier(VName))
924 return Error(AtLoc, "expected symbol variant after '@'");
925
926 Split = std::make_pair(Identifier, VName);
927 }
928 } else {
929 Split = Identifier.split('@');
930 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000931 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000932 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000933 StringRef VName;
934 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000935 // eat ')'.
936 if (parseToken(AsmToken::RParen,
937 "unexpected token in variant, expected ')'"))
938 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000939 Split = std::make_pair(Identifier, VName);
940 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000941
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000942 EndLoc = SMLoc::getFromPointer(Identifier.end());
943
Daniel Dunbard20cda02009-10-16 01:34:54 +0000944 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000945 StringRef SymbolName = Identifier;
946 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000947
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000948 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000949 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000950 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000951 if (Variant != MCSymbolRefExpr::VK_Invalid) {
952 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000953 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000954 Variant = MCSymbolRefExpr::VK_None;
955 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000956 return Error(SMLoc::getFromPointer(Split.second.begin()),
957 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000958 }
959 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000960
Jim Grosbach6f482002015-05-18 18:43:14 +0000961 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000962
Daniel Dunbard20cda02009-10-16 01:34:54 +0000963 // If this is an absolute variable reference, substitute it now to preserve
964 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000965 if (Sym->isVariable() &&
966 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000967 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000968 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000969
Vedant Kumar86dbd922015-08-31 17:44:53 +0000970 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +0000971 return false;
972 }
973
974 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000975 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +0000976 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +0000977 }
David Woodhousef42a6662014-02-01 16:20:54 +0000978 case AsmToken::BigNum:
979 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +0000980 case AsmToken::Integer: {
981 SMLoc Loc = getTok().getLoc();
982 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000983 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000984 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000985 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +0000986 // Look for 'b' or 'f' following an Integer as a directional label
987 if (Lexer.getKind() == AsmToken::Identifier) {
988 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +0000989 // Lookup the symbol variant if used.
990 std::pair<StringRef, StringRef> Split = IDVal.split('@');
991 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
992 if (Split.first.size() != IDVal.size()) {
993 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +0000994 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +0000995 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000996 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +0000997 }
Jim Grosbach4b905842013-09-20 23:08:21 +0000998 if (IDVal == "f" || IDVal == "b") {
999 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001000 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001001 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001002 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001003 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001004 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001005 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001006 Lex(); // Eat identifier.
1007 }
1008 }
Chris Lattner78db3622009-06-22 05:51:26 +00001009 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001010 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001011 case AsmToken::Real: {
1012 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001013 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001014 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001015 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001016 Lex(); // Eat token.
1017 return false;
1018 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001019 case AsmToken::Dot: {
1020 // This is a '.' reference, which references the current PC. Emit a
1021 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001022 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001023 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001024 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001025 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001026 Lex(); // Eat identifier.
1027 return false;
1028 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001029 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001030 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001031 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001032 case AsmToken::LBrac:
1033 if (!PlatformParser->HasBracketExpressions())
1034 return TokError("brackets expression not supported on this target");
1035 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001036 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001037 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001038 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001039 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001040 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001041 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001042 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001043 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001044 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001045 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001046 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001047 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001048 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001049 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001050 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001051 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001052 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001053 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001054 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001055 // MIPS unary expression operators. The lexer won't generate these tokens if
1056 // MCAsmInfo::HasMipsExpressions is false for the target.
1057 case AsmToken::PercentCall16:
1058 case AsmToken::PercentCall_Hi:
1059 case AsmToken::PercentCall_Lo:
1060 case AsmToken::PercentDtprel_Hi:
1061 case AsmToken::PercentDtprel_Lo:
1062 case AsmToken::PercentGot:
1063 case AsmToken::PercentGot_Disp:
1064 case AsmToken::PercentGot_Hi:
1065 case AsmToken::PercentGot_Lo:
1066 case AsmToken::PercentGot_Ofst:
1067 case AsmToken::PercentGot_Page:
1068 case AsmToken::PercentGottprel:
1069 case AsmToken::PercentGp_Rel:
1070 case AsmToken::PercentHi:
1071 case AsmToken::PercentHigher:
1072 case AsmToken::PercentHighest:
1073 case AsmToken::PercentLo:
1074 case AsmToken::PercentNeg:
1075 case AsmToken::PercentPcrel_Hi:
1076 case AsmToken::PercentPcrel_Lo:
1077 case AsmToken::PercentTlsgd:
1078 case AsmToken::PercentTlsldm:
1079 case AsmToken::PercentTprel_Hi:
1080 case AsmToken::PercentTprel_Lo:
1081 Lex(); // Eat the operator.
1082 if (Lexer.isNot(AsmToken::LParen))
1083 return TokError("expected '(' after operator");
1084 Lex(); // Eat the operator.
1085 if (parseExpression(Res, EndLoc))
1086 return true;
1087 if (Lexer.isNot(AsmToken::RParen))
1088 return TokError("expected ')'");
1089 Lex(); // Eat the operator.
1090 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1091 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001092 }
1093}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001094
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001095bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001096 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001097 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001098}
1099
Daniel Dunbar55f16672010-09-17 02:47:07 +00001100const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001101AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001102 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001103 // Ask the target implementation about this expression first.
1104 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1105 if (NewE)
1106 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001107 // Recurse over the given expression, rebuilding it to apply the given variant
1108 // if there is exactly one symbol.
1109 switch (E->getKind()) {
1110 case MCExpr::Target:
1111 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001112 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001113
1114 case MCExpr::SymbolRef: {
1115 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1116
1117 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001118 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1119 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001120 return E;
1121 }
1122
Jim Grosbach13760bd2015-05-30 01:25:56 +00001123 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001124 }
1125
1126 case MCExpr::Unary: {
1127 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001128 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001129 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001130 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001131 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001132 }
1133
1134 case MCExpr::Binary: {
1135 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001136 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1137 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001138
1139 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001140 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001141
Jim Grosbach4b905842013-09-20 23:08:21 +00001142 if (!LHS)
1143 LHS = BE->getLHS();
1144 if (!RHS)
1145 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001146
Jim Grosbach13760bd2015-05-30 01:25:56 +00001147 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001148 }
1149 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001150
Craig Toppera2886c22012-02-07 05:05:23 +00001151 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001152}
1153
Jim Grosbach4b905842013-09-20 23:08:21 +00001154/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001155///
Jim Grosbachbd164242011-08-20 16:24:13 +00001156/// expr ::= expr &&,|| expr -> lowest.
1157/// expr ::= expr |,^,&,! expr
1158/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1159/// expr ::= expr <<,>> expr
1160/// expr ::= expr +,- expr
1161/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001162/// expr ::= primaryexpr
1163///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001164bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001165 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001166 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001167 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001168 return true;
1169
Daniel Dunbar55f16672010-09-17 02:47:07 +00001170 // As a special case, we support 'a op b @ modifier' by rewriting the
1171 // expression to include the modifier. This is inefficient, but in general we
1172 // expect users to use 'a@modifier op b'.
1173 if (Lexer.getKind() == AsmToken::At) {
1174 Lex();
1175
1176 if (Lexer.isNot(AsmToken::Identifier))
1177 return TokError("unexpected symbol modifier following '@'");
1178
1179 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001180 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001181 if (Variant == MCSymbolRefExpr::VK_Invalid)
1182 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1183
Jim Grosbach4b905842013-09-20 23:08:21 +00001184 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001185 if (!ModifiedRes) {
1186 return TokError("invalid modifier '" + getTok().getIdentifier() +
1187 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001188 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001189
Daniel Dunbar55f16672010-09-17 02:47:07 +00001190 Res = ModifiedRes;
1191 Lex();
1192 }
1193
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001194 // Try to constant fold it up front, if possible.
1195 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001196 if (Res->evaluateAsAbsolute(Value))
1197 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001198
1199 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001200}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001201
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001202bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001203 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001204 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001205}
1206
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001207bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1208 SMLoc &EndLoc) {
1209 if (parseParenExpr(Res, EndLoc))
1210 return true;
1211
1212 for (; ParenDepth > 0; --ParenDepth) {
1213 if (parseBinOpRHS(1, Res, EndLoc))
1214 return true;
1215
1216 // We don't Lex() the last RParen.
1217 // This is the same behavior as parseParenExpression().
1218 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001219 EndLoc = getTok().getEndLoc();
1220 if (parseToken(AsmToken::RParen,
1221 "expected ')' in parentheses expression"))
1222 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001223 }
1224 }
1225 return false;
1226}
1227
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001228bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001229 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001230
Daniel Dunbar75630b32009-06-30 02:10:03 +00001231 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001232 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001233 return true;
1234
Jim Grosbach13760bd2015-05-30 01:25:56 +00001235 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001236 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001237
1238 return false;
1239}
1240
David Majnemer0993e0b2015-10-26 03:15:34 +00001241static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1242 MCBinaryExpr::Opcode &Kind,
1243 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001244 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001245 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001246 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001247
Jim Grosbach4b905842013-09-20 23:08:21 +00001248 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001249 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001250 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001251 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001252 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001253 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001254 return 1;
1255
Jim Grosbach4b905842013-09-20 23:08:21 +00001256 // Low Precedence: |, &, ^
1257 //
1258 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001259 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001260 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001261 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001262 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001263 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001264 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001265 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001266 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001267 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001268
Jim Grosbach4b905842013-09-20 23:08:21 +00001269 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001270 case AsmToken::EqualEqual:
1271 Kind = MCBinaryExpr::EQ;
1272 return 3;
1273 case AsmToken::ExclaimEqual:
1274 case AsmToken::LessGreater:
1275 Kind = MCBinaryExpr::NE;
1276 return 3;
1277 case AsmToken::Less:
1278 Kind = MCBinaryExpr::LT;
1279 return 3;
1280 case AsmToken::LessEqual:
1281 Kind = MCBinaryExpr::LTE;
1282 return 3;
1283 case AsmToken::Greater:
1284 Kind = MCBinaryExpr::GT;
1285 return 3;
1286 case AsmToken::GreaterEqual:
1287 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001288 return 3;
1289
Jim Grosbach4b905842013-09-20 23:08:21 +00001290 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001291 case AsmToken::LessLess:
1292 Kind = MCBinaryExpr::Shl;
1293 return 4;
1294 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001295 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001296 return 4;
1297
Jim Grosbach4b905842013-09-20 23:08:21 +00001298 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001299 case AsmToken::Plus:
1300 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001301 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001302 case AsmToken::Minus:
1303 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001304 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001305
Jim Grosbach4b905842013-09-20 23:08:21 +00001306 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001307 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001308 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001309 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001310 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001311 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001312 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001313 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001314 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001315 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001316 }
1317}
1318
David Majnemer0993e0b2015-10-26 03:15:34 +00001319static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1320 MCBinaryExpr::Opcode &Kind,
1321 bool ShouldUseLogicalShr) {
1322 switch (K) {
1323 default:
1324 return 0; // not a binop.
1325
1326 // Lowest Precedence: &&, ||
1327 case AsmToken::AmpAmp:
1328 Kind = MCBinaryExpr::LAnd;
1329 return 2;
1330 case AsmToken::PipePipe:
1331 Kind = MCBinaryExpr::LOr;
1332 return 1;
1333
1334 // Low Precedence: ==, !=, <>, <, <=, >, >=
1335 case AsmToken::EqualEqual:
1336 Kind = MCBinaryExpr::EQ;
1337 return 3;
1338 case AsmToken::ExclaimEqual:
1339 case AsmToken::LessGreater:
1340 Kind = MCBinaryExpr::NE;
1341 return 3;
1342 case AsmToken::Less:
1343 Kind = MCBinaryExpr::LT;
1344 return 3;
1345 case AsmToken::LessEqual:
1346 Kind = MCBinaryExpr::LTE;
1347 return 3;
1348 case AsmToken::Greater:
1349 Kind = MCBinaryExpr::GT;
1350 return 3;
1351 case AsmToken::GreaterEqual:
1352 Kind = MCBinaryExpr::GTE;
1353 return 3;
1354
1355 // Low Intermediate Precedence: +, -
1356 case AsmToken::Plus:
1357 Kind = MCBinaryExpr::Add;
1358 return 4;
1359 case AsmToken::Minus:
1360 Kind = MCBinaryExpr::Sub;
1361 return 4;
1362
1363 // High Intermediate Precedence: |, &, ^
1364 //
1365 // FIXME: gas seems to support '!' as an infix operator?
1366 case AsmToken::Pipe:
1367 Kind = MCBinaryExpr::Or;
1368 return 5;
1369 case AsmToken::Caret:
1370 Kind = MCBinaryExpr::Xor;
1371 return 5;
1372 case AsmToken::Amp:
1373 Kind = MCBinaryExpr::And;
1374 return 5;
1375
1376 // Highest Precedence: *, /, %, <<, >>
1377 case AsmToken::Star:
1378 Kind = MCBinaryExpr::Mul;
1379 return 6;
1380 case AsmToken::Slash:
1381 Kind = MCBinaryExpr::Div;
1382 return 6;
1383 case AsmToken::Percent:
1384 Kind = MCBinaryExpr::Mod;
1385 return 6;
1386 case AsmToken::LessLess:
1387 Kind = MCBinaryExpr::Shl;
1388 return 6;
1389 case AsmToken::GreaterGreater:
1390 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1391 return 6;
1392 }
1393}
1394
1395unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1396 MCBinaryExpr::Opcode &Kind) {
1397 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1398 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1399 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1400}
1401
Jim Grosbach4b905842013-09-20 23:08:21 +00001402/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001403/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001404bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001405 SMLoc &EndLoc) {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001406 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001407 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001408 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001409
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001410 // If the next token is lower precedence than we are allowed to eat, return
1411 // successfully with what we ate already.
1412 if (TokPrec < Precedence)
1413 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001414
Sean Callanan686ed8d2010-01-19 20:22:31 +00001415 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001416
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001417 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001418 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001419 if (parsePrimaryExpr(RHS, EndLoc))
1420 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001421
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001422 // If BinOp binds less tightly with RHS than the operator after RHS, let
1423 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001424 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001425 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001426 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1427 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001428
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001429 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001430 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001431 }
1432}
1433
Chris Lattner36e02122009-06-21 20:54:55 +00001434/// ParseStatement:
1435/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001436/// ::= Label* Directive ...Operands... EndOfStatement
1437/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001438bool AsmParser::parseStatement(ParseStatementInfo &Info,
1439 MCAsmParserSemaCallback *SI) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +00001440 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001441 // Eat initial spaces and comments
1442 while (Lexer.is(AsmToken::Space))
1443 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001444 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001445 // if this is a line comment we can drop it safely
1446 if (getTok().getString().front() == '\r' ||
1447 getTok().getString().front() == '\n')
1448 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001449 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001450 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001451 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001452 if (Lexer.is(AsmToken::Hash)) {
1453 // Seeing a hash here means that it was an end-of-line comment in
1454 // an asm syntax where hash's are not comment and the previous
1455 // statement parser did not check the end of statement. Relex as
1456 // EndOfStatement.
1457 StringRef CommentStr = parseStringToEndOfStatement();
1458 Lexer.Lex();
1459 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1460 return false;
1461 }
Nirav Davefd910412016-06-17 16:06:17 +00001462 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001463 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001464 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001465 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001466 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001467 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001468 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001469 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001470 if (Lexer.is(AsmToken::Integer)) {
1471 LocalLabelVal = getTok().getIntVal();
1472 if (LocalLabelVal < 0) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +00001473 if (!TheCondState.Ignore) {
1474 Lex(); // always eat a token
1475 return Error(IDLoc, "unexpected token at start of statement");
1476 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001477 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001478 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001479 IDVal = getTok().getString();
1480 Lex(); // Consume the integer token to be used as an identifier token.
1481 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +00001482 if (!TheCondState.Ignore) {
1483 Lex(); // always eat a token
1484 return Error(IDLoc, "unexpected token at start of statement");
1485 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001486 }
1487 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001488 } else if (Lexer.is(AsmToken::Dot)) {
1489 // Treat '.' as a valid identifier in this context.
1490 Lex();
1491 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001492 } else if (Lexer.is(AsmToken::LCurly)) {
1493 // Treat '{' as a valid identifier in this context.
1494 Lex();
1495 IDVal = "{";
1496
1497 } else if (Lexer.is(AsmToken::RCurly)) {
1498 // Treat '}' as a valid identifier in this context.
1499 Lex();
1500 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001501 } else if (parseIdentifier(IDVal)) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +00001502 if (!TheCondState.Ignore) {
1503 Lex(); // always eat a token
1504 return Error(IDLoc, "unexpected token at start of statement");
1505 }
Chris Lattner926885c2010-04-17 18:14:27 +00001506 IDVal = "";
1507 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001508
Chris Lattner926885c2010-04-17 18:14:27 +00001509 // Handle conditional assembly here before checking for skipping. We
1510 // have to do this so that .endif isn't skipped in a ".if 0" block for
1511 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001512 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001513 DirectiveKindMap.find(IDVal);
1514 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1515 ? DK_NO_DIRECTIVE
1516 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001517 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001518 default:
1519 break;
1520 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001521 case DK_IFEQ:
1522 case DK_IFGE:
1523 case DK_IFGT:
1524 case DK_IFLE:
1525 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001526 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001527 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001528 case DK_IFB:
1529 return parseDirectiveIfb(IDLoc, true);
1530 case DK_IFNB:
1531 return parseDirectiveIfb(IDLoc, false);
1532 case DK_IFC:
1533 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001534 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001535 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001536 case DK_IFNC:
1537 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001538 case DK_IFNES:
1539 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001540 case DK_IFDEF:
1541 return parseDirectiveIfdef(IDLoc, true);
1542 case DK_IFNDEF:
1543 case DK_IFNOTDEF:
1544 return parseDirectiveIfdef(IDLoc, false);
1545 case DK_ELSEIF:
1546 return parseDirectiveElseIf(IDLoc);
1547 case DK_ELSE:
1548 return parseDirectiveElse(IDLoc);
1549 case DK_ENDIF:
1550 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001551 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001552
Eli Bendersky88024712013-01-16 19:32:36 +00001553 // Ignore the statement if in the middle of inactive conditional
1554 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001555 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001556 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001557 return false;
1558 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001559
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001560 // FIXME: Recurse on local labels?
1561
1562 // See what kind of statement we have.
1563 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001564 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001565 if (!getTargetParser().isLabel(ID))
1566 break;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001567 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001568
Chris Lattner36e02122009-06-21 20:54:55 +00001569 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001570 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001571
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001572 // Diagnose attempt to use '.' as a label.
1573 if (IDVal == ".")
1574 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1575
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001576 // Diagnose attempt to use a variable as a label.
1577 //
1578 // FIXME: Diagnostics. Note the location of the definition as a label.
1579 // FIXME: This doesn't diagnose assignment to a symbol which has been
1580 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001581 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001582 if (LocalLabelVal == -1) {
1583 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001584 StringRef RewrittenLabel =
1585 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1586 assert(RewrittenLabel.size() &&
1587 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001588 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1589 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001590 IDVal = RewrittenLabel;
1591 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001592 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001593 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001594 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001595
1596 Sym->redefineIfPossible();
1597
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001598 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001599 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001600
Nirav Dave9263ae32016-08-02 19:17:54 +00001601 // End of Labels should be treated as end of line for lexing
1602 // purposes but that information is not available to the Lexer who
1603 // does not understand Labels. This may cause us to see a Hash
1604 // here instead of a preprocessor line comment.
1605 if (getTok().is(AsmToken::Hash)) {
1606 StringRef CommentStr = parseStringToEndOfStatement();
1607 Lexer.Lex();
1608 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1609 }
1610
Nirav Dave8ea792d2016-07-13 14:03:12 +00001611 // Consume any end of statement token, if present, to avoid spurious
1612 // AddBlankLine calls().
1613 if (getTok().is(AsmToken::EndOfStatement)) {
1614 Lex();
1615 }
1616
Daniel Dunbare73b2672009-08-26 22:13:22 +00001617 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001618 if (!ParsingInlineAsm)
1619 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001620
Kevin Enderbye7739d42011-12-09 18:09:40 +00001621 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001622 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001623 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001624 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1625 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001626
Tim Northover1744d0a2013-10-25 12:49:50 +00001627 getTargetParser().onLabelParsed(Sym);
1628
Eli Friedman0f4871d2012-10-22 23:58:19 +00001629 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001630 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001631
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001632 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001633 if (!getTargetParser().equalIsAsmAssignment())
1634 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001635 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001636 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001637
Jim Grosbach4b905842013-09-20 23:08:21 +00001638 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001639
1640 default: // Normal instruction or directive.
1641 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001642 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001643
1644 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001645 if (areMacrosEnabled())
1646 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1647 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001648 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001649
Michael J. Spencer530ce852010-10-09 11:00:50 +00001650 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001651
Eli Bendersky17233942013-01-15 22:59:42 +00001652 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001653 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001654 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001655 //
Eli Bendersky17233942013-01-15 22:59:42 +00001656 // 1. The target-specific assembly parser. Some directives are target
1657 // specific or may potentially behave differently on certain targets.
1658 // 2. Asm parser extensions. For example, platform-specific parsers
1659 // (like the ELF parser) register themselves as extensions.
1660 // 3. The generic directive parser implemented by this class. These are
1661 // all the directives that behave in a target and platform independent
1662 // manner, or at least have a default behavior that's shared between
1663 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001664
Oliver Stannard21718282016-07-26 14:19:47 +00001665 getTargetParser().flushPendingInstructions(getStreamer());
1666
Nirav Davec0c0f7a12016-09-12 20:03:02 +00001667 SMLoc StartTokLoc = getTok().getLoc();
1668 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1669
1670 if (hasPendingError())
1671 return true;
1672 // Currently the return value should be true if we are
1673 // uninterested but as this is at odds with the standard parsing
1674 // convention (return true = error) we have instances of a parsed
1675 // directive that fails returning true as an error. Catch these
1676 // cases as best as possible errors here.
1677 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1678 return true;
1679 // Return if we did some parsing or believe we succeeded.
1680 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001681 return false;
1682
Alp Tokercb402912014-01-24 17:20:08 +00001683 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001684 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001685 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1686 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001687 if (Handler.first)
1688 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1689
1690 // Finally, if no one else is interested in this directive, it must be
1691 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001692 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001693 default:
1694 break;
1695 case DK_SET:
1696 case DK_EQU:
1697 return parseDirectiveSet(IDVal, true);
1698 case DK_EQUIV:
1699 return parseDirectiveSet(IDVal, false);
1700 case DK_ASCII:
1701 return parseDirectiveAscii(IDVal, false);
1702 case DK_ASCIZ:
1703 case DK_STRING:
1704 return parseDirectiveAscii(IDVal, true);
1705 case DK_BYTE:
1706 return parseDirectiveValue(1);
1707 case DK_SHORT:
1708 case DK_VALUE:
1709 case DK_2BYTE:
1710 return parseDirectiveValue(2);
1711 case DK_LONG:
1712 case DK_INT:
1713 case DK_4BYTE:
1714 return parseDirectiveValue(4);
1715 case DK_QUAD:
1716 case DK_8BYTE:
1717 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001718 case DK_OCTA:
1719 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001720 case DK_SINGLE:
1721 case DK_FLOAT:
1722 return parseDirectiveRealValue(APFloat::IEEEsingle);
1723 case DK_DOUBLE:
1724 return parseDirectiveRealValue(APFloat::IEEEdouble);
1725 case DK_ALIGN: {
1726 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1727 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1728 }
1729 case DK_ALIGN32: {
1730 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1731 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1732 }
1733 case DK_BALIGN:
1734 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1735 case DK_BALIGNW:
1736 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1737 case DK_BALIGNL:
1738 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1739 case DK_P2ALIGN:
1740 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1741 case DK_P2ALIGNW:
1742 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1743 case DK_P2ALIGNL:
1744 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1745 case DK_ORG:
1746 return parseDirectiveOrg();
1747 case DK_FILL:
1748 return parseDirectiveFill();
1749 case DK_ZERO:
1750 return parseDirectiveZero();
1751 case DK_EXTERN:
1752 eatToEndOfStatement(); // .extern is the default, ignore it.
1753 return false;
1754 case DK_GLOBL:
1755 case DK_GLOBAL:
1756 return parseDirectiveSymbolAttribute(MCSA_Global);
1757 case DK_LAZY_REFERENCE:
1758 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1759 case DK_NO_DEAD_STRIP:
1760 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1761 case DK_SYMBOL_RESOLVER:
1762 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1763 case DK_PRIVATE_EXTERN:
1764 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1765 case DK_REFERENCE:
1766 return parseDirectiveSymbolAttribute(MCSA_Reference);
1767 case DK_WEAK_DEFINITION:
1768 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1769 case DK_WEAK_REFERENCE:
1770 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1771 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1772 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1773 case DK_COMM:
1774 case DK_COMMON:
1775 return parseDirectiveComm(/*IsLocal=*/false);
1776 case DK_LCOMM:
1777 return parseDirectiveComm(/*IsLocal=*/true);
1778 case DK_ABORT:
1779 return parseDirectiveAbort();
1780 case DK_INCLUDE:
1781 return parseDirectiveInclude();
1782 case DK_INCBIN:
1783 return parseDirectiveIncbin();
1784 case DK_CODE16:
1785 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001786 return TokError(Twine(IDVal) +
1787 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001788 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001789 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001790 case DK_IRP:
1791 return parseDirectiveIrp(IDLoc);
1792 case DK_IRPC:
1793 return parseDirectiveIrpc(IDLoc);
1794 case DK_ENDR:
1795 return parseDirectiveEndr(IDLoc);
1796 case DK_BUNDLE_ALIGN_MODE:
1797 return parseDirectiveBundleAlignMode();
1798 case DK_BUNDLE_LOCK:
1799 return parseDirectiveBundleLock();
1800 case DK_BUNDLE_UNLOCK:
1801 return parseDirectiveBundleUnlock();
1802 case DK_SLEB128:
1803 return parseDirectiveLEB128(true);
1804 case DK_ULEB128:
1805 return parseDirectiveLEB128(false);
1806 case DK_SPACE:
1807 case DK_SKIP:
1808 return parseDirectiveSpace(IDVal);
1809 case DK_FILE:
1810 return parseDirectiveFile(IDLoc);
1811 case DK_LINE:
1812 return parseDirectiveLine();
1813 case DK_LOC:
1814 return parseDirectiveLoc();
1815 case DK_STABS:
1816 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001817 case DK_CV_FILE:
1818 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001819 case DK_CV_FUNC_ID:
1820 return parseDirectiveCVFuncId();
1821 case DK_CV_INLINE_SITE_ID:
1822 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001823 case DK_CV_LOC:
1824 return parseDirectiveCVLoc();
1825 case DK_CV_LINETABLE:
1826 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001827 case DK_CV_INLINE_LINETABLE:
1828 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001829 case DK_CV_DEF_RANGE:
1830 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001831 case DK_CV_STRINGTABLE:
1832 return parseDirectiveCVStringTable();
1833 case DK_CV_FILECHECKSUMS:
1834 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001835 case DK_CFI_SECTIONS:
1836 return parseDirectiveCFISections();
1837 case DK_CFI_STARTPROC:
1838 return parseDirectiveCFIStartProc();
1839 case DK_CFI_ENDPROC:
1840 return parseDirectiveCFIEndProc();
1841 case DK_CFI_DEF_CFA:
1842 return parseDirectiveCFIDefCfa(IDLoc);
1843 case DK_CFI_DEF_CFA_OFFSET:
1844 return parseDirectiveCFIDefCfaOffset();
1845 case DK_CFI_ADJUST_CFA_OFFSET:
1846 return parseDirectiveCFIAdjustCfaOffset();
1847 case DK_CFI_DEF_CFA_REGISTER:
1848 return parseDirectiveCFIDefCfaRegister(IDLoc);
1849 case DK_CFI_OFFSET:
1850 return parseDirectiveCFIOffset(IDLoc);
1851 case DK_CFI_REL_OFFSET:
1852 return parseDirectiveCFIRelOffset(IDLoc);
1853 case DK_CFI_PERSONALITY:
1854 return parseDirectiveCFIPersonalityOrLsda(true);
1855 case DK_CFI_LSDA:
1856 return parseDirectiveCFIPersonalityOrLsda(false);
1857 case DK_CFI_REMEMBER_STATE:
1858 return parseDirectiveCFIRememberState();
1859 case DK_CFI_RESTORE_STATE:
1860 return parseDirectiveCFIRestoreState();
1861 case DK_CFI_SAME_VALUE:
1862 return parseDirectiveCFISameValue(IDLoc);
1863 case DK_CFI_RESTORE:
1864 return parseDirectiveCFIRestore(IDLoc);
1865 case DK_CFI_ESCAPE:
1866 return parseDirectiveCFIEscape();
1867 case DK_CFI_SIGNAL_FRAME:
1868 return parseDirectiveCFISignalFrame();
1869 case DK_CFI_UNDEFINED:
1870 return parseDirectiveCFIUndefined(IDLoc);
1871 case DK_CFI_REGISTER:
1872 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001873 case DK_CFI_WINDOW_SAVE:
1874 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001875 case DK_MACROS_ON:
1876 case DK_MACROS_OFF:
1877 return parseDirectiveMacrosOnOff(IDVal);
1878 case DK_MACRO:
1879 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001880 case DK_EXITM:
1881 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001882 case DK_ENDM:
1883 case DK_ENDMACRO:
1884 return parseDirectiveEndMacro(IDVal);
1885 case DK_PURGEM:
1886 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001887 case DK_END:
1888 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001889 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001890 return parseDirectiveError(IDLoc, false);
1891 case DK_ERROR:
1892 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001893 case DK_WARNING:
1894 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001895 case DK_RELOC:
1896 return parseDirectiveReloc(IDLoc);
Petr Hosek731bb9c2016-08-23 21:34:53 +00001897 case DK_DC:
1898 return parseDirectiveValue(2);
1899 case DK_DC_A:
1900 return parseDirectiveValue(getContext().getAsmInfo()->getPointerSize());
1901 case DK_DC_B:
1902 return parseDirectiveValue(1);
1903 case DK_DC_D:
1904 return parseDirectiveRealValue(APFloat::IEEEdouble);
1905 case DK_DC_L:
1906 return parseDirectiveValue(4);
1907 case DK_DC_S:
1908 return parseDirectiveRealValue(APFloat::IEEEsingle);
1909 case DK_DC_W:
1910 return parseDirectiveValue(2);
1911 case DK_DC_X:
1912 return TokError(Twine(IDVal) +
1913 " not currently supported for this target");
Eli Friedman20b02642010-07-19 04:17:25 +00001914 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001915
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001916 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001917 }
Chris Lattner36e02122009-06-21 20:54:55 +00001918
Chad Rosierc7f552c2013-02-12 21:33:51 +00001919 // __asm _emit or __asm __emit
1920 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1921 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001922 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001923
1924 // __asm align
1925 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001926 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001927
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001928 if (ParsingInlineAsm && (IDVal == "even"))
1929 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001930 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001931
Chris Lattner7cbfa442010-05-19 23:34:33 +00001932 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001933 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001934 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Davec0c0f7a12016-09-12 20:03:02 +00001935 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1936 Info.ParsedOperands);
1937 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001938
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001939 // Dump the parsed representation, if requested.
1940 if (getShowParsedOperands()) {
1941 SmallString<256> Str;
1942 raw_svector_ostream OS(Str);
1943 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001944 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001945 if (i != 0)
1946 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001947 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001948 }
1949 OS << "]";
1950
Jim Grosbach4b905842013-09-20 23:08:21 +00001951 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001952 }
1953
Nirav Davec0c0f7a12016-09-12 20:03:02 +00001954 // Fail even if ParseInstruction erroneously returns false.
1955 if (hasPendingError() || ParseHadError)
1956 return true;
1957
Oliver Stannard8b273082014-06-19 15:52:37 +00001958 // If we are generating dwarf for the current section then generate a .loc
1959 // directive for the instruction.
Nirav Davec0c0f7a12016-09-12 20:03:02 +00001960 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001961 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001962 getStreamer().getCurrentSection().first)) {
1963 unsigned Line;
1964 if (ActiveMacros.empty())
1965 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1966 else
Frederic Riss16238d92015-06-25 21:57:33 +00001967 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1968 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001969
Eli Bendersky88024712013-01-16 19:32:36 +00001970 // If we previously parsed a cpp hash file line comment then make sure the
1971 // current Dwarf File is for the CppHashFilename if not then emit the
1972 // Dwarf File table for it and adjust the line number for the .loc.
Tim Northoverc0bef992016-04-13 19:46:54 +00001973 if (CppHashInfo.Filename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001974 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00001975 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00001976 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001977
Jim Grosbach4b905842013-09-20 23:08:21 +00001978 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1979 // cache with the different Loc from the call above we save the last
1980 // info we queried here with SrcMgr.FindLineNumber().
1981 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001982 if (LastQueryIDLoc == CppHashInfo.Loc &&
1983 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00001984 CppHashLocLineNo = LastQueryLine;
1985 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00001986 CppHashLocLineNo =
1987 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001988 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001989 LastQueryIDLoc = CppHashInfo.Loc;
1990 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00001991 }
Tim Northoverc0bef992016-04-13 19:46:54 +00001992 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00001993 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001994
Jim Grosbach4b905842013-09-20 23:08:21 +00001995 getStreamer().EmitDwarfLocDirective(
1996 getContext().getGenDwarfFileNumber(), Line, 0,
1997 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1998 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00001999 }
2000
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002001 // If parsing succeeded, match the instruction.
Nirav Davec0c0f7a12016-09-12 20:03:02 +00002002 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002003 uint64_t ErrorInfo;
Nirav Davec0c0f7a12016-09-12 20:03:02 +00002004 if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2005 Info.ParsedOperands, Out,
2006 ErrorInfo, ParsingInlineAsm))
2007 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002008 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002009 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002010}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002011
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002012// Parse and erase curly braces marking block start/end
2013bool
2014AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2015 // Identify curly brace marking block start/end
2016 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2017 return false;
2018
2019 SMLoc StartLoc = Lexer.getLoc();
2020 Lex(); // Eat the brace
2021 if (Lexer.is(AsmToken::EndOfStatement))
2022 Lex(); // Eat EndOfStatement following the brace
2023
2024 // Erase the block start/end brace from the output asm string
2025 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2026 StartLoc.getPointer());
2027 return true;
2028}
2029
Jim Grosbach4b905842013-09-20 23:08:21 +00002030/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002031/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002032bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002033 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002034 // Lexer only ever emits HashDirective if it fully formed if it's
2035 // done the checking already so this is an internal error.
2036 assert(getTok().is(AsmToken::Integer) &&
2037 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002038 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002039 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002040 assert(getTok().is(AsmToken::String) &&
2041 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002042 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002043 Lex();
Nirav Davec0c0f7a12016-09-12 20:03:02 +00002044
Kevin Enderby72553612011-09-13 23:45:18 +00002045 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002046 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002047
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002048 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002049 CppHashInfo.Loc = L;
2050 CppHashInfo.Filename = Filename;
2051 CppHashInfo.LineNumber = LineNumber;
2052 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002053 return false;
2054}
2055
Jim Grosbach4b905842013-09-20 23:08:21 +00002056/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002057/// for the Filename and LineNo if any in the diagnostic.
2058void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002059 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002060 raw_ostream &OS = errs();
2061
2062 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002063 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002064 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2065 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002066 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002067
Jim Grosbach4b905842013-09-20 23:08:21 +00002068 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002069 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002070 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2071 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2072 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002073 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2074 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002075 }
2076
Eric Christophera7c32732012-12-18 00:30:54 +00002077 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002078 // manager changed or buffer changed (like in a nested include) then just
2079 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002080 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002081 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002082 if (Parser->SavedDiagHandler)
2083 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2084 else
Craig Topper353eda42014-04-24 06:44:33 +00002085 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002086 return;
2087 }
2088
Eric Christophera7c32732012-12-18 00:30:54 +00002089 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002090 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2091 // for the diagnostic.
2092 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002093
2094 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2095 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002096 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002097 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002098 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002099
Jim Grosbach4b905842013-09-20 23:08:21 +00002100 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2101 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002102 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002103
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002104 if (Parser->SavedDiagHandler)
2105 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2106 else
Craig Topper353eda42014-04-24 06:44:33 +00002107 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002108}
2109
Rafael Espindola2c064482012-08-21 18:29:30 +00002110// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2111// difference being that that function accepts '@' as part of identifiers and
2112// we can't do that. AsmLexer.cpp should probably be changed to handle
2113// '@' as a special case when needed.
2114static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002115 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2116 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002117}
2118
Rafael Espindola34b9c512012-06-03 23:57:14 +00002119bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002120 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002121 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002122 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002123 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002124 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002125 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002126 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002127
Preston Gurd05500642012-09-19 20:36:12 +00002128 // A macro without parameters is handled differently on Darwin:
2129 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002130 while (!Body.empty()) {
2131 // Scan for the next substitution.
2132 std::size_t End = Body.size(), Pos = 0;
2133 for (; Pos != End; ++Pos) {
2134 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002135 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002136 // This macro has no parameters, look for $0, $1, etc.
2137 if (Body[Pos] != '$' || Pos + 1 == End)
2138 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002139
Rafael Espindola1134ab232011-06-05 02:43:45 +00002140 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002141 if (Next == '$' || Next == 'n' ||
2142 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002143 break;
2144 } else {
2145 // This macro has parameters, look for \foo, \bar, etc.
2146 if (Body[Pos] == '\\' && Pos + 1 != End)
2147 break;
2148 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002149 }
2150
2151 // Add the prefix.
2152 OS << Body.slice(0, Pos);
2153
2154 // Check if we reached the end.
2155 if (Pos == End)
2156 break;
2157
Benjamin Kramer513e7442014-02-20 13:36:32 +00002158 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002159 switch (Body[Pos + 1]) {
2160 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002161 case '$':
2162 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002163 break;
2164
Jim Grosbach4b905842013-09-20 23:08:21 +00002165 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002166 case 'n':
2167 OS << A.size();
2168 break;
2169
Jim Grosbach4b905842013-09-20 23:08:21 +00002170 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002171 default: {
2172 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002173 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002174 if (Index >= A.size())
2175 break;
2176
2177 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002178 for (const AsmToken &Token : A[Index])
2179 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002180 break;
2181 }
2182 }
2183 Pos += 2;
2184 } else {
2185 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002186
2187 // Check for the \@ pseudo-variable.
2188 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002189 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002190 else
2191 while (isIdentifierChar(Body[I]) && I + 1 != End)
2192 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002193
Jim Grosbach4b905842013-09-20 23:08:21 +00002194 const char *Begin = Body.data() + Pos + 1;
2195 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002196 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002197
Toma Tabacu217116e2015-04-27 10:50:29 +00002198 if (Argument == "@") {
2199 OS << NumOfMacroInstantiations;
2200 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002201 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002202 for (; Index < NParameters; ++Index)
2203 if (Parameters[Index].Name == Argument)
2204 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002205
Toma Tabacu217116e2015-04-27 10:50:29 +00002206 if (Index == NParameters) {
2207 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2208 Pos += 3;
2209 else {
2210 OS << '\\' << Argument;
2211 Pos = I;
2212 }
2213 } else {
2214 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002215 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002216 // We expect no quotes around the string's contents when
2217 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002218 if (Token.getKind() != AsmToken::String || VarargParameter)
2219 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002220 else
Craig Topper84008482015-10-10 05:38:14 +00002221 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002222
2223 Pos += 1 + Argument.size();
2224 }
Preston Gurd05500642012-09-19 20:36:12 +00002225 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002226 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002227 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002228 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002229 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002230
Rafael Espindola1134ab232011-06-05 02:43:45 +00002231 return false;
2232}
Daniel Dunbar43235712010-07-18 18:54:11 +00002233
Nico Weber2a8f9222014-07-24 16:29:04 +00002234MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002235 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002236 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002237 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002238
Jim Grosbach4b905842013-09-20 23:08:21 +00002239static bool isOperator(AsmToken::TokenKind kind) {
2240 switch (kind) {
2241 default:
2242 return false;
2243 case AsmToken::Plus:
2244 case AsmToken::Minus:
2245 case AsmToken::Tilde:
2246 case AsmToken::Slash:
2247 case AsmToken::Star:
2248 case AsmToken::Dot:
2249 case AsmToken::Equal:
2250 case AsmToken::EqualEqual:
2251 case AsmToken::Pipe:
2252 case AsmToken::PipePipe:
2253 case AsmToken::Caret:
2254 case AsmToken::Amp:
2255 case AsmToken::AmpAmp:
2256 case AsmToken::Exclaim:
2257 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002258 case AsmToken::Less:
2259 case AsmToken::LessEqual:
2260 case AsmToken::LessLess:
2261 case AsmToken::LessGreater:
2262 case AsmToken::Greater:
2263 case AsmToken::GreaterEqual:
2264 case AsmToken::GreaterGreater:
2265 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002266 }
2267}
2268
David Majnemer16252452014-01-29 00:07:39 +00002269namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002270
David Majnemer16252452014-01-29 00:07:39 +00002271class AsmLexerSkipSpaceRAII {
2272public:
2273 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2274 Lexer.setSkipSpace(SkipSpace);
2275 }
2276
2277 ~AsmLexerSkipSpaceRAII() {
2278 Lexer.setSkipSpace(true);
2279 }
2280
2281private:
2282 AsmLexer &Lexer;
2283};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002284
2285} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002286
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002287bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2288
2289 if (Vararg) {
2290 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2291 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002292 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002293 }
2294 return false;
2295 }
2296
Rafael Espindola768b41c2012-06-15 14:02:34 +00002297 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002298
David Majnemer16252452014-01-29 00:07:39 +00002299 // Darwin doesn't use spaces to delmit arguments.
2300 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002301
Scott Egertona1fa68a2016-02-11 13:48:49 +00002302 bool SpaceEaten;
2303
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002304 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002305 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002306 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002307 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002308
Scott Egertona1fa68a2016-02-11 13:48:49 +00002309 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002310
Scott Egertona1fa68a2016-02-11 13:48:49 +00002311 if (Lexer.is(AsmToken::Comma))
2312 break;
2313
2314 if (Lexer.is(AsmToken::Space)) {
2315 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002316 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002317 }
Preston Gurd05500642012-09-19 20:36:12 +00002318
2319 // Spaces can delimit parameters, but could also be part an expression.
2320 // If the token after a space is an operator, add the token and the next
2321 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002322 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002323 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002324 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002325 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002326
Scott Egertona1fa68a2016-02-11 13:48:49 +00002327 // Whitespace after an operator can be ignored.
2328 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002329 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002330
2331 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002332 }
2333 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002334 if (SpaceEaten)
2335 break;
Preston Gurd05500642012-09-19 20:36:12 +00002336 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002337
Jim Grosbach4b905842013-09-20 23:08:21 +00002338 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002339 // to be able to fill in the remaining default parameter values
2340 if (Lexer.is(AsmToken::EndOfStatement))
2341 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002342
2343 // Adjust the current parentheses level.
2344 if (Lexer.is(AsmToken::LParen))
2345 ++ParenLevel;
2346 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2347 --ParenLevel;
2348
2349 // Append the token to the current argument list.
2350 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002351 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002352 }
Preston Gurd05500642012-09-19 20:36:12 +00002353
Rafael Espindola768b41c2012-06-15 14:02:34 +00002354 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002355 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002356 return false;
2357}
2358
2359// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002360bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002361 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002362 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002363 bool NamedParametersFound = false;
2364 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002365
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002366 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002367 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002368
Rafael Espindola768b41c2012-06-15 14:02:34 +00002369 // Parse two kinds of macro invocations:
2370 // - macros defined without any parameters accept an arbitrary number of them
2371 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002372 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002373 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2374 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002375 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002376 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002377
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002378 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +00002379 if (parseIdentifier(FA.Name))
2380 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002381
Nirav Davec0c0f7a12016-09-12 20:03:02 +00002382 if (Lexer.isNot(AsmToken::Equal))
2383 return TokError("expected '=' after formal parameter identifier");
2384
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002385 Lex();
2386
2387 NamedParametersFound = true;
2388 }
2389
Nirav Davec0c0f7a12016-09-12 20:03:02 +00002390 if (NamedParametersFound && FA.Name.empty())
2391 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002392
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002393 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2394 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002395 return true;
2396
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002397 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002398 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002399 unsigned FAI = 0;
2400 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002401 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002402 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002403
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002404 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002405 assert(M && "expected macro to be defined");
Nirav Davec0c0f7a12016-09-12 20:03:02 +00002406 return Error(IDLoc, "parameter named '" + FA.Name +
2407 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002408 }
2409 PI = FAI;
2410 }
2411
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002412 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002413 if (A.size() <= PI)
2414 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002415 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002416
2417 if (FALocs.size() <= PI)
2418 FALocs.resize(PI + 1);
2419
2420 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002421 }
Jim Grosbach206661622012-07-30 22:44:17 +00002422
Preston Gurd242ed3152012-09-19 20:29:04 +00002423 // At the end of the statement, fill in remaining arguments that have
2424 // default values. If there aren't any, then the next argument is
2425 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002426 if (Lexer.is(AsmToken::EndOfStatement)) {
2427 bool Failure = false;
2428 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2429 if (A[FAI].empty()) {
2430 if (M->Parameters[FAI].Required) {
2431 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2432 "missing value for required parameter "
2433 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2434 Failure = true;
2435 }
2436
2437 if (!M->Parameters[FAI].Value.empty())
2438 A[FAI] = M->Parameters[FAI].Value;
2439 }
2440 }
2441 return Failure;
2442 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002443
2444 if (Lexer.is(AsmToken::Comma))
2445 Lex();
2446 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002447
2448 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002449}
2450
Jim Grosbach4b905842013-09-20 23:08:21 +00002451const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002452 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2453 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002454}
2455
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002456void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2457 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002458}
2459
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002460void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002461
Jim Grosbach4b905842013-09-20 23:08:21 +00002462bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002463 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2464 // eliminate this, although we should protect against infinite loops.
2465 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2466 if (ActiveMacros.size() == MaxNestingDepth) {
2467 std::ostringstream MaxNestingDepthError;
2468 MaxNestingDepthError << "macros cannot be nested more than "
2469 << MaxNestingDepth << " levels deep."
2470 << " Use -asm-macro-max-nesting-depth to increase "
2471 "this limit.";
2472 return TokError(MaxNestingDepthError.str());
2473 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002474
Eli Bendersky38274122013-01-14 23:22:36 +00002475 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002476 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002477 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002478
Rafael Espindola1134ab232011-06-05 02:43:45 +00002479 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2480 // to hold the macro body with substitutions.
2481 SmallString<256> Buf;
2482 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002483 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002484
Toma Tabacu217116e2015-04-27 10:50:29 +00002485 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002486 return true;
2487
Eli Bendersky38274122013-01-14 23:22:36 +00002488 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002489 // instantiation.
2490 OS << ".endmacro\n";
2491
Rafael Espindola3560ff22014-08-27 20:03:13 +00002492 std::unique_ptr<MemoryBuffer> Instantiation =
2493 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002494
Daniel Dunbar43235712010-07-18 18:54:11 +00002495 // Create the macro instantiation object and add to the current macro
2496 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002497 MacroInstantiation *MI = new MacroInstantiation(
2498 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002499 ActiveMacros.push_back(MI);
2500
Toma Tabacu217116e2015-04-27 10:50:29 +00002501 ++NumOfMacroInstantiations;
2502
Daniel Dunbar43235712010-07-18 18:54:11 +00002503 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002504 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002505 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002506 Lex();
2507
2508 return false;
2509}
2510
Jim Grosbach4b905842013-09-20 23:08:21 +00002511void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002512 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002513 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002514 Lex();
2515
2516 // Pop the instantiation entry.
2517 delete ActiveMacros.back();
2518 ActiveMacros.pop_back();
2519}
2520
Jim Grosbach4b905842013-09-20 23:08:21 +00002521bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002522 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002523 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002524 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002525 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2526 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002527 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002528
Pete Cooper80d21cb2015-06-22 19:35:57 +00002529 if (!Sym) {
2530 // In the case where we parse an expression starting with a '.', we will
2531 // not generate an error, nor will we create a symbol. In this case we
2532 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002533 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002534 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002535
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002536 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002537 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002538 if (NoDeadStrip)
2539 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2540
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002541 return false;
2542}
2543
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002544/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002545/// ::= identifier
2546/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002547bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002548 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002549 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2550 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002551 // handle this as a context dependent token, instead we detect adjacent tokens
2552 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002553 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2554 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002555
Hans Wennborgce69d772013-10-18 20:46:28 +00002556 // Consume the prefix character, and check for a following identifier.
Nirav Dave1180e6892016-06-02 17:15:05 +00002557 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002558 if (Lexer.isNot(AsmToken::Identifier))
2559 return true;
2560
Hans Wennborgce69d772013-10-18 20:46:28 +00002561 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2562 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002563 return true;
2564
2565 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002566 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002567 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002568 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002569 return false;
2570 }
2571
Jim Grosbach4b905842013-09-20 23:08:21 +00002572 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002573 return true;
2574
Sean Callanan936b0d32010-01-19 21:44:56 +00002575 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002576
Sean Callanan686ed8d2010-01-19 20:22:31 +00002577 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002578
2579 return false;
2580}
2581
Jim Grosbach4b905842013-09-20 23:08:21 +00002582/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002583/// ::= .equ identifier ',' expression
2584/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002585/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002586bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002587 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002588
Nirav Davea645433c2016-07-18 15:24:03 +00002589 if (check(parseIdentifier(Name),
2590 "expected identifier after '" + Twine(IDVal) + "'") ||
2591 parseToken(AsmToken::Comma, "unexpected token in '" + Twine(IDVal) + "'"))
2592 return true;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002593
Jim Grosbach4b905842013-09-20 23:08:21 +00002594 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002595}
2596
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002597bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002598 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002599
2600 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002601 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002602 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2603 if (Str[i] != '\\') {
2604 Data += Str[i];
2605 continue;
2606 }
2607
2608 // Recognize escaped characters. Note that this escape semantics currently
2609 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2610 ++i;
2611 if (i == e)
2612 return TokError("unexpected backslash at end of string");
2613
2614 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002615 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002616 // Consume up to three octal characters.
2617 unsigned Value = Str[i] - '0';
2618
Jim Grosbach4b905842013-09-20 23:08:21 +00002619 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002620 ++i;
2621 Value = Value * 8 + (Str[i] - '0');
2622
Jim Grosbach4b905842013-09-20 23:08:21 +00002623 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002624 ++i;
2625 Value = Value * 8 + (Str[i] - '0');
2626 }
2627 }
2628
2629 if (Value > 255)
2630 return TokError("invalid octal escape sequence (out of range)");
2631
Jim Grosbach4b905842013-09-20 23:08:21 +00002632 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002633 continue;
2634 }
2635
2636 // Otherwise recognize individual escapes.
2637 switch (Str[i]) {
2638 default:
2639 // Just reject invalid escape sequences for now.
2640 return TokError("invalid escape sequence (unrecognized character)");
2641
2642 case 'b': Data += '\b'; break;
2643 case 'f': Data += '\f'; break;
2644 case 'n': Data += '\n'; break;
2645 case 'r': Data += '\r'; break;
2646 case 't': Data += '\t'; break;
2647 case '"': Data += '"'; break;
2648 case '\\': Data += '\\'; break;
2649 }
2650 }
2651
Nirav Davea645433c2016-07-18 15:24:03 +00002652 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002653 return false;
2654}
2655
Jim Grosbach4b905842013-09-20 23:08:21 +00002656/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002657/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002658bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002659 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002660 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002661
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002662 while (true) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002663 std::string Data;
Nirav Davea645433c2016-07-18 15:24:03 +00002664 if (check(getTok().isNot(AsmToken::String),
2665 "expected string in '" + Twine(IDVal) + "' directive") ||
2666 parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002667 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002668
Rafael Espindola64e1af82013-07-02 15:49:13 +00002669 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002670 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002671 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002672
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002673 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002674 break;
2675
Nirav Davea645433c2016-07-18 15:24:03 +00002676 if (parseToken(AsmToken::Comma,
2677 "unexpected token in '" + Twine(IDVal) + "' directive"))
2678 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002679 }
2680 }
2681
Sean Callanan686ed8d2010-01-19 20:22:31 +00002682 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002683 return false;
2684}
2685
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002686/// parseDirectiveReloc
2687/// ::= .reloc expression , identifier [ , expression ]
2688bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2689 const MCExpr *Offset;
2690 const MCExpr *Expr = nullptr;
2691
2692 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2693 if (parseExpression(Offset))
2694 return true;
2695
2696 // We can only deal with constant expressions at the moment.
2697 int64_t OffsetValue;
Nirav Davea645433c2016-07-18 15:24:03 +00002698 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2699 "expression is not a constant value") ||
2700 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2701 parseToken(AsmToken::Comma, "expected comma") ||
2702 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2703 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002704
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002705 SMLoc NameLoc = Lexer.getTok().getLoc();
2706 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002707 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002708
2709 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002710 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002711 SMLoc ExprLoc = Lexer.getLoc();
2712 if (parseExpression(Expr))
2713 return true;
2714
2715 MCValue Value;
2716 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2717 return Error(ExprLoc, "expression must be relocatable");
2718 }
2719
Nirav Davea645433c2016-07-18 15:24:03 +00002720 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002721 "unexpected token in .reloc directive"))
2722 return true;
2723
2724 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2725 return Error(NameLoc, "unknown relocation name");
2726
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002727 return false;
2728}
2729
Jim Grosbach4b905842013-09-20 23:08:21 +00002730/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002731/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002732bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002733 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002734 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002735
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002736 while (true) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002737 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002738 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002739 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002740 return true;
2741
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002742 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002743 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2744 assert(Size <= 8 && "Invalid size");
2745 uint64_t IntValue = MCE->getValue();
2746 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2747 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002748 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002749 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002750 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002751
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002752 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002753 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002754
Daniel Dunbara10e5192009-06-24 23:30:00 +00002755 // FIXME: Improve diagnostic.
Nirav Davea645433c2016-07-18 15:24:03 +00002756 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2757 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002758 }
2759 }
2760
Sean Callanan686ed8d2010-01-19 20:22:31 +00002761 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002762 return false;
2763}
2764
David Woodhoused6de0d92014-02-01 16:20:59 +00002765/// ParseDirectiveOctaValue
2766/// ::= .octa [ hexconstant (, hexconstant)* ]
2767bool AsmParser::parseDirectiveOctaValue() {
2768 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2769 checkForValidSection();
2770
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002771 while (true) {
Nirav Davea645433c2016-07-18 15:24:03 +00002772 if (getTok().is(AsmToken::Error))
David Woodhoused6de0d92014-02-01 16:20:59 +00002773 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00002774 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
David Woodhoused6de0d92014-02-01 16:20:59 +00002775 return TokError("unknown token in expression");
2776
2777 SMLoc ExprLoc = getLexer().getLoc();
2778 APInt IntValue = getTok().getAPIntVal();
2779 Lex();
2780
2781 uint64_t hi, lo;
2782 if (IntValue.isIntN(64)) {
2783 hi = 0;
2784 lo = IntValue.getZExtValue();
2785 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002786 // It might actually have more than 128 bits, but the top ones are zero.
2787 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002788 lo = IntValue.getLoBits(64).getZExtValue();
2789 } else
2790 return Error(ExprLoc, "literal value out of range for directive");
2791
2792 if (MAI.isLittleEndian()) {
2793 getStreamer().EmitIntValue(lo, 8);
2794 getStreamer().EmitIntValue(hi, 8);
2795 } else {
2796 getStreamer().EmitIntValue(hi, 8);
2797 getStreamer().EmitIntValue(lo, 8);
2798 }
2799
2800 if (getLexer().is(AsmToken::EndOfStatement))
2801 break;
2802
2803 // FIXME: Improve diagnostic.
Nirav Davea645433c2016-07-18 15:24:03 +00002804 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2805 return true;
David Woodhoused6de0d92014-02-01 16:20:59 +00002806 }
2807 }
2808
2809 Lex();
2810 return false;
2811}
2812
Jim Grosbach4b905842013-09-20 23:08:21 +00002813/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002814/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002815bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002816 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002817 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002818
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002819 while (true) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002820 // We don't truly support arithmetic on floating point expressions, so we
2821 // have to manually parse unary prefixes.
2822 bool IsNeg = false;
2823 if (getLexer().is(AsmToken::Minus)) {
Nirav Dave1180e6892016-06-02 17:15:05 +00002824 Lexer.Lex();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002825 IsNeg = true;
2826 } else if (getLexer().is(AsmToken::Plus))
Nirav Dave1180e6892016-06-02 17:15:05 +00002827 Lexer.Lex();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002828
Nirav Dave1180e6892016-06-02 17:15:05 +00002829 if (Lexer.is(AsmToken::Error))
2830 return TokError(Lexer.getErr());
2831 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2832 Lexer.isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002833 return TokError("unexpected token in directive");
2834
2835 // Convert to an APFloat.
2836 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002837 StringRef IDVal = getTok().getString();
2838 if (getLexer().is(AsmToken::Identifier)) {
2839 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2840 Value = APFloat::getInf(Semantics);
2841 else if (!IDVal.compare_lower("nan"))
2842 Value = APFloat::getNaN(Semantics, false, ~0);
2843 else
2844 return TokError("invalid floating point literal");
2845 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002846 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002847 return TokError("invalid floating point literal");
2848 if (IsNeg)
2849 Value.changeSign();
2850
2851 // Consume the numeric token.
2852 Lex();
2853
2854 // Emit the value as an integer.
2855 APInt AsInt = Value.bitcastToAPInt();
2856 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002857 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002858
Nirav Dave1180e6892016-06-02 17:15:05 +00002859 if (Lexer.is(AsmToken::EndOfStatement))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002860 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002861
Nirav Davea645433c2016-07-18 15:24:03 +00002862 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2863 return true;
Daniel Dunbar2af16532010-09-24 01:59:56 +00002864 }
2865 }
2866
2867 Lex();
2868 return false;
2869}
2870
Jim Grosbach4b905842013-09-20 23:08:21 +00002871/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002872/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002873bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002874 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002875
Petr Hosek67a94a72016-05-28 05:57:48 +00002876 SMLoc NumBytesLoc = Lexer.getLoc();
2877 const MCExpr *NumBytes;
2878 if (parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002879 return true;
2880
Rafael Espindolab91bac62010-10-05 19:42:57 +00002881 int64_t Val = 0;
2882 if (getLexer().is(AsmToken::Comma)) {
2883 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002884 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002885 return true;
2886 }
2887
Nirav Davea645433c2016-07-18 15:24:03 +00002888 if (parseToken(AsmToken::EndOfStatement,
2889 "unexpected token in '.zero' directive"))
2890 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002891 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002892
2893 return false;
2894}
2895
Jim Grosbach4b905842013-09-20 23:08:21 +00002896/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002897/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002898bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002899 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002900
Petr Hosek67a94a72016-05-28 05:57:48 +00002901 SMLoc NumValuesLoc = Lexer.getLoc();
2902 const MCExpr *NumValues;
2903 if (parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002904 return true;
2905
Roman Divackye33098f2013-09-24 17:44:41 +00002906 int64_t FillSize = 1;
2907 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002908
David Majnemer522d3db2014-02-01 07:19:38 +00002909 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002910 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara10e5192009-06-24 23:30:00 +00002911
Nirav Davea645433c2016-07-18 15:24:03 +00002912 if (parseToken(AsmToken::Comma, "unexpected token in '.fill' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00002913 parseTokenLoc(SizeLoc) || parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002914 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002915
Roman Divackye33098f2013-09-24 17:44:41 +00002916 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002917 if (parseToken(AsmToken::Comma,
2918 "unexpected token in '.fill' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00002919 parseTokenLoc(ExprLoc) || parseAbsoluteExpression(FillExpr) ||
Nirav Davea645433c2016-07-18 15:24:03 +00002920 parseToken(AsmToken::EndOfStatement,
2921 "unexpected token in '.fill' directive"))
Roman Divackye33098f2013-09-24 17:44:41 +00002922 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002923 }
2924 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002925
David Majnemer522d3db2014-02-01 07:19:38 +00002926 if (FillSize < 0) {
2927 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002928 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002929 }
2930 if (FillSize > 8) {
2931 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2932 FillSize = 8;
2933 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002934
David Majnemer522d3db2014-02-01 07:19:38 +00002935 if (!isUInt<32>(FillExpr) && FillSize > 4)
2936 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2937
Petr Hosek67a94a72016-05-28 05:57:48 +00002938 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002939
2940 return false;
2941}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002942
Jim Grosbach4b905842013-09-20 23:08:21 +00002943/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002944/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002945bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002946 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002947
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002948 const MCExpr *Offset;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002949 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002950 return true;
2951
2952 // Parse optional fill expression.
2953 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002954 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002955 if (parseToken(AsmToken::Comma, "unexpected token in '.org' directive") ||
2956 parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002957 return true;
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002958 }
2959
Nirav Davea645433c2016-07-18 15:24:03 +00002960 if (parseToken(AsmToken::EndOfStatement,
2961 "unexpected token in '.org' directive"))
2962 return true;
2963
Rafael Espindola7ae65d82015-11-04 23:59:18 +00002964 getStreamer().emitValueToOffset(Offset, FillExpr);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002965 return false;
2966}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002967
Jim Grosbach4b905842013-09-20 23:08:21 +00002968/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002969/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002970bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002971 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002972
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002973 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002974 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002975 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002976 return true;
2977
2978 SMLoc MaxBytesLoc;
2979 bool HasFillExpr = false;
2980 int64_t FillExpr = 0;
2981 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002982 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002983 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2984 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002985
2986 // The fill expression can be omitted while specifying a maximum number of
2987 // alignment bytes, e.g:
2988 // .align 3,,4
Nirav Davea645433c2016-07-18 15:24:03 +00002989 if (getTok().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002990 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002991 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002992 return true;
2993 }
2994
Nirav Davea645433c2016-07-18 15:24:03 +00002995 if (getTok().isNot(AsmToken::EndOfStatement)) {
2996 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00002997 parseTokenLoc(MaxBytesLoc) || parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002998 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002999 }
3000 }
3001
Nirav Davea645433c2016-07-18 15:24:03 +00003002 if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
3003 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003004
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003005 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003006 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003007
Nirav Davec0c0f7a12016-09-12 20:03:02 +00003008 // Always emit an alignment here even if we thrown an error.
3009 bool ReturnVal = false;
3010
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003011 // Compute alignment in bytes.
3012 if (IsPow2) {
3013 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003014 if (Alignment >= 32) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +00003015 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003016 Alignment = 31;
3017 }
3018
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003019 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003020 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003021 // Reject alignments that aren't either a power of two or zero,
3022 // for gas compatibility. Alignment of zero is silently rounded
3023 // up to one.
3024 if (Alignment == 0)
3025 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003026 if (!isPowerOf2_64(Alignment))
Nirav Davec0c0f7a12016-09-12 20:03:02 +00003027 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003028 }
3029
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003030 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003031 if (MaxBytesLoc.isValid()) {
3032 if (MaxBytesToFill < 1) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +00003033 ReturnVal |= Error(MaxBytesLoc,
3034 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003035 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003036 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003037 }
3038
3039 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003040 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003041 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003042 MaxBytesToFill = 0;
3043 }
3044 }
3045
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003046 // Check whether we should use optimal code alignment for this .align
3047 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003048 const MCSection *Section = getStreamer().getCurrentSection().first;
3049 assert(Section && "must have section to emit alignment");
3050 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003051 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3052 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003053 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003054 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003055 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003056 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3057 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003058 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003059
Nirav Davec0c0f7a12016-09-12 20:03:02 +00003060 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003061}
3062
Jim Grosbach4b905842013-09-20 23:08:21 +00003063/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003064/// ::= .file [number] filename
3065/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003066bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003067 // FIXME: I'm not sure what this is.
3068 int64_t FileNumber = -1;
3069 SMLoc FileNumberLoc = getLexer().getLoc();
3070 if (getLexer().is(AsmToken::Integer)) {
3071 FileNumber = getTok().getIntVal();
3072 Lex();
3073
3074 if (FileNumber < 1)
3075 return TokError("file number less than one");
3076 }
3077
Nirav Davea645433c2016-07-18 15:24:03 +00003078 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003079
3080 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003081 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003082 if (check(getTok().isNot(AsmToken::String),
3083 "unexpected token in '.file' directive") ||
3084 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003085 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003086
3087 StringRef Directory;
3088 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003089 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003090 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003091 if (check(FileNumber == -1,
3092 "explicit path specified, but no file number") ||
3093 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003094 return true;
3095 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003096 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003097 } else {
3098 Filename = Path;
3099 }
3100
Nirav Davea645433c2016-07-18 15:24:03 +00003101 if (parseToken(AsmToken::EndOfStatement,
3102 "unexpected token in '.file' directive"))
3103 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003104
3105 if (FileNumber == -1)
3106 getStreamer().EmitFileDirective(Filename);
3107 else {
David Blaikie22748082016-05-26 00:22:26 +00003108 // If there is -g option as well as debug info from directive file,
3109 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003110 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003111 getContext().setGenDwarfForAssembly(false);
3112 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003113 0)
Nirav Davec0c0f7a12016-09-12 20:03:02 +00003114 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003115 }
3116
3117 return false;
3118}
3119
Jim Grosbach4b905842013-09-20 23:08:21 +00003120/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003121/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003122bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003123 int64_t LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003124 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003125 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3126 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003127 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003128 // FIXME: Do something with the .line.
3129 }
Nirav Davea645433c2016-07-18 15:24:03 +00003130 if (parseToken(AsmToken::EndOfStatement,
3131 "unexpected token in '.line' directive"))
3132 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003133
3134 return false;
3135}
3136
Jim Grosbach4b905842013-09-20 23:08:21 +00003137/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003138/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3139/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3140/// The first number is a file number, must have been previously assigned with
3141/// a .file directive, the second number is the line number and optionally the
3142/// third number is a column position (zero if not specified). The remaining
3143/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003144bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003145 int64_t FileNumber = 0, LineNumber = 0;
3146 SMLoc Loc = getTok().getLoc();
3147 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3148 check(FileNumber < 1, Loc,
3149 "file number less than one in '.loc' directive") ||
3150 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3151 "unassigned file number in '.loc' directive"))
3152 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003153
Nirav Davea645433c2016-07-18 15:24:03 +00003154 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003155 if (getLexer().is(AsmToken::Integer)) {
3156 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003157 if (LineNumber < 0)
3158 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003159 Lex();
3160 }
3161
3162 int64_t ColumnPos = 0;
3163 if (getLexer().is(AsmToken::Integer)) {
3164 ColumnPos = getTok().getIntVal();
3165 if (ColumnPos < 0)
3166 return TokError("column position less than zero in '.loc' directive");
3167 Lex();
3168 }
3169
3170 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3171 unsigned Isa = 0;
3172 int64_t Discriminator = 0;
3173 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003174 while (true) {
Eli Bendersky17233942013-01-15 22:59:42 +00003175 if (getLexer().is(AsmToken::EndOfStatement))
3176 break;
3177
3178 StringRef Name;
3179 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003180 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003181 return TokError("unexpected token in '.loc' directive");
3182
3183 if (Name == "basic_block")
3184 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3185 else if (Name == "prologue_end")
3186 Flags |= DWARF2_FLAG_PROLOGUE_END;
3187 else if (Name == "epilogue_begin")
3188 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3189 else if (Name == "is_stmt") {
3190 Loc = getTok().getLoc();
3191 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003192 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003193 return true;
3194 // The expression must be the constant 0 or 1.
3195 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3196 int Value = MCE->getValue();
3197 if (Value == 0)
3198 Flags &= ~DWARF2_FLAG_IS_STMT;
3199 else if (Value == 1)
3200 Flags |= DWARF2_FLAG_IS_STMT;
3201 else
3202 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003203 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003204 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3205 }
Craig Topperf15655b2013-04-22 04:22:40 +00003206 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00003207 Loc = getTok().getLoc();
3208 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003209 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003210 return true;
3211 // The expression must be a constant greater or equal to 0.
3212 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3213 int Value = MCE->getValue();
3214 if (Value < 0)
3215 return Error(Loc, "isa number less than zero");
3216 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00003217 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003218 return Error(Loc, "isa number not a constant value");
3219 }
Craig Topperf15655b2013-04-22 04:22:40 +00003220 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003221 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00003222 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00003223 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003224 return Error(Loc, "unknown sub-directive in '.loc' directive");
3225 }
3226
3227 if (getLexer().is(AsmToken::EndOfStatement))
3228 break;
3229 }
3230 }
Nirav Davea645433c2016-07-18 15:24:03 +00003231 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003232
3233 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3234 Isa, Discriminator, StringRef());
3235
3236 return false;
3237}
3238
Jim Grosbach4b905842013-09-20 23:08:21 +00003239/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003240/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003241bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003242 return TokError("unsupported directive '.stabs'");
3243}
3244
Reid Kleckner2214ed82016-01-29 00:49:42 +00003245/// parseDirectiveCVFile
3246/// ::= .cv_file number filename
3247bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003248 SMLoc FileNumberLoc = getTok().getLoc();
3249 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003250 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003251
3252 if (parseIntToken(FileNumber,
3253 "expected file number in '.cv_file' directive") ||
3254 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3255 check(getTok().isNot(AsmToken::String),
3256 "unexpected token in '.cv_file' directive") ||
3257 // Usually directory and filename are together, otherwise just
3258 // directory. Allow the strings to have escaped octal character sequence.
3259 parseEscapedString(Filename) ||
3260 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003261 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003262 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003263
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003264 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1ab71992016-07-18 19:35:21 +00003265 Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003266
3267 return false;
3268}
3269
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003270bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3271 StringRef DirectiveName) {
3272 SMLoc Loc;
3273 return parseTokenLoc(Loc) ||
3274 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3275 "' directive") ||
3276 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3277 "expected function id within range [0, UINT_MAX)");
3278}
3279
3280bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3281 SMLoc Loc;
3282 return parseTokenLoc(Loc) ||
3283 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3284 "' directive") ||
3285 check(FileNumber < 1, Loc, "file number less than one in '" +
3286 DirectiveName + "' directive") ||
3287 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3288 "unassigned file number in '" + DirectiveName + "' directive");
3289}
3290
3291/// parseDirectiveCVFuncId
3292/// ::= .cv_func_id FunctionId
3293///
3294/// Introduces a function ID that can be used with .cv_loc.
3295bool AsmParser::parseDirectiveCVFuncId() {
3296 SMLoc FunctionIdLoc = getTok().getLoc();
3297 int64_t FunctionId;
3298
3299 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3300 parseToken(AsmToken::EndOfStatement,
3301 "unexpected token in '.cv_func_id' directive"))
3302 return true;
3303
3304 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
3305 Error(FunctionIdLoc, "function id already allocated");
3306
3307 return false;
3308}
3309
3310/// parseDirectiveCVInlineSiteId
3311/// ::= .cv_inline_site_id FunctionId
3312/// "within" IAFunc
3313/// "inlined_at" IAFile IALine [IACol]
3314///
3315/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3316/// at" source location information for use in the line table of the caller,
3317/// whether the caller is a real function or another inlined call site.
3318bool AsmParser::parseDirectiveCVInlineSiteId() {
3319 SMLoc FunctionIdLoc = getTok().getLoc();
3320 int64_t FunctionId;
3321 int64_t IAFunc;
3322 int64_t IAFile;
3323 int64_t IALine;
3324 int64_t IACol = 0;
3325
3326 // FunctionId
3327 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3328 return true;
3329
3330 // "within"
3331 if (check((getLexer().isNot(AsmToken::Identifier) ||
3332 getTok().getIdentifier() != "within"),
3333 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3334 return true;
3335 Lex();
3336
3337 // IAFunc
3338 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3339 return true;
3340
3341 // "inlined_at"
3342 if (check((getLexer().isNot(AsmToken::Identifier) ||
3343 getTok().getIdentifier() != "inlined_at"),
3344 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3345 "directive") )
3346 return true;
3347 Lex();
3348
3349 // IAFile IALine
3350 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3351 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3352 return true;
3353
3354 // [IACol]
3355 if (getLexer().is(AsmToken::Integer)) {
3356 IACol = getTok().getIntVal();
3357 Lex();
3358 }
3359
3360 if (parseToken(AsmToken::EndOfStatement,
3361 "unexpected token in '.cv_inline_site_id' directive"))
3362 return true;
3363
3364 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3365 IALine, IACol, FunctionIdLoc))
Nirav Davec0c0f7a12016-09-12 20:03:02 +00003366 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003367
3368 return false;
3369}
3370
Reid Kleckner2214ed82016-01-29 00:49:42 +00003371/// parseDirectiveCVLoc
3372/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3373/// [is_stmt VALUE]
3374/// The first number is a file number, must have been previously assigned with
3375/// a .file directive, the second number is the line number and optionally the
3376/// third number is a column position (zero if not specified). The remaining
3377/// optional items are .loc sub-directives.
3378bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003379 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003380 SMLoc Loc;
3381 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003382 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3383 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003384 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003385
3386 int64_t LineNumber = 0;
3387 if (getLexer().is(AsmToken::Integer)) {
3388 LineNumber = getTok().getIntVal();
3389 if (LineNumber < 0)
3390 return TokError("line number less than zero in '.cv_loc' directive");
3391 Lex();
3392 }
3393
3394 int64_t ColumnPos = 0;
3395 if (getLexer().is(AsmToken::Integer)) {
3396 ColumnPos = getTok().getIntVal();
3397 if (ColumnPos < 0)
3398 return TokError("column position less than zero in '.cv_loc' directive");
3399 Lex();
3400 }
3401
3402 bool PrologueEnd = false;
3403 uint64_t IsStmt = 0;
3404 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3405 StringRef Name;
3406 SMLoc Loc = getTok().getLoc();
3407 if (parseIdentifier(Name))
3408 return TokError("unexpected token in '.cv_loc' directive");
3409
3410 if (Name == "prologue_end")
3411 PrologueEnd = true;
3412 else if (Name == "is_stmt") {
3413 Loc = getTok().getLoc();
3414 const MCExpr *Value;
3415 if (parseExpression(Value))
3416 return true;
3417 // The expression must be the constant 0 or 1.
3418 IsStmt = ~0ULL;
3419 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3420 IsStmt = MCE->getValue();
3421
3422 if (IsStmt > 1)
3423 return Error(Loc, "is_stmt value not 0 or 1");
3424 } else {
3425 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3426 }
3427 }
Nirav Davea645433c2016-07-18 15:24:03 +00003428 Lex();
Reid Kleckner2214ed82016-01-29 00:49:42 +00003429
3430 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003431 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3432 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003433 return false;
3434}
3435
3436/// parseDirectiveCVLinetable
3437/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3438bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003439 int64_t FunctionId;
3440 StringRef FnStartName, FnEndName;
3441 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003442 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003443 parseToken(AsmToken::Comma,
3444 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003445 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3446 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003447 parseToken(AsmToken::Comma,
3448 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003449 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3450 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003451 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003452
3453 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3454 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3455
3456 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3457 return false;
3458}
3459
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003460/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003461/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003462bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003463 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3464 StringRef FnStartName, FnEndName;
3465 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003466 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003467 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003468 parseIntToken(
3469 SourceFileId,
3470 "expected SourceField in '.cv_inline_linetable' directive") ||
3471 check(SourceFileId <= 0, Loc,
3472 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003473 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003474 parseIntToken(
3475 SourceLineNum,
3476 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3477 check(SourceLineNum < 0, Loc,
3478 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003479 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3480 "expected identifier in directive") ||
3481 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3482 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003483 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003484
Nirav Davea645433c2016-07-18 15:24:03 +00003485 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3486 return true;
3487
3488 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3489 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003490 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3491 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003492 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003493 return false;
3494}
3495
David Majnemer408b5e62016-02-05 01:55:49 +00003496/// parseDirectiveCVDefRange
3497/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3498bool AsmParser::parseDirectiveCVDefRange() {
3499 SMLoc Loc;
3500 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3501 while (getLexer().is(AsmToken::Identifier)) {
3502 Loc = getLexer().getLoc();
3503 StringRef GapStartName;
3504 if (parseIdentifier(GapStartName))
3505 return Error(Loc, "expected identifier in directive");
3506 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3507
3508 Loc = getLexer().getLoc();
3509 StringRef GapEndName;
3510 if (parseIdentifier(GapEndName))
3511 return Error(Loc, "expected identifier in directive");
3512 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3513
3514 Ranges.push_back({GapStartSym, GapEndSym});
3515 }
3516
David Majnemer408b5e62016-02-05 01:55:49 +00003517 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003518 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3519 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003520 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003521
3522 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3523 return false;
3524}
3525
Reid Kleckner2214ed82016-01-29 00:49:42 +00003526/// parseDirectiveCVStringTable
3527/// ::= .cv_stringtable
3528bool AsmParser::parseDirectiveCVStringTable() {
3529 getStreamer().EmitCVStringTableDirective();
3530 return false;
3531}
3532
3533/// parseDirectiveCVFileChecksums
3534/// ::= .cv_filechecksums
3535bool AsmParser::parseDirectiveCVFileChecksums() {
3536 getStreamer().EmitCVFileChecksumsDirective();
3537 return false;
3538}
3539
Jim Grosbach4b905842013-09-20 23:08:21 +00003540/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003541/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003542bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003543 StringRef Name;
3544 bool EH = false;
3545 bool Debug = false;
3546
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003547 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003548 return TokError("Expected an identifier");
3549
3550 if (Name == ".eh_frame")
3551 EH = true;
3552 else if (Name == ".debug_frame")
3553 Debug = true;
3554
3555 if (getLexer().is(AsmToken::Comma)) {
3556 Lex();
3557
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003558 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003559 return TokError("Expected an identifier");
3560
3561 if (Name == ".eh_frame")
3562 EH = true;
3563 else if (Name == ".debug_frame")
3564 Debug = true;
3565 }
3566
3567 getStreamer().EmitCFISections(EH, Debug);
3568 return false;
3569}
3570
Jim Grosbach4b905842013-09-20 23:08:21 +00003571/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003572/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003573bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003574 StringRef Simple;
3575 if (getLexer().isNot(AsmToken::EndOfStatement))
3576 if (parseIdentifier(Simple) || Simple != "simple")
3577 return TokError("unexpected token in .cfi_startproc directive");
3578
Nirav Davea645433c2016-07-18 15:24:03 +00003579 if (parseToken(AsmToken::EndOfStatement, "Expected end of statement"))
3580 return true;
3581
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003582 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003583 return false;
3584}
3585
Jim Grosbach4b905842013-09-20 23:08:21 +00003586/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003587/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003588bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003589 getStreamer().EmitCFIEndProc();
3590 return false;
3591}
3592
Jim Grosbach4b905842013-09-20 23:08:21 +00003593/// \brief parse register name or number.
3594bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003595 SMLoc DirectiveLoc) {
3596 unsigned RegNo;
3597
3598 if (getLexer().isNot(AsmToken::Integer)) {
3599 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3600 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003601 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003602 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003603 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003604
3605 return false;
3606}
3607
Jim Grosbach4b905842013-09-20 23:08:21 +00003608/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003609/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003610bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003611 int64_t Register = 0, Offset = 0;
3612 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3613 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3614 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003615 return true;
3616
3617 getStreamer().EmitCFIDefCfa(Register, Offset);
3618 return false;
3619}
3620
Jim Grosbach4b905842013-09-20 23:08:21 +00003621/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003622/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003623bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003624 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003625 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003626 return true;
3627
3628 getStreamer().EmitCFIDefCfaOffset(Offset);
3629 return false;
3630}
3631
Jim Grosbach4b905842013-09-20 23:08:21 +00003632/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003633/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003634bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003635 int64_t Register1 = 0, Register2 = 0;
3636 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3637 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3638 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003639 return true;
3640
3641 getStreamer().EmitCFIRegister(Register1, Register2);
3642 return false;
3643}
3644
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003645/// parseDirectiveCFIWindowSave
3646/// ::= .cfi_window_save
3647bool AsmParser::parseDirectiveCFIWindowSave() {
3648 getStreamer().EmitCFIWindowSave();
3649 return false;
3650}
3651
Jim Grosbach4b905842013-09-20 23:08:21 +00003652/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003653/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003654bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003655 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003656 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003657 return true;
3658
3659 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3660 return false;
3661}
3662
Jim Grosbach4b905842013-09-20 23:08:21 +00003663/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003664/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003665bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003666 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003667 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003668 return true;
3669
3670 getStreamer().EmitCFIDefCfaRegister(Register);
3671 return false;
3672}
3673
Jim Grosbach4b905842013-09-20 23:08:21 +00003674/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003675/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003676bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003677 int64_t Register = 0;
3678 int64_t Offset = 0;
3679
Nirav Davea645433c2016-07-18 15:24:03 +00003680 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3681 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3682 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003683 return true;
3684
3685 getStreamer().EmitCFIOffset(Register, Offset);
3686 return false;
3687}
3688
Jim Grosbach4b905842013-09-20 23:08:21 +00003689/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003690/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003691bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003692 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003693
Nirav Davea645433c2016-07-18 15:24:03 +00003694 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3695 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3696 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003697 return true;
3698
3699 getStreamer().EmitCFIRelOffset(Register, Offset);
3700 return false;
3701}
3702
3703static bool isValidEncoding(int64_t Encoding) {
3704 if (Encoding & ~0xff)
3705 return false;
3706
3707 if (Encoding == dwarf::DW_EH_PE_omit)
3708 return true;
3709
3710 const unsigned Format = Encoding & 0xf;
3711 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3712 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3713 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3714 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3715 return false;
3716
3717 const unsigned Application = Encoding & 0x70;
3718 if (Application != dwarf::DW_EH_PE_absptr &&
3719 Application != dwarf::DW_EH_PE_pcrel)
3720 return false;
3721
3722 return true;
3723}
3724
Jim Grosbach4b905842013-09-20 23:08:21 +00003725/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003726/// IsPersonality true for cfi_personality, false for cfi_lsda
3727/// ::= .cfi_personality encoding, [symbol_name]
3728/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003729bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003730 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003731 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003732 return true;
3733 if (Encoding == dwarf::DW_EH_PE_omit)
3734 return false;
3735
Eli Bendersky17233942013-01-15 22:59:42 +00003736 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003737 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3738 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3739 check(parseIdentifier(Name), "expected identifier in directive"))
3740 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003741
Jim Grosbach6f482002015-05-18 18:43:14 +00003742 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003743
3744 if (IsPersonality)
3745 getStreamer().EmitCFIPersonality(Sym, Encoding);
3746 else
3747 getStreamer().EmitCFILsda(Sym, Encoding);
3748 return false;
3749}
3750
Jim Grosbach4b905842013-09-20 23:08:21 +00003751/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003752/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003753bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003754 getStreamer().EmitCFIRememberState();
3755 return false;
3756}
3757
Jim Grosbach4b905842013-09-20 23:08:21 +00003758/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003759/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003760bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003761 getStreamer().EmitCFIRestoreState();
3762 return false;
3763}
3764
Jim Grosbach4b905842013-09-20 23:08:21 +00003765/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003766/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003767bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003768 int64_t Register = 0;
3769
Jim Grosbach4b905842013-09-20 23:08:21 +00003770 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003771 return true;
3772
3773 getStreamer().EmitCFISameValue(Register);
3774 return false;
3775}
3776
Jim Grosbach4b905842013-09-20 23:08:21 +00003777/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003778/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003779bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003780 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003781 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003782 return true;
3783
3784 getStreamer().EmitCFIRestore(Register);
3785 return false;
3786}
3787
Jim Grosbach4b905842013-09-20 23:08:21 +00003788/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003789/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003790bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003791 std::string Values;
3792 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003793 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003794 return true;
3795
3796 Values.push_back((uint8_t)CurrValue);
3797
3798 while (getLexer().is(AsmToken::Comma)) {
3799 Lex();
3800
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003801 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003802 return true;
3803
3804 Values.push_back((uint8_t)CurrValue);
3805 }
3806
3807 getStreamer().EmitCFIEscape(Values);
3808 return false;
3809}
3810
Jim Grosbach4b905842013-09-20 23:08:21 +00003811/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003812/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003813bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003814 if (parseToken(AsmToken::EndOfStatement,
3815 "unexpected token in '.cfi_signal_frame'"))
3816 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003817
3818 getStreamer().EmitCFISignalFrame();
3819 return false;
3820}
3821
Jim Grosbach4b905842013-09-20 23:08:21 +00003822/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003823/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003824bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003825 int64_t Register = 0;
3826
Jim Grosbach4b905842013-09-20 23:08:21 +00003827 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003828 return true;
3829
3830 getStreamer().EmitCFIUndefined(Register);
3831 return false;
3832}
3833
Jim Grosbach4b905842013-09-20 23:08:21 +00003834/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003835/// ::= .macros_on
3836/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003837bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003838 if (parseToken(AsmToken::EndOfStatement,
3839 "unexpected token in '" + Directive + "' directive"))
3840 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003841
Jim Grosbach4b905842013-09-20 23:08:21 +00003842 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003843 return false;
3844}
3845
Jim Grosbach4b905842013-09-20 23:08:21 +00003846/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003847/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003848bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003849 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003850 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003851 return TokError("expected identifier in '.macro' directive");
3852
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003853 if (getLexer().is(AsmToken::Comma))
3854 Lex();
3855
Eli Bendersky17233942013-01-15 22:59:42 +00003856 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003857 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003858
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003859 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003860 return Error(Lexer.getLoc(),
3861 "Vararg parameter '" + Parameters.back().Name +
3862 "' should be last one in the list of parameters.");
3863
David Majnemer91fc4c22014-01-29 18:57:46 +00003864 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003865 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003866 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003867
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003868 if (Lexer.is(AsmToken::Colon)) {
3869 Lex(); // consume ':'
3870
3871 SMLoc QualLoc;
3872 StringRef Qualifier;
3873
3874 QualLoc = Lexer.getLoc();
3875 if (parseIdentifier(Qualifier))
3876 return Error(QualLoc, "missing parameter qualifier for "
3877 "'" + Parameter.Name + "' in macro '" + Name + "'");
3878
3879 if (Qualifier == "req")
3880 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003881 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003882 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003883 else
3884 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3885 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3886 }
3887
David Majnemer91fc4c22014-01-29 18:57:46 +00003888 if (getLexer().is(AsmToken::Equal)) {
3889 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003890
3891 SMLoc ParamLoc;
3892
3893 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003894 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003895 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003896
3897 if (Parameter.Required)
3898 Warning(ParamLoc, "pointless default value for required parameter "
3899 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003900 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003901
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003902 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003903
3904 if (getLexer().is(AsmToken::Comma))
3905 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003906 }
3907
Nirav Dave1180e6892016-06-02 17:15:05 +00003908 // Eat just the end of statement.
3909 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003910
Nirav Dave1180e6892016-06-02 17:15:05 +00003911 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003912 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003913 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003914 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003915 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003916 // Ignore Lexing errors in macros.
3917 while (Lexer.is(AsmToken::Error)) {
3918 Lexer.Lex();
3919 }
3920
Eli Bendersky17233942013-01-15 22:59:42 +00003921 // Check whether we have reached the end of the file.
3922 if (getLexer().is(AsmToken::Eof))
3923 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3924
3925 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003926 if (getLexer().is(AsmToken::Identifier)) {
3927 if (getTok().getIdentifier() == ".endm" ||
3928 getTok().getIdentifier() == ".endmacro") {
3929 if (MacroDepth == 0) { // Outermost macro.
3930 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003931 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003932 if (getLexer().isNot(AsmToken::EndOfStatement))
3933 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3934 "' directive");
3935 break;
3936 } else {
3937 // Otherwise we just found the end of an inner macro.
3938 --MacroDepth;
3939 }
3940 } else if (getTok().getIdentifier() == ".macro") {
3941 // We allow nested macros. Those aren't instantiated until the outermost
3942 // macro is expanded so just ignore them for now.
3943 ++MacroDepth;
3944 }
Eli Bendersky17233942013-01-15 22:59:42 +00003945 }
3946
3947 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003948 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003949 }
3950
Jim Grosbach4b905842013-09-20 23:08:21 +00003951 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003952 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3953 }
3954
3955 const char *BodyStart = StartToken.getLoc().getPointer();
3956 const char *BodyEnd = EndToken.getLoc().getPointer();
3957 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003958 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003959 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003960 return false;
3961}
3962
Jim Grosbach4b905842013-09-20 23:08:21 +00003963/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003964///
3965/// With the support added for named parameters there may be code out there that
3966/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003967/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003968/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003969/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003970/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3971/// warning that the positional parameter found in body which have no effect.
3972/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003973/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003974/// intended or change the macro to use the named parameters. It is possible
3975/// this warning will trigger when the none of the named parameters are used
3976/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003977void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003978 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003979 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003980 // If this macro is not defined with named parameters the warning we are
3981 // checking for here doesn't apply.
3982 unsigned NParameters = Parameters.size();
3983 if (NParameters == 0)
3984 return;
3985
3986 bool NamedParametersFound = false;
3987 bool PositionalParametersFound = false;
3988
3989 // Look at the body of the macro for use of both the named parameters and what
3990 // are likely to be positional parameters. This is what expandMacro() is
3991 // doing when it finds the parameters in the body.
3992 while (!Body.empty()) {
3993 // Scan for the next possible parameter.
3994 std::size_t End = Body.size(), Pos = 0;
3995 for (; Pos != End; ++Pos) {
3996 // Check for a substitution or escape.
3997 // This macro is defined with parameters, look for \foo, \bar, etc.
3998 if (Body[Pos] == '\\' && Pos + 1 != End)
3999 break;
4000
4001 // This macro should have parameters, but look for $0, $1, ..., $n too.
4002 if (Body[Pos] != '$' || Pos + 1 == End)
4003 continue;
4004 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004005 if (Next == '$' || Next == 'n' ||
4006 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004007 break;
4008 }
4009
4010 // Check if we reached the end.
4011 if (Pos == End)
4012 break;
4013
4014 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004015 switch (Body[Pos + 1]) {
4016 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004017 case '$':
4018 break;
4019
Jim Grosbach4b905842013-09-20 23:08:21 +00004020 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004021 case 'n':
4022 PositionalParametersFound = true;
4023 break;
4024
Jim Grosbach4b905842013-09-20 23:08:21 +00004025 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004026 default: {
4027 PositionalParametersFound = true;
4028 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004029 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004030 }
4031 Pos += 2;
4032 } else {
4033 unsigned I = Pos + 1;
4034 while (isIdentifierChar(Body[I]) && I + 1 != End)
4035 ++I;
4036
Jim Grosbach4b905842013-09-20 23:08:21 +00004037 const char *Begin = Body.data() + Pos + 1;
4038 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004039 unsigned Index = 0;
4040 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004041 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004042 break;
4043
4044 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004045 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4046 Pos += 3;
4047 else {
4048 Pos = I;
4049 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004050 } else {
4051 NamedParametersFound = true;
4052 Pos += 1 + Argument.size();
4053 }
4054 }
4055 // Update the scan point.
4056 Body = Body.substr(Pos);
4057 }
4058
4059 if (!NamedParametersFound && PositionalParametersFound)
4060 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4061 "used in macro body, possible positional parameter "
4062 "found in body which will have no effect");
4063}
4064
Nico Weber155dccd12014-07-24 17:08:39 +00004065/// parseDirectiveExitMacro
4066/// ::= .exitm
4067bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004068 if (parseToken(AsmToken::EndOfStatement,
4069 "unexpected token in '" + Directive + "' directive"))
4070 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004071
4072 if (!isInsideMacroInstantiation())
4073 return TokError("unexpected '" + Directive + "' in file, "
4074 "no current macro definition");
4075
4076 // Exit all conditionals that are active in the current macro.
4077 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4078 TheCondState = TheCondStack.back();
4079 TheCondStack.pop_back();
4080 }
4081
4082 handleMacroExit();
4083 return false;
4084}
4085
Jim Grosbach4b905842013-09-20 23:08:21 +00004086/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004087/// ::= .endm
4088/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004089bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004090 if (getLexer().isNot(AsmToken::EndOfStatement))
4091 return TokError("unexpected token in '" + Directive + "' directive");
4092
4093 // If we are inside a macro instantiation, terminate the current
4094 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004095 if (isInsideMacroInstantiation()) {
4096 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004097 return false;
4098 }
4099
4100 // Otherwise, this .endmacro is a stray entry in the file; well formed
4101 // .endmacro directives are handled during the macro definition parsing.
4102 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004103 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004104}
4105
Jim Grosbach4b905842013-09-20 23:08:21 +00004106/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004107/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004108bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004109 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004110 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004111 if (parseTokenLoc(Loc) ||
4112 check(parseIdentifier(Name), Loc,
4113 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004114 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004115 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004116 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004117
Nirav Dave1ab71992016-07-18 19:35:21 +00004118 if (!lookupMacro(Name))
4119 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4120
Jim Grosbach4b905842013-09-20 23:08:21 +00004121 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004122 return false;
4123}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004124
Jim Grosbach4b905842013-09-20 23:08:21 +00004125/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004126/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004127bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004128 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00004129
4130 // Expect a single argument: an expression that evaluates to a constant
4131 // in the inclusive range 0-30.
4132 SMLoc ExprLoc = getLexer().getLoc();
4133 int64_t AlignSizePow2;
Nirav Davea645433c2016-07-18 15:24:03 +00004134 if (parseAbsoluteExpression(AlignSizePow2) ||
4135 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4136 "in '.bundle_align_mode' "
4137 "directive") ||
4138 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4139 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004140 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004141
4142 // Because of AlignSizePow2's verified range we can safely truncate it to
4143 // unsigned.
4144 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4145 return false;
4146}
4147
Jim Grosbach4b905842013-09-20 23:08:21 +00004148/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004149/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004150bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004151 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00004152 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004153
Eli Bendersky802b6282013-01-07 21:51:08 +00004154 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4155 StringRef Option;
4156 SMLoc Loc = getTok().getLoc();
4157 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00004158 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004159
Nirav Davea645433c2016-07-18 15:24:03 +00004160 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4161 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
4162 check(getTok().isNot(AsmToken::EndOfStatement), Loc,
4163 "unexpected token after '.bundle_lock' directive option"))
4164 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004165 AlignToEnd = true;
4166 }
4167
Eli Benderskyf483ff92012-12-20 19:05:53 +00004168 Lex();
4169
Eli Bendersky802b6282013-01-07 21:51:08 +00004170 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004171 return false;
4172}
4173
Jim Grosbach4b905842013-09-20 23:08:21 +00004174/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004175/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004176bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004177 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00004178
Nirav Davea645433c2016-07-18 15:24:03 +00004179 if (parseToken(AsmToken::EndOfStatement,
4180 "unexpected token in '.bundle_unlock' directive"))
4181 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004182
4183 getStreamer().EmitBundleUnlock();
4184 return false;
4185}
4186
Jim Grosbach4b905842013-09-20 23:08:21 +00004187/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004188/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004189bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004190 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004191
Petr Hosek67a94a72016-05-28 05:57:48 +00004192 SMLoc NumBytesLoc = Lexer.getLoc();
4193 const MCExpr *NumBytes;
4194 if (parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004195 return true;
4196
4197 int64_t FillExpr = 0;
4198 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004199
Nirav Davea645433c2016-07-18 15:24:03 +00004200 if (parseToken(AsmToken::Comma,
4201 "unexpected token in '" + Twine(IDVal) + "' directive") ||
4202 parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00004203 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004204 }
4205
Nirav Davea645433c2016-07-18 15:24:03 +00004206 if (parseToken(AsmToken::EndOfStatement,
4207 "unexpected token in '" + Twine(IDVal) + "' directive"))
4208 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004209
Eli Bendersky17233942013-01-15 22:59:42 +00004210 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004211 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004212
4213 return false;
4214}
4215
Jim Grosbach4b905842013-09-20 23:08:21 +00004216/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004217/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004218bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004219 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004220 const MCExpr *Value;
4221
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004222 while (true) {
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004223 if (parseExpression(Value))
4224 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004225
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004226 if (Signed)
4227 getStreamer().EmitSLEB128Value(Value);
4228 else
4229 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00004230
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004231 if (getLexer().is(AsmToken::EndOfStatement))
4232 break;
4233
Nirav Davea645433c2016-07-18 15:24:03 +00004234 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
4235 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004236 }
Nirav Davea645433c2016-07-18 15:24:03 +00004237 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004238
4239 return false;
4240}
4241
Jim Grosbach4b905842013-09-20 23:08:21 +00004242/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004243/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004244bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004245 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004246 while (true) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004247 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004248 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004249
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004250 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004251 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004252
Jim Grosbach6f482002015-05-18 18:43:14 +00004253 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00004254
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004255 // Assembler local symbols don't make any sense here. Complain loudly.
4256 if (Sym->isTemporary())
4257 return Error(Loc, "non-local symbol required in directive");
4258
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00004259 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4260 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00004261
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004262 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004263 break;
4264
Nirav Davea645433c2016-07-18 15:24:03 +00004265 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
4266 return true;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004267 }
4268 }
4269
Sean Callanan686ed8d2010-01-19 20:22:31 +00004270 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00004271 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004272}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004273
Jim Grosbach4b905842013-09-20 23:08:21 +00004274/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004275/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004276bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004277 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00004278
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004279 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004280 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004281 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004282 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004283
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004284 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004285 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004286
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004287 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004288 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004289 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004290
4291 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004292 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004293 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004294 return true;
4295
4296 int64_t Pow2Alignment = 0;
4297 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004298 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004299 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004300 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004301 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004302 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004303
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004304 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4305 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004306 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4307
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004308 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004309 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4310 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004311 if (!isPowerOf2_64(Pow2Alignment))
4312 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4313 Pow2Alignment = Log2_64(Pow2Alignment);
4314 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004315 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004316
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004317 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00004318 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004319
Sean Callanan686ed8d2010-01-19 20:22:31 +00004320 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004321
Chris Lattner28ad7542009-07-09 17:25:12 +00004322 // NOTE: a size of zero for a .comm should create a undefined symbol
4323 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004324 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004325 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004326 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004327
Eric Christopherbc818852010-05-14 01:38:54 +00004328 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004329 // may internally end up wanting an alignment in bytes.
4330 // FIXME: Diagnose overflow.
4331 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004332 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004333 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004334
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004335 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004336 return Error(IDLoc, "invalid symbol redefinition");
4337
Chris Lattner28ad7542009-07-09 17:25:12 +00004338 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004339 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004340 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004341 return false;
4342 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004343
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004344 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004345 return false;
4346}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004347
Jim Grosbach4b905842013-09-20 23:08:21 +00004348/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004349/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004350bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004351 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004352 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004353
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004354 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004355 if (parseToken(AsmToken::EndOfStatement,
4356 "unexpected token in '.abort' directive"))
4357 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004358
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004359 if (Str.empty())
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004360 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004361 else
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004362 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004363 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004364
4365 return false;
4366}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004367
Jim Grosbach4b905842013-09-20 23:08:21 +00004368/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004369/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004370bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004371 // Allow the strings to have escaped octal character sequence.
4372 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004373 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004374
Nirav Davea645433c2016-07-18 15:24:03 +00004375 if (check(getTok().isNot(AsmToken::String),
4376 "expected string in '.include' directive") ||
4377 parseEscapedString(Filename) ||
4378 check(getTok().isNot(AsmToken::EndOfStatement),
4379 "unexpected token in '.include' directive") ||
4380 // Attempt to switch the lexer to the included file before consuming the
4381 // end of statement to avoid losing it when we switch.
4382 check(enterIncludeFile(Filename), IncludeLoc,
4383 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004384 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004385
4386 return false;
4387}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004388
Jim Grosbach4b905842013-09-20 23:08:21 +00004389/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00004390/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004391bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004392 // Allow the strings to have escaped octal character sequence.
4393 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004394 SMLoc IncbinLoc = getTok().getLoc();
4395 if (check(getTok().isNot(AsmToken::String),
4396 "expected string in '.incbin' directive") ||
4397 parseEscapedString(Filename) ||
4398 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004399 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004400 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004401
4402 // Attempt to process the included file.
4403 if (processIncbinFile(Filename))
4404 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004405 return false;
4406}
4407
Jim Grosbach4b905842013-09-20 23:08:21 +00004408/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004409/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4410bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004411 TheCondStack.push_back(TheCondState);
4412 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004413 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004414 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004415 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004416 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004417 if (parseAbsoluteExpression(ExprValue) ||
4418 parseToken(AsmToken::EndOfStatement,
4419 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004420 return true;
4421
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004422 switch (DirKind) {
4423 default:
4424 llvm_unreachable("unsupported directive");
4425 case DK_IF:
4426 case DK_IFNE:
4427 break;
4428 case DK_IFEQ:
4429 ExprValue = ExprValue == 0;
4430 break;
4431 case DK_IFGE:
4432 ExprValue = ExprValue >= 0;
4433 break;
4434 case DK_IFGT:
4435 ExprValue = ExprValue > 0;
4436 break;
4437 case DK_IFLE:
4438 ExprValue = ExprValue <= 0;
4439 break;
4440 case DK_IFLT:
4441 ExprValue = ExprValue < 0;
4442 break;
4443 }
4444
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004445 TheCondState.CondMet = ExprValue;
4446 TheCondState.Ignore = !TheCondState.CondMet;
4447 }
4448
4449 return false;
4450}
4451
Jim Grosbach4b905842013-09-20 23:08:21 +00004452/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004453/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004454bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004455 TheCondStack.push_back(TheCondState);
4456 TheCondState.TheCond = AsmCond::IfCond;
4457
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004458 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004459 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004460 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004461 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004462
Nirav Davea645433c2016-07-18 15:24:03 +00004463 if (parseToken(AsmToken::EndOfStatement,
4464 "unexpected token in '.ifb' directive"))
4465 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004466
4467 TheCondState.CondMet = ExpectBlank == Str.empty();
4468 TheCondState.Ignore = !TheCondState.CondMet;
4469 }
4470
4471 return false;
4472}
4473
Jim Grosbach4b905842013-09-20 23:08:21 +00004474/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004475/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004476/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004477bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004478 TheCondStack.push_back(TheCondState);
4479 TheCondState.TheCond = AsmCond::IfCond;
4480
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004481 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004482 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004483 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004484 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004485
Nirav Davea645433c2016-07-18 15:24:03 +00004486 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4487 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004488
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004489 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004490
Nirav Davea645433c2016-07-18 15:24:03 +00004491 if (parseToken(AsmToken::EndOfStatement,
4492 "unexpected token in '.ifc' directive"))
4493 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004494
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004495 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004496 TheCondState.Ignore = !TheCondState.CondMet;
4497 }
4498
4499 return false;
4500}
4501
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004502/// parseDirectiveIfeqs
4503/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004504bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004505 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004506 if (ExpectEqual)
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004507 return TokError("expected string parameter for '.ifeqs' directive");
4508 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004509 }
4510
4511 StringRef String1 = getTok().getStringContents();
4512 Lex();
4513
4514 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004515 if (ExpectEqual)
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004516 return TokError(
4517 "expected comma after first string for '.ifeqs' directive");
4518 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004519 }
4520
4521 Lex();
4522
4523 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004524 if (ExpectEqual)
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004525 return TokError("expected string parameter for '.ifeqs' directive");
4526 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004527 }
4528
4529 StringRef String2 = getTok().getStringContents();
4530 Lex();
4531
4532 TheCondStack.push_back(TheCondState);
4533 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004534 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004535 TheCondState.Ignore = !TheCondState.CondMet;
4536
4537 return false;
4538}
4539
Jim Grosbach4b905842013-09-20 23:08:21 +00004540/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004541/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004542bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004543 StringRef Name;
4544 TheCondStack.push_back(TheCondState);
4545 TheCondState.TheCond = AsmCond::IfCond;
4546
4547 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004548 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004549 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004550 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4551 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4552 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004553
Jim Grosbach6f482002015-05-18 18:43:14 +00004554 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004555
4556 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004557 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004558 else
Craig Topper353eda42014-04-24 06:44:33 +00004559 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004560 TheCondState.Ignore = !TheCondState.CondMet;
4561 }
4562
4563 return false;
4564}
4565
Jim Grosbach4b905842013-09-20 23:08:21 +00004566/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004567/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004568bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004569 if (TheCondState.TheCond != AsmCond::IfCond &&
4570 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004571 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4572 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004573 TheCondState.TheCond = AsmCond::ElseIfCond;
4574
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004575 bool LastIgnoreState = false;
4576 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004577 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004578 if (LastIgnoreState || TheCondState.CondMet) {
4579 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004580 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004581 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004582 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004583 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004584 return true;
4585
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004586 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004587 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004588
Sean Callanan686ed8d2010-01-19 20:22:31 +00004589 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004590 TheCondState.CondMet = ExprValue;
4591 TheCondState.Ignore = !TheCondState.CondMet;
4592 }
4593
4594 return false;
4595}
4596
Jim Grosbach4b905842013-09-20 23:08:21 +00004597/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004598/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004599bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004600 if (parseToken(AsmToken::EndOfStatement,
4601 "unexpected token in '.else' directive"))
4602 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004603
4604 if (TheCondState.TheCond != AsmCond::IfCond &&
4605 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004606 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4607 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004608 TheCondState.TheCond = AsmCond::ElseCond;
4609 bool LastIgnoreState = false;
4610 if (!TheCondStack.empty())
4611 LastIgnoreState = TheCondStack.back().Ignore;
4612 if (LastIgnoreState || TheCondState.CondMet)
4613 TheCondState.Ignore = true;
4614 else
4615 TheCondState.Ignore = false;
4616
4617 return false;
4618}
4619
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004620/// parseDirectiveEnd
4621/// ::= .end
4622bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004623 if (parseToken(AsmToken::EndOfStatement,
4624 "unexpected token in '.end' directive"))
4625 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004626
4627 while (Lexer.isNot(AsmToken::Eof))
4628 Lex();
4629
4630 return false;
4631}
4632
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004633/// parseDirectiveError
4634/// ::= .err
4635/// ::= .error [string]
4636bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4637 if (!TheCondStack.empty()) {
4638 if (TheCondStack.back().Ignore) {
4639 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004640 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004641 }
4642 }
4643
4644 if (!WithMessage)
4645 return Error(L, ".err encountered");
4646
4647 StringRef Message = ".error directive invoked in source file";
4648 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004649 if (Lexer.isNot(AsmToken::String))
4650 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004651
4652 Message = getTok().getStringContents();
4653 Lex();
4654 }
4655
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004656 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004657}
4658
Nico Weber404012b2014-07-24 16:26:06 +00004659/// parseDirectiveWarning
4660/// ::= .warning [string]
4661bool AsmParser::parseDirectiveWarning(SMLoc L) {
4662 if (!TheCondStack.empty()) {
4663 if (TheCondStack.back().Ignore) {
4664 eatToEndOfStatement();
4665 return false;
4666 }
4667 }
4668
4669 StringRef Message = ".warning directive invoked in source file";
4670 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004671 if (Lexer.isNot(AsmToken::String))
4672 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004673
4674 Message = getTok().getStringContents();
4675 Lex();
4676 }
4677
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004678 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004679}
4680
Jim Grosbach4b905842013-09-20 23:08:21 +00004681/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004682/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004683bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004684 if (parseToken(AsmToken::EndOfStatement,
4685 "unexpected token in '.endif' directive"))
4686 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004687
Jim Grosbach4b905842013-09-20 23:08:21 +00004688 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004689 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4690 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004691 if (!TheCondStack.empty()) {
4692 TheCondState = TheCondStack.back();
4693 TheCondStack.pop_back();
4694 }
4695
4696 return false;
4697}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004698
Eli Bendersky17233942013-01-15 22:59:42 +00004699void AsmParser::initializeDirectiveKindMap() {
4700 DirectiveKindMap[".set"] = DK_SET;
4701 DirectiveKindMap[".equ"] = DK_EQU;
4702 DirectiveKindMap[".equiv"] = DK_EQUIV;
4703 DirectiveKindMap[".ascii"] = DK_ASCII;
4704 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4705 DirectiveKindMap[".string"] = DK_STRING;
4706 DirectiveKindMap[".byte"] = DK_BYTE;
4707 DirectiveKindMap[".short"] = DK_SHORT;
4708 DirectiveKindMap[".value"] = DK_VALUE;
4709 DirectiveKindMap[".2byte"] = DK_2BYTE;
4710 DirectiveKindMap[".long"] = DK_LONG;
4711 DirectiveKindMap[".int"] = DK_INT;
4712 DirectiveKindMap[".4byte"] = DK_4BYTE;
4713 DirectiveKindMap[".quad"] = DK_QUAD;
4714 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004715 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004716 DirectiveKindMap[".single"] = DK_SINGLE;
4717 DirectiveKindMap[".float"] = DK_FLOAT;
4718 DirectiveKindMap[".double"] = DK_DOUBLE;
4719 DirectiveKindMap[".align"] = DK_ALIGN;
4720 DirectiveKindMap[".align32"] = DK_ALIGN32;
4721 DirectiveKindMap[".balign"] = DK_BALIGN;
4722 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4723 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4724 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4725 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4726 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4727 DirectiveKindMap[".org"] = DK_ORG;
4728 DirectiveKindMap[".fill"] = DK_FILL;
4729 DirectiveKindMap[".zero"] = DK_ZERO;
4730 DirectiveKindMap[".extern"] = DK_EXTERN;
4731 DirectiveKindMap[".globl"] = DK_GLOBL;
4732 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004733 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4734 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4735 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4736 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4737 DirectiveKindMap[".reference"] = DK_REFERENCE;
4738 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4739 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4740 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4741 DirectiveKindMap[".comm"] = DK_COMM;
4742 DirectiveKindMap[".common"] = DK_COMMON;
4743 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4744 DirectiveKindMap[".abort"] = DK_ABORT;
4745 DirectiveKindMap[".include"] = DK_INCLUDE;
4746 DirectiveKindMap[".incbin"] = DK_INCBIN;
4747 DirectiveKindMap[".code16"] = DK_CODE16;
4748 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4749 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004750 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004751 DirectiveKindMap[".irp"] = DK_IRP;
4752 DirectiveKindMap[".irpc"] = DK_IRPC;
4753 DirectiveKindMap[".endr"] = DK_ENDR;
4754 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4755 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4756 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4757 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004758 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4759 DirectiveKindMap[".ifge"] = DK_IFGE;
4760 DirectiveKindMap[".ifgt"] = DK_IFGT;
4761 DirectiveKindMap[".ifle"] = DK_IFLE;
4762 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004763 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004764 DirectiveKindMap[".ifb"] = DK_IFB;
4765 DirectiveKindMap[".ifnb"] = DK_IFNB;
4766 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004767 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004768 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004769 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004770 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4771 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4772 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4773 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4774 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004775 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004776 DirectiveKindMap[".endif"] = DK_ENDIF;
4777 DirectiveKindMap[".skip"] = DK_SKIP;
4778 DirectiveKindMap[".space"] = DK_SPACE;
4779 DirectiveKindMap[".file"] = DK_FILE;
4780 DirectiveKindMap[".line"] = DK_LINE;
4781 DirectiveKindMap[".loc"] = DK_LOC;
4782 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004783 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004784 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004785 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4786 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004787 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004788 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00004789 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004790 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4791 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004792 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4793 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4794 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4795 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4796 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4797 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4798 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4799 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4800 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4801 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4802 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4803 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4804 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4805 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4806 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4807 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4808 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4809 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4810 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4811 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4812 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004813 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004814 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4815 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4816 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004817 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004818 DirectiveKindMap[".endm"] = DK_ENDM;
4819 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4820 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004821 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004822 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004823 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004824 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00004825 DirectiveKindMap[".dc"] = DK_DC;
4826 DirectiveKindMap[".dc.a"] = DK_DC_A;
4827 DirectiveKindMap[".dc.b"] = DK_DC_B;
4828 DirectiveKindMap[".dc.d"] = DK_DC_D;
4829 DirectiveKindMap[".dc.l"] = DK_DC_L;
4830 DirectiveKindMap[".dc.s"] = DK_DC_S;
4831 DirectiveKindMap[".dc.w"] = DK_DC_W;
4832 DirectiveKindMap[".dc.x"] = DK_DC_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004833}
4834
Jim Grosbach4b905842013-09-20 23:08:21 +00004835MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004836 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004837
Rafael Espindola34b9c512012-06-03 23:57:14 +00004838 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004839 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004840 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004841 if (getLexer().is(AsmToken::Eof)) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004842 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004843 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004844 }
4845
Rafael Espindola34b9c512012-06-03 23:57:14 +00004846 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004847 (getTok().getIdentifier() == ".rept" ||
4848 getTok().getIdentifier() == ".irp" ||
4849 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004850 ++NestLevel;
4851 }
4852
4853 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004854 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004855 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004856 EndToken = getTok();
4857 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004858 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Davec0c0f7a12016-09-12 20:03:02 +00004859 printError(getTok().getLoc(),
4860 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004861 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004862 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004863 break;
4864 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004865 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004866 }
4867
Rafael Espindola34b9c512012-06-03 23:57:14 +00004868 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004869 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004870 }
4871
4872 const char *BodyStart = StartToken.getLoc().getPointer();
4873 const char *BodyEnd = EndToken.getLoc().getPointer();
4874 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4875
Rafael Espindola34b9c512012-06-03 23:57:14 +00004876 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004877 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004878 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004879}
4880
Jim Grosbach4b905842013-09-20 23:08:21 +00004881void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004882 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004883 OS << ".endr\n";
4884
Rafael Espindola3560ff22014-08-27 20:03:13 +00004885 std::unique_ptr<MemoryBuffer> Instantiation =
4886 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004887
Rafael Espindola34b9c512012-06-03 23:57:14 +00004888 // Create the macro instantiation object and add to the current macro
4889 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004890 MacroInstantiation *MI = new MacroInstantiation(
4891 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004892 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004893
Rafael Espindola34b9c512012-06-03 23:57:14 +00004894 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004895 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004896 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004897 Lex();
4898}
4899
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004900/// parseDirectiveRept
4901/// ::= .rep | .rept count
4902bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004903 const MCExpr *CountExpr;
4904 SMLoc CountLoc = getTok().getLoc();
4905 if (parseExpression(CountExpr))
4906 return true;
4907
Rafael Espindola34b9c512012-06-03 23:57:14 +00004908 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004909 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004910 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4911 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004912
Nirav Davea645433c2016-07-18 15:24:03 +00004913 if (check(Count < 0, CountLoc, "Count is negative") ||
4914 parseToken(AsmToken::EndOfStatement,
4915 "unexpected token in '" + Dir + "' directive"))
4916 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004917
4918 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004919 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00004920 if (!M)
4921 return true;
4922
4923 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4924 // to hold the macro body with substitutions.
4925 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004926 raw_svector_ostream OS(Buf);
4927 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004928 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4929 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004930 return true;
4931 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004932 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004933
4934 return false;
4935}
4936
Jim Grosbach4b905842013-09-20 23:08:21 +00004937/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004938/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004939bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004940 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00004941 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00004942 if (check(parseIdentifier(Parameter.Name),
4943 "expected identifier in '.irp' directive") ||
4944 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
4945 parseMacroArguments(nullptr, A) ||
4946 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004947 return true;
4948
Rafael Espindola768b41c2012-06-15 14:02:34 +00004949 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004950 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004951 if (!M)
4952 return true;
4953
4954 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4955 // to hold the macro body with substitutions.
4956 SmallString<256> Buf;
4957 raw_svector_ostream OS(Buf);
4958
Craig Topper84008482015-10-10 05:38:14 +00004959 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004960 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4961 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00004962 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004963 return true;
4964 }
4965
Jim Grosbach4b905842013-09-20 23:08:21 +00004966 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004967
4968 return false;
4969}
4970
Jim Grosbach4b905842013-09-20 23:08:21 +00004971/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004972/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004973bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004974 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00004975 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00004976
4977 if (check(parseIdentifier(Parameter.Name),
4978 "expected identifier in '.irpc' directive") ||
4979 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
4980 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004981 return true;
4982
4983 if (A.size() != 1 || A.front().size() != 1)
4984 return TokError("unexpected token in '.irpc' directive");
4985
4986 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00004987 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
4988 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004989
4990 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004991 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004992 if (!M)
4993 return true;
4994
4995 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4996 // to hold the macro body with substitutions.
4997 SmallString<256> Buf;
4998 raw_svector_ostream OS(Buf);
4999
5000 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005001 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005002 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005003 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005004
Toma Tabacu217116e2015-04-27 10:50:29 +00005005 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5006 // This is undocumented, but GAS seems to support it.
5007 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005008 return true;
5009 }
5010
Jim Grosbach4b905842013-09-20 23:08:21 +00005011 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005012
5013 return false;
5014}
5015
Jim Grosbach4b905842013-09-20 23:08:21 +00005016bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005017 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005018 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005019
5020 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005021 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005022 assert(getLexer().is(AsmToken::EndOfStatement));
5023
Jim Grosbach4b905842013-09-20 23:08:21 +00005024 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005025 return false;
5026}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005027
Jim Grosbach4b905842013-09-20 23:08:21 +00005028bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005029 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005030 const MCExpr *Value;
5031 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005032 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005033 return true;
5034 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5035 if (!MCE)
5036 return Error(ExprLoc, "unexpected expression in _emit");
5037 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005038 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005039 return Error(ExprLoc, "literal value out of range for directive");
5040
Craig Topper7d5b2312015-10-10 05:25:02 +00005041 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005042 return false;
5043}
5044
Jim Grosbach4b905842013-09-20 23:08:21 +00005045bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005046 const MCExpr *Value;
5047 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005048 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005049 return true;
5050 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5051 if (!MCE)
5052 return Error(ExprLoc, "unexpected expression in align");
5053 uint64_t IntValue = MCE->getValue();
5054 if (!isPowerOf2_64(IntValue))
5055 return Error(ExprLoc, "literal value not a power of two greater then zero");
5056
Craig Topper7d5b2312015-10-10 05:25:02 +00005057 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005058 return false;
5059}
5060
Chad Rosierf43fcf52013-02-13 21:27:17 +00005061// We are comparing pointers, but the pointers are relative to a single string.
5062// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005063static int rewritesSort(const AsmRewrite *AsmRewriteA,
5064 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005065 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5066 return -1;
5067 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5068 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005069
Chad Rosierfce4fab2013-04-08 17:43:47 +00005070 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5071 // rewrite to the same location. Make sure the SizeDirective rewrite is
5072 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5073 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005074 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5075 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005076 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005077
Jim Grosbach4b905842013-09-20 23:08:21 +00005078 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5079 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005080 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005081 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005082}
5083
Jim Grosbach4b905842013-09-20 23:08:21 +00005084bool AsmParser::parseMSInlineAsm(
5085 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5086 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
5087 SmallVectorImpl<std::string> &Constraints,
5088 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5089 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005090 SmallVector<void *, 4> InputDecls;
5091 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005092 SmallVector<bool, 4> InputDeclsAddressOf;
5093 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005094 SmallVector<std::string, 4> InputConstraints;
5095 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005096 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005097
Benjamin Kramer1a136112013-02-15 20:37:21 +00005098 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005099
5100 // Prime the lexer.
5101 Lex();
5102
5103 // While we have input, parse each statement.
5104 unsigned InputIdx = 0;
5105 unsigned OutputIdx = 0;
5106 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005107 // Parse curly braces marking block start/end
5108 if (parseCurlyBlockScope(AsmStrRewrites))
5109 continue;
5110
Eli Friedman0f4871d2012-10-22 23:58:19 +00005111 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Davec0c0f7a12016-09-12 20:03:02 +00005112 bool StatementErr = parseStatement(Info, &SI);
Chad Rosier8bce6642012-10-18 15:49:34 +00005113
Nirav Davec0c0f7a12016-09-12 20:03:02 +00005114 if (StatementErr || Info.ParseError) {
5115 // Emit pending errors if any exist.
5116 printPendingErrors();
Chad Rosier149e8e02012-12-12 22:45:52 +00005117 return true;
Nirav Davec0c0f7a12016-09-12 20:03:02 +00005118 }
5119
5120 // No pending error should exist here.
5121 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005122
Benjamin Kramer1a136112013-02-15 20:37:21 +00005123 if (Info.Opcode == ~0U)
5124 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005125
Benjamin Kramer1a136112013-02-15 20:37:21 +00005126 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005127
Benjamin Kramer1a136112013-02-15 20:37:21 +00005128 // Build the list of clobbers, outputs and inputs.
5129 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005130 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005131
Benjamin Kramer1a136112013-02-15 20:37:21 +00005132 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005133 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005134 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005135
Benjamin Kramer1a136112013-02-15 20:37:21 +00005136 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005137 if (Operand.isReg() && !Operand.needAddressOf() &&
5138 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005139 unsigned NumDefs = Desc.getNumDefs();
5140 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005141 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5142 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005143 continue;
5144 }
5145
5146 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005147 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005148 if (SymName.empty())
5149 continue;
5150
David Blaikie960ea3f2014-06-08 16:18:35 +00005151 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005152 if (!OpDecl)
5153 continue;
5154
5155 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005156 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005157 if (isOutput) {
5158 ++InputIdx;
5159 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005160 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005161 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005162 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005163 } else {
5164 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005165 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5166 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005167 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005168 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005169 }
Reid Kleckneree088972013-12-10 18:27:32 +00005170
5171 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005172 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5173 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005174 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005175 }
5176
5177 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005178 NumOutputs = OutputDecls.size();
5179 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005180
5181 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005182 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5183 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5184 ClobberRegs.end());
5185 Clobbers.assign(ClobberRegs.size(), std::string());
5186 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5187 raw_string_ostream OS(Clobbers[I]);
5188 IP->printRegName(OS, ClobberRegs[I]);
5189 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005190
5191 // Merge the various outputs and inputs. Output are expected first.
5192 if (NumOutputs || NumInputs) {
5193 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005194 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005195 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005196 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005197 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005198 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005199 }
5200 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005201 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005202 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005203 }
5204 }
5205
5206 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005207 std::string AsmStringIR;
5208 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005209 StringRef ASMString =
5210 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5211 const char *AsmStart = ASMString.begin();
5212 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005213 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005214 for (const AsmRewrite &AR : AsmStrRewrites) {
5215 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005216 if (Kind == AOK_Delete)
5217 continue;
5218
David Majnemer8114c1a2014-06-23 02:17:16 +00005219 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005220 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005221
Chad Rosier120eefd2013-03-19 17:32:17 +00005222 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005223 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005224 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005225
Chad Rosier37e755c2012-10-23 17:43:43 +00005226 // Skip the original expression.
5227 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005228 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005229 continue;
5230 }
5231
Chad Rosierff10ed12013-04-12 16:26:42 +00005232 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005233 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005234 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005235 default:
5236 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005237 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005238 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005239 break;
5240 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005241 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005242 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005243 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005244 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005245 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005246 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005247 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005248 break;
5249 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005250 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005251 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005252 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005253 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005254 default: break;
5255 case 8: OS << "byte ptr "; break;
5256 case 16: OS << "word ptr "; break;
5257 case 32: OS << "dword ptr "; break;
5258 case 64: OS << "qword ptr "; break;
5259 case 80: OS << "xword ptr "; break;
5260 case 128: OS << "xmmword ptr "; break;
5261 case 256: OS << "ymmword ptr "; break;
5262 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005263 break;
5264 case AOK_Emit:
5265 OS << ".byte";
5266 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005267 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005268 // MS alignment directives are measured in bytes. If the native assembler
5269 // measures alignment in bytes, we can pass it straight through.
5270 OS << ".align";
5271 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5272 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005273
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005274 // Alignment is in log2 form, so print that instead and skip the original
5275 // immediate.
5276 unsigned Val = AR.Val;
5277 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005278 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005279 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5280 break;
5281 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005282 case AOK_EVEN:
5283 OS << ".even";
5284 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005285 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005286 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005287 OS.flush();
5288 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005289 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005290 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005291 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005292 case AOK_EndOfStatement:
5293 OS << "\n\t";
5294 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005295 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005296
Chad Rosier8bce6642012-10-18 15:49:34 +00005297 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005298 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005299 }
5300
5301 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005302 if (AsmStart != AsmEnd)
5303 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005304
5305 AsmString = OS.str();
5306 return false;
5307}
5308
Pete Cooper80d21cb2015-06-22 19:35:57 +00005309namespace llvm {
5310namespace MCParserUtils {
5311
5312/// Returns whether the given symbol is used anywhere in the given expression,
5313/// or subexpressions.
5314static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5315 switch (Value->getKind()) {
5316 case MCExpr::Binary: {
5317 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5318 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5319 isSymbolUsedInExpression(Sym, BE->getRHS());
5320 }
5321 case MCExpr::Target:
5322 case MCExpr::Constant:
5323 return false;
5324 case MCExpr::SymbolRef: {
5325 const MCSymbol &S =
5326 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5327 if (S.isVariable())
5328 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5329 return &S == Sym;
5330 }
5331 case MCExpr::Unary:
5332 return isSymbolUsedInExpression(
5333 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5334 }
5335
5336 llvm_unreachable("Unknown expr kind!");
5337}
5338
5339bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5340 MCAsmParser &Parser, MCSymbol *&Sym,
5341 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005342
5343 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005344 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005345
5346 if (Parser.parseExpression(Value)) {
5347 Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005348 return true;
5349 }
5350
5351 // Note: we don't count b as used in "a = b". This is to allow
5352 // a = b
5353 // b = c
5354
Nirav Davefd910412016-06-17 16:06:17 +00005355 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
Pete Cooper80d21cb2015-06-22 19:35:57 +00005356 return Parser.TokError("unexpected token in assignment");
5357
5358 // Eat the end of statement marker.
5359 Parser.Lex();
5360
5361 // Validate that the LHS is allowed to be a variable (either it has not been
5362 // used as a symbol, or it is an absolute symbol).
5363 Sym = Parser.getContext().lookupSymbol(Name);
5364 if (Sym) {
5365 // Diagnose assignment to a label.
5366 //
5367 // FIXME: Diagnostics. Note the location of the definition as a label.
5368 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5369 if (isSymbolUsedInExpression(Sym, Value))
5370 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005371 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5372 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005373 ; // Allow redefinitions of undefined symbols only used in directives.
5374 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5375 ; // Allow redefinitions of variables that haven't yet been used.
5376 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5377 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5378 else if (!Sym->isVariable())
5379 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5380 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5381 return Parser.Error(EqualLoc,
5382 "invalid reassignment of non-absolute variable '" +
5383 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005384 } else if (Name == ".") {
Rafael Espindola7ae65d82015-11-04 23:59:18 +00005385 Parser.getStreamer().emitValueToOffset(Value, 0);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005386 return false;
5387 } else
5388 Sym = Parser.getContext().getOrCreateSymbol(Name);
5389
5390 Sym->setRedefinable(allow_redef);
5391
5392 return false;
5393}
5394
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005395} // end namespace MCParserUtils
5396} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005397
Daniel Dunbar01e36072010-07-17 02:26:10 +00005398/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005399MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5400 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005401 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005402}