blob: 9d5eaf3140849f1cd37678ae7491144baca769b3 [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"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000038#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000039#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000040#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000041#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000042#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000043#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000044#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000045#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000046#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000047#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000048#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000049#include "llvm/Support/CommandLine.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000050#include "llvm/Support/Dwarf.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000051#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000052#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000053#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000054#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000055#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000056#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000057#include <algorithm>
58#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000059#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000060#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000061#include <cstddef>
62#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000063#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000064#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000065#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000066#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000067#include <tuple>
68#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000069#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000070
Chris Lattnerb0133452009-06-21 20:16:42 +000071using namespace llvm;
72
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000073MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000074
Davide Italiano7c9fc732016-07-27 05:51:56 +000075static cl::opt<unsigned> AsmMacroMaxNestingDepth(
76 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
77 cl::desc("The maximum nesting depth allowed for assembly macros."));
78
Daniel Dunbar86033402010-07-12 17:54:38 +000079namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000080
Eli Benderskya313ae62013-01-16 18:56:50 +000081/// \brief Helper types for tracking macro definitions.
82typedef std::vector<AsmToken> MCAsmMacroArgument;
83typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000084
85struct MCAsmMacroParameter {
86 StringRef Name;
87 MCAsmMacroArgument Value;
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000088 bool Required = false;
89 bool Vararg = false;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000090
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000091 MCAsmMacroParameter() = default;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000092};
93
Eli Benderskya313ae62013-01-16 18:56:50 +000094typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
95
96struct MCAsmMacro {
97 StringRef Name;
98 StringRef Body;
99 MCAsmMacroParameters Parameters;
100
101public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000102 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
103 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +0000104};
105
Daniel Dunbar43235712010-07-18 18:54:11 +0000106/// \brief Helper class for storing information about an active macro
107/// instantiation.
108struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +0000109 /// The location of the instantiation.
110 SMLoc InstantiationLoc;
111
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000112 /// The buffer where parsing should resume upon instantiation completion.
113 int ExitBuffer;
114
Daniel Dunbar43235712010-07-18 18:54:11 +0000115 /// The location where parsing should resume upon instantiation completion.
116 SMLoc ExitLoc;
117
Nico Weber155dccd12014-07-24 17:08:39 +0000118 /// The depth of TheCondStack at the start of the instantiation.
119 size_t CondStackDepth;
120
Daniel Dunbar43235712010-07-18 18:54:11 +0000121public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000122 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000123};
124
Eli Friedman0f4871d2012-10-22 23:58:19 +0000125struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000126 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000127 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000128
Jim Grosbach4b905842013-09-20 23:08:21 +0000129 /// \brief The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000130 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000131
Jim Grosbach4b905842013-09-20 23:08:21 +0000132 /// \brief Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000133 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000134
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000135 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000136
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000137 ParseStatementInfo() = default;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000138 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000139 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000140};
141
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000142/// \brief The concrete assembly parser instance.
143class AsmParser : public MCAsmParser {
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.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000202 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000203
Jim Grosbach4b905842013-09-20 23:08:21 +0000204 /// \brief is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000205 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000206
Jim Grosbach4b905842013-09-20 23:08:21 +0000207 /// \brief Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000208 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000209
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000210public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000211 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000212 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000213 AsmParser(const AsmParser &) = delete;
214 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000215 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000216
Craig Topper59be68f2014-03-08 07:14:16 +0000217 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000218
Craig Topper59be68f2014-03-08 07:14:16 +0000219 void addDirectiveHandler(StringRef Directive,
220 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000221 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000222 }
223
Toma Tabacu11e14a92015-04-21 11:50:52 +0000224 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
225 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
226 }
227
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000228 /// @name MCAsmParser Interface
229 /// {
230
Craig Topper59be68f2014-03-08 07:14:16 +0000231 SourceMgr &getSourceManager() override { return SrcMgr; }
232 MCAsmLexer &getLexer() override { return Lexer; }
233 MCContext &getContext() override { return Ctx; }
234 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000235
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000236 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
237
Craig Topper59be68f2014-03-08 07:14:16 +0000238 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000239 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000240 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000241 else
242 return AssemblerDialect;
243 }
Craig Topper59be68f2014-03-08 07:14:16 +0000244 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000245 AssemblerDialect = i;
246 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000247
Nirav Dave2364748a2016-09-16 18:30:20 +0000248 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
249 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
250 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000251
Craig Topper59be68f2014-03-08 07:14:16 +0000252 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000254 void setParsingInlineAsm(bool V) override {
255 ParsingInlineAsm = V;
256 Lexer.setParsingMSInlineAsm(V);
257 }
Craig Topper59be68f2014-03-08 07:14:16 +0000258 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000259
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000260 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000261 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000262 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000263 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000264 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000265 const MCInstrInfo *MII, const MCInstPrinter *IP,
266 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000267
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000268 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000269 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
270 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
271 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000272 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
273 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000274 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000275
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000276 /// \brief Parse a floating point expression using the float \p Semantics
277 /// and set \p Res to the value.
278 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
279
Jim Grosbach4b905842013-09-20 23:08:21 +0000280 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000281 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000282 bool parseIdentifier(StringRef &Res) override;
283 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000284
Nirav Davef43cc9f2016-10-10 15:24:54 +0000285 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000286
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000287 /// }
288
289private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000290 bool parseStatement(ParseStatementInfo &Info,
291 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000292 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000293 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000294
Jim Grosbach4b905842013-09-20 23:08:21 +0000295 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000296 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000297 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000298 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000299 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000300 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000301
Eli Benderskya313ae62013-01-16 18:56:50 +0000302 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000303 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000304
305 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000306 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000307
308 /// \brief Lookup a previously defined macro.
309 /// \param Name Macro name.
310 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000311 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000312
313 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000314 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000315
316 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000317 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000318
319 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000320 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000321
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000322 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000323 ///
324 /// \param M The macro.
325 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000326 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000327
328 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000329 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000330
David Majnemer91fc4c22014-01-29 18:57:46 +0000331 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000332 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000333
334 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000335 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000336
Jim Grosbach4b905842013-09-20 23:08:21 +0000337 void printMacroInstantiations();
338 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000339 SMRange Range = None) const {
340 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000341 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000342 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000343 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000344
Jim Grosbach4b905842013-09-20 23:08:21 +0000345 /// \brief Enter the specified file. This returns true on failure.
346 bool enterIncludeFile(const std::string &Filename);
347
348 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000349 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000350 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
351 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000352
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000353 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000354 /// current token is not set; clients should ensure Lex() is called
355 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000356 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000357 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000358 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000359 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000360
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000361 /// \brief Parse up to the end of statement and a return the contents from the
362 /// current token until the end of the statement; the current token on exit
363 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000364 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000365
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000366 /// \brief Parse until the end of a statement or a comma is encountered,
367 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000368 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000369
Jim Grosbach4b905842013-09-20 23:08:21 +0000370 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000371 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000372
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000373 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
374 MCBinaryExpr::Opcode &Kind);
375
Jim Grosbach4b905842013-09-20 23:08:21 +0000376 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
377 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
378 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000379
Jim Grosbach4b905842013-09-20 23:08:21 +0000380 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000381
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000382 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
383 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
384
Eli Bendersky17233942013-01-15 22:59:42 +0000385 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000386 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000387 DK_NO_DIRECTIVE, // Placeholder
388 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000389 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000390 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
Petr Hosek731bb9c2016-08-23 21:34:53 +0000391 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000392 DK_DCB, DK_DCB_B, DK_DCB_D, DK_DCB_L, DK_DCB_S, DK_DCB_W, DK_DCB_X,
Petr Hosek85b2f672016-09-23 21:53:36 +0000393 DK_DS, DK_DS_B, DK_DS_D, DK_DS_L, DK_DS_P, DK_DS_S, DK_DS_W, DK_DS_X,
David Woodhoused6de0d92014-02-01 16:20:59 +0000394 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000395 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000396 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000397 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000398 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000399 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000400 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
401 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000402 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000403 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
404 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000405 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000406 DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE,
407 DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE,
408 DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000409 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
410 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
411 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
412 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
413 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000414 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000415 DK_MACROS_ON, DK_MACROS_OFF,
416 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000417 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000418 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000419 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000420 };
421
Jim Grosbach4b905842013-09-20 23:08:21 +0000422 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000423 /// directives parsed by this class.
424 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000425
426 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000427 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000428 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000429 bool parseDirectiveValue(StringRef IDVal,
430 unsigned Size); // ".byte", ".long", ...
431 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
432 bool parseDirectiveRealValue(StringRef IDVal,
433 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000434 bool parseDirectiveFill(); // ".fill"
435 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000436 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000437 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
438 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000439 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000440 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000441
Eli Bendersky17233942013-01-15 22:59:42 +0000442 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000443 bool parseDirectiveFile(SMLoc DirectiveLoc);
444 bool parseDirectiveLine();
445 bool parseDirectiveLoc();
446 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000447
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000448 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
449 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000450 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000451 bool parseDirectiveCVFuncId();
452 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000453 bool parseDirectiveCVLoc();
454 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000455 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000456 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000457 bool parseDirectiveCVStringTable();
458 bool parseDirectiveCVFileChecksums();
459
Eli Bendersky17233942013-01-15 22:59:42 +0000460 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000461 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000462 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000463 bool parseDirectiveCFISections();
464 bool parseDirectiveCFIStartProc();
465 bool parseDirectiveCFIEndProc();
466 bool parseDirectiveCFIDefCfaOffset();
467 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
468 bool parseDirectiveCFIAdjustCfaOffset();
469 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
470 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
471 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
472 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
473 bool parseDirectiveCFIRememberState();
474 bool parseDirectiveCFIRestoreState();
475 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
476 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
477 bool parseDirectiveCFIEscape();
478 bool parseDirectiveCFISignalFrame();
479 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000480
481 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000482 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000483 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000484 bool parseDirectiveEndMacro(StringRef Directive);
485 bool parseDirectiveMacro(SMLoc DirectiveLoc);
486 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000487
Eli Benderskyf483ff92012-12-20 19:05:53 +0000488 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000489 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000490 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000491 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000492 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000493 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000494
Eli Bendersky17233942013-01-15 22:59:42 +0000495 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000496 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000497
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000498 // ".dcb"
499 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
500 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000501 // ".ds"
502 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000503
Eli Bendersky17233942013-01-15 22:59:42 +0000504 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000505 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000506
Jim Grosbach4b905842013-09-20 23:08:21 +0000507 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000508 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000509 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000510
Jim Grosbach4b905842013-09-20 23:08:21 +0000511 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000512
Jim Grosbach4b905842013-09-20 23:08:21 +0000513 bool parseDirectiveAbort(); // ".abort"
514 bool parseDirectiveInclude(); // ".include"
515 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000516
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000517 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
518 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000519 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000520 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000521 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000522 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000523 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
524 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000525 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000526 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
527 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
528 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
529 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000530 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000531
Jim Grosbach4b905842013-09-20 23:08:21 +0000532 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000533 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000534
Rafael Espindola34b9c512012-06-03 23:57:14 +0000535 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000536 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
537 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000538 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000539 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000540 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
541 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
542 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000543
Chad Rosierc7f552c2013-02-12 21:33:51 +0000544 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000545 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000546 size_t Len);
547
548 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000549 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000550
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000551 // "end"
552 bool parseDirectiveEnd(SMLoc DirectiveLoc);
553
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000554 // ".err" or ".error"
555 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000556
Nico Weber404012b2014-07-24 16:26:06 +0000557 // ".warning"
558 bool parseDirectiveWarning(SMLoc DirectiveLoc);
559
Eli Bendersky17233942013-01-15 22:59:42 +0000560 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000561};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000562
563} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000564
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000565namespace llvm {
566
567extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000568extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000569extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000570
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000571} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000572
Chris Lattnerc35681b2010-01-19 19:46:13 +0000573enum { DEFAULT_ADDRSPACE = 0 };
574
David Blaikie9f380a32015-03-16 18:06:57 +0000575AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000576 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000577 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000578 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000579 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000580 // Save the old handler.
581 SavedDiagHandler = SrcMgr.getDiagHandler();
582 SavedDiagContext = SrcMgr.getDiagContext();
583 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000584 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000585 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000586
Daniel Dunbarc5011082010-07-12 18:12:02 +0000587 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000588 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
589 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000590 PlatformParser.reset(createCOFFAsmParser());
591 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000592 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000593 PlatformParser.reset(createDarwinAsmParser());
594 IsDarwin = true;
595 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000596 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000597 PlatformParser.reset(createELFAsmParser());
598 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000599 case MCObjectFileInfo::IsWasm:
600 llvm_unreachable("Wasm parsing not supported yet");
601 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000602 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000603
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000604 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000605 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000606
607 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000608}
609
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000610AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000611 assert((HadError || ActiveMacros.empty()) &&
612 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000613
614 // Restore the saved diagnostics handler and context for use during
615 // finalization.
616 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000617}
618
Jim Grosbach4b905842013-09-20 23:08:21 +0000619void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000620 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000621 for (std::vector<MacroInstantiation *>::const_reverse_iterator
622 it = ActiveMacros.rbegin(),
623 ie = ActiveMacros.rend();
624 it != ie; ++it)
625 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000626 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000627}
628
Nirav Dave2364748a2016-09-16 18:30:20 +0000629void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
630 printPendingErrors();
631 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000632 printMacroInstantiations();
633}
634
Nirav Dave2364748a2016-09-16 18:30:20 +0000635bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000636 if(getTargetParser().getTargetOptions().MCNoWarn)
637 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000638 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000639 return Error(L, Msg, Range);
640 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000641 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000642 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000643}
644
Nirav Dave2364748a2016-09-16 18:30:20 +0000645bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000646 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000647 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000648 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000649 return true;
650}
651
Jim Grosbach4b905842013-09-20 23:08:21 +0000652bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000653 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000654 unsigned NewBuf =
655 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
656 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000657 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000658
Sean Callanan7a77eae2010-01-21 00:19:58 +0000659 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000660 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000661 return false;
662}
Daniel Dunbar43235712010-07-18 18:54:11 +0000663
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000664/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000665/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000666/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000667bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
668 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000669 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000670 unsigned NewBuf =
671 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
672 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000673 return true;
674
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000675 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000676 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
677 Bytes = Bytes.drop_front(Skip);
678 if (Count) {
679 int64_t Res;
680 if (!Count->evaluateAsAbsolute(Res))
681 return Error(Loc, "expected absolute expression");
682 if (Res < 0)
683 return Warning(Loc, "negative count has no effect");
684 Bytes = Bytes.take_front(Res);
685 }
686 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000687 return false;
688}
689
Alp Tokera55b95b2014-07-06 10:33:31 +0000690void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
691 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000692 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
693 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000694}
695
Sean Callanan7a77eae2010-01-21 00:19:58 +0000696const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000697 if (Lexer.getTok().is(AsmToken::Error))
698 Error(Lexer.getErrLoc(), Lexer.getErr());
699
Nirav Dave53a72f42016-07-11 12:42:14 +0000700 // if it's a end of statement with a comment in it
701 if (getTok().is(AsmToken::EndOfStatement)) {
702 // if this is a line comment output it.
703 if (getTok().getString().front() != '\n' &&
704 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
705 Out.addExplicitComment(Twine(getTok().getString()));
706 }
707
Sean Callanan7a77eae2010-01-21 00:19:58 +0000708 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000709
710 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000711 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000712 if (MAI.preserveAsmComments())
713 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000714 tok = &Lexer.Lex();
715 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000716
Sean Callanan7a77eae2010-01-21 00:19:58 +0000717 if (tok->is(AsmToken::Eof)) {
718 // If this is the end of an included file, pop the parent file off the
719 // include stack.
720 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
721 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000722 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000723 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000724 }
725 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000726
Sean Callanan7a77eae2010-01-21 00:19:58 +0000727 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000728}
729
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000730bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000731 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000732 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000733 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000734
Chris Lattner36e02122009-06-21 20:54:55 +0000735 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000736 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000737
738 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000739 AsmCond StartingCondState = TheCondState;
740
Kevin Enderby6469fc22011-11-01 22:27:22 +0000741 // If we are generating dwarf for assembly source files save the initial text
742 // section and generate a .file directive.
743 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000744 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000745 if (!Sec->getBeginSymbol()) {
746 MCSymbol *SectionStartSym = getContext().createTempSymbol();
747 getStreamer().EmitLabel(SectionStartSym);
748 Sec->setBeginSymbol(SectionStartSym);
749 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000750 bool InsertResult = getContext().addGenDwarfSection(Sec);
751 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000752 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000753 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
754 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000755 }
756
Chris Lattner73f36112009-07-02 21:53:43 +0000757 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000758 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000759 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000760 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000761 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000762
Nirav Dave2364748a2016-09-16 18:30:20 +0000763 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
764 // for printing ErrMsg via Lex() only if no (presumably better) parser error
765 // exists.
766 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000767 Lex();
768 }
769
Nirav Dave2364748a2016-09-16 18:30:20 +0000770 // parseStatement returned true so may need to emit an error.
771 printPendingErrors();
772
773 // Skipping to the next line if needed.
774 if (!getLexer().isAtStartOfStatement())
775 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000776 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000777
Nirav Dave2364748a2016-09-16 18:30:20 +0000778 // All errors should have been emitted.
779 assert(!hasPendingError() && "unexpected error from parseStatement");
780
Oliver Stannard21718282016-07-26 14:19:47 +0000781 getTargetParser().flushPendingInstructions(getStreamer());
782
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000783 if (TheCondState.TheCond != StartingCondState.TheCond ||
784 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000785 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000786 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000787 const auto &LineTables = getContext().getMCDwarfLineTables();
788 if (!LineTables.empty()) {
789 unsigned Index = 0;
790 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
791 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000792 printError(getTok().getLoc(), "unassigned file number: " +
793 Twine(Index) +
794 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000795 ++Index;
796 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000797 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000798
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000799 // Check to see that all assembler local symbols were actually defined.
800 // Targets that don't do subsections via symbols may not want this, though,
801 // so conservatively exclude them. Only do this if we're finalizing, though,
802 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000803 if (!NoFinalize) {
804 if (MAI.hasSubsectionsViaSymbols()) {
805 for (const auto &TableEntry : getContext().getSymbols()) {
806 MCSymbol *Sym = TableEntry.getValue();
807 // Variable symbols may not be marked as defined, so check those
808 // explicitly. If we know it's a variable, we have a definition for
809 // the purposes of this check.
810 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
811 // FIXME: We would really like to refer back to where the symbol was
812 // first referenced for a source location. We need to add something
813 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000814 printError(getTok().getLoc(), "assembler local symbol '" +
815 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000816 }
817 }
818
819 // Temporary symbols like the ones for directional jumps don't go in the
820 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000821 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
822 if (std::get<2>(LocSym)->isUndefined()) {
823 // Reset the state of any "# line file" directives we've seen to the
824 // context as it was at the diagnostic site.
825 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000826 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000827 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000828 }
829 }
830
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000831 // Finalize the output stream if there are no errors and if the client wants
832 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000833 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000834 Out.Finish();
835
Oliver Stannard07b43d32015-11-17 09:58:07 +0000836 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000837}
838
Nirav Davef43cc9f2016-10-10 15:24:54 +0000839bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000840 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000841 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000842 return Error(getTok().getLoc(),
843 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000844 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000845 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000846}
847
Jim Grosbach4b905842013-09-20 23:08:21 +0000848/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000849void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000850 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000851 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000852
Chris Lattnere5074c42009-06-22 01:29:09 +0000853 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000854 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000855 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000856}
857
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000858StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000859 const char *Start = getTok().getLoc().getPointer();
860
Jim Grosbach4b905842013-09-20 23:08:21 +0000861 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000862 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000863
864 const char *End = getTok().getLoc().getPointer();
865 return StringRef(Start, End - Start);
866}
Chris Lattner78db3622009-06-22 05:51:26 +0000867
Jim Grosbach4b905842013-09-20 23:08:21 +0000868StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000869 const char *Start = getTok().getLoc().getPointer();
870
871 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000872 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000873 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000874
875 const char *End = getTok().getLoc().getPointer();
876 return StringRef(Start, End - Start);
877}
878
Jim Grosbach4b905842013-09-20 23:08:21 +0000879/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000880/// NOTE: This assumes the leading '(' has already been consumed.
881///
882/// parenexpr ::= expr)
883///
Jim Grosbach4b905842013-09-20 23:08:21 +0000884bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
885 if (parseExpression(Res))
886 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000887 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000888 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000889 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000890 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000891 return false;
892}
Chris Lattner78db3622009-06-22 05:51:26 +0000893
Jim Grosbach4b905842013-09-20 23:08:21 +0000894/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000895/// NOTE: This assumes the leading '[' has already been consumed.
896///
897/// bracketexpr ::= expr]
898///
Jim Grosbach4b905842013-09-20 23:08:21 +0000899bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
900 if (parseExpression(Res))
901 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000902 EndLoc = getTok().getEndLoc();
903 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
904 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000905 return false;
906}
907
Jim Grosbach4b905842013-09-20 23:08:21 +0000908/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000909/// primaryexpr ::= (parenexpr
910/// primaryexpr ::= symbol
911/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000912/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000913/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000914bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000915 SMLoc FirstTokenLoc = getLexer().getLoc();
916 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
917 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000918 default:
919 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000920 // If we have an error assume that we've already handled it.
921 case AsmToken::Error:
922 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000923 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000924 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000925 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000926 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +0000927 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000928 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000929 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000930 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000931 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000932 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000933 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000934 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +0000935 // We may have failed but $ may be a valid token.
936 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000937 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +0000938 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +0000939 // This is a '$' reference, which references the current PC. Emit a
940 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000941 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000942 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000943 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000944 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000945 EndLoc = FirstTokenLoc;
946 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000947 }
948 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000949 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000950 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000951 // Parse symbol variant
952 std::pair<StringRef, StringRef> Split;
953 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000954 if (FirstTokenKind == AsmToken::String) {
955 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000956 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000957 SMLoc AtLoc = getLexer().getLoc();
958 StringRef VName;
959 if (parseIdentifier(VName))
960 return Error(AtLoc, "expected symbol variant after '@'");
961
962 Split = std::make_pair(Identifier, VName);
963 }
964 } else {
965 Split = Identifier.split('@');
966 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000967 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000968 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000969 StringRef VName;
970 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000971 // eat ')'.
972 if (parseToken(AsmToken::RParen,
973 "unexpected token in variant, expected ')'"))
974 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000975 Split = std::make_pair(Identifier, VName);
976 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000977
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000978 EndLoc = SMLoc::getFromPointer(Identifier.end());
979
Daniel Dunbard20cda02009-10-16 01:34:54 +0000980 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000981 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +0000982 if (SymbolName.empty())
983 return true;
984
Hans Wennborgce69d772013-10-18 20:46:28 +0000985 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000986
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000987 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000988 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000989 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000990 if (Variant != MCSymbolRefExpr::VK_Invalid) {
991 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000992 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000993 Variant = MCSymbolRefExpr::VK_None;
994 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000995 return Error(SMLoc::getFromPointer(Split.second.begin()),
996 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000997 }
998 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000999
Jim Grosbach6f482002015-05-18 18:43:14 +00001000 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001001
Daniel Dunbard20cda02009-10-16 01:34:54 +00001002 // If this is an absolute variable reference, substitute it now to preserve
1003 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001004 if (Sym->isVariable() &&
1005 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001006 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001007 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001008
Vedant Kumar86dbd922015-08-31 17:44:53 +00001009 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001010 return false;
1011 }
1012
1013 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001014 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001015 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001016 }
David Woodhousef42a6662014-02-01 16:20:54 +00001017 case AsmToken::BigNum:
1018 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001019 case AsmToken::Integer: {
1020 SMLoc Loc = getTok().getLoc();
1021 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001022 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001023 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001024 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001025 // Look for 'b' or 'f' following an Integer as a directional label
1026 if (Lexer.getKind() == AsmToken::Identifier) {
1027 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001028 // Lookup the symbol variant if used.
1029 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1030 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1031 if (Split.first.size() != IDVal.size()) {
1032 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001033 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001034 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001035 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001036 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001037 if (IDVal == "f" || IDVal == "b") {
1038 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001039 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001040 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001041 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001042 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001043 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001044 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001045 Lex(); // Eat identifier.
1046 }
1047 }
Chris Lattner78db3622009-06-22 05:51:26 +00001048 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001049 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001050 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001051 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001052 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001053 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001054 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001055 Lex(); // Eat token.
1056 return false;
1057 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001058 case AsmToken::Dot: {
1059 // This is a '.' reference, which references the current PC. Emit a
1060 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001061 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001062 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001063 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001064 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001065 Lex(); // Eat identifier.
1066 return false;
1067 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001068 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001069 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001070 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001071 case AsmToken::LBrac:
1072 if (!PlatformParser->HasBracketExpressions())
1073 return TokError("brackets expression not supported on this target");
1074 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001075 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001076 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001077 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001078 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001079 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001080 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001081 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001082 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001083 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001084 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001085 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001086 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001087 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001088 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001089 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001090 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001091 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001092 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001093 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001094 // MIPS unary expression operators. The lexer won't generate these tokens if
1095 // MCAsmInfo::HasMipsExpressions is false for the target.
1096 case AsmToken::PercentCall16:
1097 case AsmToken::PercentCall_Hi:
1098 case AsmToken::PercentCall_Lo:
1099 case AsmToken::PercentDtprel_Hi:
1100 case AsmToken::PercentDtprel_Lo:
1101 case AsmToken::PercentGot:
1102 case AsmToken::PercentGot_Disp:
1103 case AsmToken::PercentGot_Hi:
1104 case AsmToken::PercentGot_Lo:
1105 case AsmToken::PercentGot_Ofst:
1106 case AsmToken::PercentGot_Page:
1107 case AsmToken::PercentGottprel:
1108 case AsmToken::PercentGp_Rel:
1109 case AsmToken::PercentHi:
1110 case AsmToken::PercentHigher:
1111 case AsmToken::PercentHighest:
1112 case AsmToken::PercentLo:
1113 case AsmToken::PercentNeg:
1114 case AsmToken::PercentPcrel_Hi:
1115 case AsmToken::PercentPcrel_Lo:
1116 case AsmToken::PercentTlsgd:
1117 case AsmToken::PercentTlsldm:
1118 case AsmToken::PercentTprel_Hi:
1119 case AsmToken::PercentTprel_Lo:
1120 Lex(); // Eat the operator.
1121 if (Lexer.isNot(AsmToken::LParen))
1122 return TokError("expected '(' after operator");
1123 Lex(); // Eat the operator.
1124 if (parseExpression(Res, EndLoc))
1125 return true;
1126 if (Lexer.isNot(AsmToken::RParen))
1127 return TokError("expected ')'");
1128 Lex(); // Eat the operator.
1129 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1130 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001131 }
1132}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001133
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001134bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001135 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001136 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001137}
1138
Daniel Dunbar55f16672010-09-17 02:47:07 +00001139const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001140AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001141 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001142 // Ask the target implementation about this expression first.
1143 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1144 if (NewE)
1145 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001146 // Recurse over the given expression, rebuilding it to apply the given variant
1147 // if there is exactly one symbol.
1148 switch (E->getKind()) {
1149 case MCExpr::Target:
1150 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001151 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001152
1153 case MCExpr::SymbolRef: {
1154 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1155
1156 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001157 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1158 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001159 return E;
1160 }
1161
Jim Grosbach13760bd2015-05-30 01:25:56 +00001162 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001163 }
1164
1165 case MCExpr::Unary: {
1166 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001167 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001168 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001169 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001170 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001171 }
1172
1173 case MCExpr::Binary: {
1174 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001175 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1176 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001177
1178 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001179 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001180
Jim Grosbach4b905842013-09-20 23:08:21 +00001181 if (!LHS)
1182 LHS = BE->getLHS();
1183 if (!RHS)
1184 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001185
Jim Grosbach13760bd2015-05-30 01:25:56 +00001186 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001187 }
1188 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001189
Craig Toppera2886c22012-02-07 05:05:23 +00001190 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001191}
1192
Jim Grosbach4b905842013-09-20 23:08:21 +00001193/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001194///
Jim Grosbachbd164242011-08-20 16:24:13 +00001195/// expr ::= expr &&,|| expr -> lowest.
1196/// expr ::= expr |,^,&,! expr
1197/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1198/// expr ::= expr <<,>> expr
1199/// expr ::= expr +,- expr
1200/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001201/// expr ::= primaryexpr
1202///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001203bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001204 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001205 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001206 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001207 return true;
1208
Daniel Dunbar55f16672010-09-17 02:47:07 +00001209 // As a special case, we support 'a op b @ modifier' by rewriting the
1210 // expression to include the modifier. This is inefficient, but in general we
1211 // expect users to use 'a@modifier op b'.
1212 if (Lexer.getKind() == AsmToken::At) {
1213 Lex();
1214
1215 if (Lexer.isNot(AsmToken::Identifier))
1216 return TokError("unexpected symbol modifier following '@'");
1217
1218 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001219 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001220 if (Variant == MCSymbolRefExpr::VK_Invalid)
1221 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1222
Jim Grosbach4b905842013-09-20 23:08:21 +00001223 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001224 if (!ModifiedRes) {
1225 return TokError("invalid modifier '" + getTok().getIdentifier() +
1226 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001227 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001228
Daniel Dunbar55f16672010-09-17 02:47:07 +00001229 Res = ModifiedRes;
1230 Lex();
1231 }
1232
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001233 // Try to constant fold it up front, if possible.
1234 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001235 if (Res->evaluateAsAbsolute(Value))
1236 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001237
1238 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001239}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001240
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001241bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001242 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001243 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001244}
1245
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001246bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1247 SMLoc &EndLoc) {
1248 if (parseParenExpr(Res, EndLoc))
1249 return true;
1250
1251 for (; ParenDepth > 0; --ParenDepth) {
1252 if (parseBinOpRHS(1, Res, EndLoc))
1253 return true;
1254
1255 // We don't Lex() the last RParen.
1256 // This is the same behavior as parseParenExpression().
1257 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001258 EndLoc = getTok().getEndLoc();
1259 if (parseToken(AsmToken::RParen,
1260 "expected ')' in parentheses expression"))
1261 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001262 }
1263 }
1264 return false;
1265}
1266
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001267bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001268 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001269
Daniel Dunbar75630b32009-06-30 02:10:03 +00001270 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001271 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001272 return true;
1273
Jim Grosbach13760bd2015-05-30 01:25:56 +00001274 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001275 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001276
1277 return false;
1278}
1279
David Majnemer0993e0b2015-10-26 03:15:34 +00001280static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1281 MCBinaryExpr::Opcode &Kind,
1282 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001283 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001284 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001285 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001286
Jim Grosbach4b905842013-09-20 23:08:21 +00001287 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001288 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001289 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001290 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001291 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001292 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001293 return 1;
1294
Jim Grosbach4b905842013-09-20 23:08:21 +00001295 // Low Precedence: |, &, ^
1296 //
1297 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001298 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001299 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001300 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001301 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001302 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001303 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001304 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001305 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001306 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001307
Jim Grosbach4b905842013-09-20 23:08:21 +00001308 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001309 case AsmToken::EqualEqual:
1310 Kind = MCBinaryExpr::EQ;
1311 return 3;
1312 case AsmToken::ExclaimEqual:
1313 case AsmToken::LessGreater:
1314 Kind = MCBinaryExpr::NE;
1315 return 3;
1316 case AsmToken::Less:
1317 Kind = MCBinaryExpr::LT;
1318 return 3;
1319 case AsmToken::LessEqual:
1320 Kind = MCBinaryExpr::LTE;
1321 return 3;
1322 case AsmToken::Greater:
1323 Kind = MCBinaryExpr::GT;
1324 return 3;
1325 case AsmToken::GreaterEqual:
1326 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001327 return 3;
1328
Jim Grosbach4b905842013-09-20 23:08:21 +00001329 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001330 case AsmToken::LessLess:
1331 Kind = MCBinaryExpr::Shl;
1332 return 4;
1333 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001334 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001335 return 4;
1336
Jim Grosbach4b905842013-09-20 23:08:21 +00001337 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001338 case AsmToken::Plus:
1339 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001340 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001341 case AsmToken::Minus:
1342 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001343 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001344
Jim Grosbach4b905842013-09-20 23:08:21 +00001345 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001346 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001347 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001348 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001349 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001350 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001351 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001352 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001353 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001354 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001355 }
1356}
1357
David Majnemer0993e0b2015-10-26 03:15:34 +00001358static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1359 MCBinaryExpr::Opcode &Kind,
1360 bool ShouldUseLogicalShr) {
1361 switch (K) {
1362 default:
1363 return 0; // not a binop.
1364
1365 // Lowest Precedence: &&, ||
1366 case AsmToken::AmpAmp:
1367 Kind = MCBinaryExpr::LAnd;
1368 return 2;
1369 case AsmToken::PipePipe:
1370 Kind = MCBinaryExpr::LOr;
1371 return 1;
1372
1373 // Low Precedence: ==, !=, <>, <, <=, >, >=
1374 case AsmToken::EqualEqual:
1375 Kind = MCBinaryExpr::EQ;
1376 return 3;
1377 case AsmToken::ExclaimEqual:
1378 case AsmToken::LessGreater:
1379 Kind = MCBinaryExpr::NE;
1380 return 3;
1381 case AsmToken::Less:
1382 Kind = MCBinaryExpr::LT;
1383 return 3;
1384 case AsmToken::LessEqual:
1385 Kind = MCBinaryExpr::LTE;
1386 return 3;
1387 case AsmToken::Greater:
1388 Kind = MCBinaryExpr::GT;
1389 return 3;
1390 case AsmToken::GreaterEqual:
1391 Kind = MCBinaryExpr::GTE;
1392 return 3;
1393
1394 // Low Intermediate Precedence: +, -
1395 case AsmToken::Plus:
1396 Kind = MCBinaryExpr::Add;
1397 return 4;
1398 case AsmToken::Minus:
1399 Kind = MCBinaryExpr::Sub;
1400 return 4;
1401
1402 // High Intermediate Precedence: |, &, ^
1403 //
1404 // FIXME: gas seems to support '!' as an infix operator?
1405 case AsmToken::Pipe:
1406 Kind = MCBinaryExpr::Or;
1407 return 5;
1408 case AsmToken::Caret:
1409 Kind = MCBinaryExpr::Xor;
1410 return 5;
1411 case AsmToken::Amp:
1412 Kind = MCBinaryExpr::And;
1413 return 5;
1414
1415 // Highest Precedence: *, /, %, <<, >>
1416 case AsmToken::Star:
1417 Kind = MCBinaryExpr::Mul;
1418 return 6;
1419 case AsmToken::Slash:
1420 Kind = MCBinaryExpr::Div;
1421 return 6;
1422 case AsmToken::Percent:
1423 Kind = MCBinaryExpr::Mod;
1424 return 6;
1425 case AsmToken::LessLess:
1426 Kind = MCBinaryExpr::Shl;
1427 return 6;
1428 case AsmToken::GreaterGreater:
1429 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1430 return 6;
1431 }
1432}
1433
1434unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1435 MCBinaryExpr::Opcode &Kind) {
1436 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1437 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1438 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1439}
1440
Jim Grosbach4b905842013-09-20 23:08:21 +00001441/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001442/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001443bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001444 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001445 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001446 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001447 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001448 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001449
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001450 // If the next token is lower precedence than we are allowed to eat, return
1451 // successfully with what we ate already.
1452 if (TokPrec < Precedence)
1453 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001454
Sean Callanan686ed8d2010-01-19 20:22:31 +00001455 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001456
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001457 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001458 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001459 if (parsePrimaryExpr(RHS, EndLoc))
1460 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001461
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001462 // If BinOp binds less tightly with RHS than the operator after RHS, let
1463 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001464 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001465 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001466 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1467 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001468
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001469 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001470 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001471 }
1472}
1473
Chris Lattner36e02122009-06-21 20:54:55 +00001474/// ParseStatement:
1475/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001476/// ::= Label* Directive ...Operands... EndOfStatement
1477/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001478bool AsmParser::parseStatement(ParseStatementInfo &Info,
1479 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001480 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001481 // Eat initial spaces and comments
1482 while (Lexer.is(AsmToken::Space))
1483 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001484 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001485 // if this is a line comment we can drop it safely
1486 if (getTok().getString().front() == '\r' ||
1487 getTok().getString().front() == '\n')
1488 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001489 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001490 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001491 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001492 if (Lexer.is(AsmToken::Hash)) {
1493 // Seeing a hash here means that it was an end-of-line comment in
1494 // an asm syntax where hash's are not comment and the previous
1495 // statement parser did not check the end of statement. Relex as
1496 // EndOfStatement.
1497 StringRef CommentStr = parseStringToEndOfStatement();
1498 Lexer.Lex();
1499 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1500 return false;
1501 }
Nirav Davefd910412016-06-17 16:06:17 +00001502 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001503 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001504 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001505 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001506 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001507 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001508 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001509 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001510 if (Lexer.is(AsmToken::Integer)) {
1511 LocalLabelVal = getTok().getIntVal();
1512 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001513 if (!TheCondState.Ignore) {
1514 Lex(); // always eat a token
1515 return Error(IDLoc, "unexpected token at start of statement");
1516 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001517 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001518 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001519 IDVal = getTok().getString();
1520 Lex(); // Consume the integer token to be used as an identifier token.
1521 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001522 if (!TheCondState.Ignore) {
1523 Lex(); // always eat a token
1524 return Error(IDLoc, "unexpected token at start of statement");
1525 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001526 }
1527 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001528 } else if (Lexer.is(AsmToken::Dot)) {
1529 // Treat '.' as a valid identifier in this context.
1530 Lex();
1531 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001532 } else if (Lexer.is(AsmToken::LCurly)) {
1533 // Treat '{' as a valid identifier in this context.
1534 Lex();
1535 IDVal = "{";
1536
1537 } else if (Lexer.is(AsmToken::RCurly)) {
1538 // Treat '}' as a valid identifier in this context.
1539 Lex();
1540 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001541 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001542 if (!TheCondState.Ignore) {
1543 Lex(); // always eat a token
1544 return Error(IDLoc, "unexpected token at start of statement");
1545 }
Chris Lattner926885c2010-04-17 18:14:27 +00001546 IDVal = "";
1547 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001548
Chris Lattner926885c2010-04-17 18:14:27 +00001549 // Handle conditional assembly here before checking for skipping. We
1550 // have to do this so that .endif isn't skipped in a ".if 0" block for
1551 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001552 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001553 DirectiveKindMap.find(IDVal);
1554 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1555 ? DK_NO_DIRECTIVE
1556 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001557 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001558 default:
1559 break;
1560 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001561 case DK_IFEQ:
1562 case DK_IFGE:
1563 case DK_IFGT:
1564 case DK_IFLE:
1565 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001566 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001567 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001568 case DK_IFB:
1569 return parseDirectiveIfb(IDLoc, true);
1570 case DK_IFNB:
1571 return parseDirectiveIfb(IDLoc, false);
1572 case DK_IFC:
1573 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001574 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001575 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001576 case DK_IFNC:
1577 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001578 case DK_IFNES:
1579 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001580 case DK_IFDEF:
1581 return parseDirectiveIfdef(IDLoc, true);
1582 case DK_IFNDEF:
1583 case DK_IFNOTDEF:
1584 return parseDirectiveIfdef(IDLoc, false);
1585 case DK_ELSEIF:
1586 return parseDirectiveElseIf(IDLoc);
1587 case DK_ELSE:
1588 return parseDirectiveElse(IDLoc);
1589 case DK_ENDIF:
1590 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001591 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001592
Eli Bendersky88024712013-01-16 19:32:36 +00001593 // Ignore the statement if in the middle of inactive conditional
1594 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001595 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001596 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001597 return false;
1598 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001599
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001600 // FIXME: Recurse on local labels?
1601
1602 // See what kind of statement we have.
1603 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001604 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001605 if (!getTargetParser().isLabel(ID))
1606 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001607 if (checkForValidSection())
1608 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001609
Chris Lattner36e02122009-06-21 20:54:55 +00001610 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001611 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001612
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001613 // Diagnose attempt to use '.' as a label.
1614 if (IDVal == ".")
1615 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1616
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001617 // Diagnose attempt to use a variable as a label.
1618 //
1619 // FIXME: Diagnostics. Note the location of the definition as a label.
1620 // FIXME: This doesn't diagnose assignment to a symbol which has been
1621 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001622 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001623 if (LocalLabelVal == -1) {
1624 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001625 StringRef RewrittenLabel =
1626 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001627 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001628 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001629 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1630 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001631 IDVal = RewrittenLabel;
1632 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001633 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001634 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001635 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001636 // End of Labels should be treated as end of line for lexing
1637 // purposes but that information is not available to the Lexer who
1638 // does not understand Labels. This may cause us to see a Hash
1639 // here instead of a preprocessor line comment.
1640 if (getTok().is(AsmToken::Hash)) {
1641 StringRef CommentStr = parseStringToEndOfStatement();
1642 Lexer.Lex();
1643 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1644 }
1645
Nirav Dave8ea792d2016-07-13 14:03:12 +00001646 // Consume any end of statement token, if present, to avoid spurious
1647 // AddBlankLine calls().
1648 if (getTok().is(AsmToken::EndOfStatement)) {
1649 Lex();
1650 }
1651
Daniel Dunbare73b2672009-08-26 22:13:22 +00001652 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001653 if (!ParsingInlineAsm)
Rafael Espindolabe991572017-02-10 15:13:12 +00001654 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001655
Kevin Enderbye7739d42011-12-09 18:09:40 +00001656 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001657 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001658 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001659 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1660 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001661
Tim Northover1744d0a2013-10-25 12:49:50 +00001662 getTargetParser().onLabelParsed(Sym);
1663
Eli Friedman0f4871d2012-10-22 23:58:19 +00001664 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001665 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001666
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001667 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001668 if (!getTargetParser().equalIsAsmAssignment())
1669 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001670 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001671 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001672
Jim Grosbach4b905842013-09-20 23:08:21 +00001673 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001674
1675 default: // Normal instruction or directive.
1676 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001677 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001678
1679 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001680 if (areMacrosEnabled())
1681 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1682 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001683 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001684
Michael J. Spencer530ce852010-10-09 11:00:50 +00001685 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001686
Eli Bendersky17233942013-01-15 22:59:42 +00001687 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001688 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001689 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001690 //
Eli Bendersky17233942013-01-15 22:59:42 +00001691 // 1. The target-specific assembly parser. Some directives are target
1692 // specific or may potentially behave differently on certain targets.
1693 // 2. Asm parser extensions. For example, platform-specific parsers
1694 // (like the ELF parser) register themselves as extensions.
1695 // 3. The generic directive parser implemented by this class. These are
1696 // all the directives that behave in a target and platform independent
1697 // manner, or at least have a default behavior that's shared between
1698 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001699
Oliver Stannard21718282016-07-26 14:19:47 +00001700 getTargetParser().flushPendingInstructions(getStreamer());
1701
Nirav Dave2364748a2016-09-16 18:30:20 +00001702 SMLoc StartTokLoc = getTok().getLoc();
1703 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1704
1705 if (hasPendingError())
1706 return true;
1707 // Currently the return value should be true if we are
1708 // uninterested but as this is at odds with the standard parsing
1709 // convention (return true = error) we have instances of a parsed
1710 // directive that fails returning true as an error. Catch these
1711 // cases as best as possible errors here.
1712 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1713 return true;
1714 // Return if we did some parsing or believe we succeeded.
1715 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001716 return false;
1717
Alp Tokercb402912014-01-24 17:20:08 +00001718 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001719 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001720 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1721 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001722 if (Handler.first)
1723 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1724
1725 // Finally, if no one else is interested in this directive, it must be
1726 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001727 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001728 default:
1729 break;
1730 case DK_SET:
1731 case DK_EQU:
1732 return parseDirectiveSet(IDVal, true);
1733 case DK_EQUIV:
1734 return parseDirectiveSet(IDVal, false);
1735 case DK_ASCII:
1736 return parseDirectiveAscii(IDVal, false);
1737 case DK_ASCIZ:
1738 case DK_STRING:
1739 return parseDirectiveAscii(IDVal, true);
1740 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001741 case DK_DC_B:
1742 return parseDirectiveValue(IDVal, 1);
1743 case DK_DC:
1744 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001745 case DK_SHORT:
1746 case DK_VALUE:
1747 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001748 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001749 case DK_LONG:
1750 case DK_INT:
1751 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001752 case DK_DC_L:
1753 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001754 case DK_QUAD:
1755 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001756 return parseDirectiveValue(IDVal, 8);
1757 case DK_DC_A:
1758 return parseDirectiveValue(IDVal,
1759 getContext().getAsmInfo()->getPointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001760 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001761 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001762 case DK_SINGLE:
1763 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001764 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001765 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001766 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001767 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001768 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001769 case DK_ALIGN: {
1770 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1771 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1772 }
1773 case DK_ALIGN32: {
1774 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1775 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1776 }
1777 case DK_BALIGN:
1778 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1779 case DK_BALIGNW:
1780 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1781 case DK_BALIGNL:
1782 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1783 case DK_P2ALIGN:
1784 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1785 case DK_P2ALIGNW:
1786 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1787 case DK_P2ALIGNL:
1788 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1789 case DK_ORG:
1790 return parseDirectiveOrg();
1791 case DK_FILL:
1792 return parseDirectiveFill();
1793 case DK_ZERO:
1794 return parseDirectiveZero();
1795 case DK_EXTERN:
1796 eatToEndOfStatement(); // .extern is the default, ignore it.
1797 return false;
1798 case DK_GLOBL:
1799 case DK_GLOBAL:
1800 return parseDirectiveSymbolAttribute(MCSA_Global);
1801 case DK_LAZY_REFERENCE:
1802 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1803 case DK_NO_DEAD_STRIP:
1804 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1805 case DK_SYMBOL_RESOLVER:
1806 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1807 case DK_PRIVATE_EXTERN:
1808 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1809 case DK_REFERENCE:
1810 return parseDirectiveSymbolAttribute(MCSA_Reference);
1811 case DK_WEAK_DEFINITION:
1812 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1813 case DK_WEAK_REFERENCE:
1814 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1815 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1816 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1817 case DK_COMM:
1818 case DK_COMMON:
1819 return parseDirectiveComm(/*IsLocal=*/false);
1820 case DK_LCOMM:
1821 return parseDirectiveComm(/*IsLocal=*/true);
1822 case DK_ABORT:
1823 return parseDirectiveAbort();
1824 case DK_INCLUDE:
1825 return parseDirectiveInclude();
1826 case DK_INCBIN:
1827 return parseDirectiveIncbin();
1828 case DK_CODE16:
1829 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001830 return TokError(Twine(IDVal) +
1831 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001832 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001833 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001834 case DK_IRP:
1835 return parseDirectiveIrp(IDLoc);
1836 case DK_IRPC:
1837 return parseDirectiveIrpc(IDLoc);
1838 case DK_ENDR:
1839 return parseDirectiveEndr(IDLoc);
1840 case DK_BUNDLE_ALIGN_MODE:
1841 return parseDirectiveBundleAlignMode();
1842 case DK_BUNDLE_LOCK:
1843 return parseDirectiveBundleLock();
1844 case DK_BUNDLE_UNLOCK:
1845 return parseDirectiveBundleUnlock();
1846 case DK_SLEB128:
1847 return parseDirectiveLEB128(true);
1848 case DK_ULEB128:
1849 return parseDirectiveLEB128(false);
1850 case DK_SPACE:
1851 case DK_SKIP:
1852 return parseDirectiveSpace(IDVal);
1853 case DK_FILE:
1854 return parseDirectiveFile(IDLoc);
1855 case DK_LINE:
1856 return parseDirectiveLine();
1857 case DK_LOC:
1858 return parseDirectiveLoc();
1859 case DK_STABS:
1860 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001861 case DK_CV_FILE:
1862 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001863 case DK_CV_FUNC_ID:
1864 return parseDirectiveCVFuncId();
1865 case DK_CV_INLINE_SITE_ID:
1866 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001867 case DK_CV_LOC:
1868 return parseDirectiveCVLoc();
1869 case DK_CV_LINETABLE:
1870 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001871 case DK_CV_INLINE_LINETABLE:
1872 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001873 case DK_CV_DEF_RANGE:
1874 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001875 case DK_CV_STRINGTABLE:
1876 return parseDirectiveCVStringTable();
1877 case DK_CV_FILECHECKSUMS:
1878 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001879 case DK_CFI_SECTIONS:
1880 return parseDirectiveCFISections();
1881 case DK_CFI_STARTPROC:
1882 return parseDirectiveCFIStartProc();
1883 case DK_CFI_ENDPROC:
1884 return parseDirectiveCFIEndProc();
1885 case DK_CFI_DEF_CFA:
1886 return parseDirectiveCFIDefCfa(IDLoc);
1887 case DK_CFI_DEF_CFA_OFFSET:
1888 return parseDirectiveCFIDefCfaOffset();
1889 case DK_CFI_ADJUST_CFA_OFFSET:
1890 return parseDirectiveCFIAdjustCfaOffset();
1891 case DK_CFI_DEF_CFA_REGISTER:
1892 return parseDirectiveCFIDefCfaRegister(IDLoc);
1893 case DK_CFI_OFFSET:
1894 return parseDirectiveCFIOffset(IDLoc);
1895 case DK_CFI_REL_OFFSET:
1896 return parseDirectiveCFIRelOffset(IDLoc);
1897 case DK_CFI_PERSONALITY:
1898 return parseDirectiveCFIPersonalityOrLsda(true);
1899 case DK_CFI_LSDA:
1900 return parseDirectiveCFIPersonalityOrLsda(false);
1901 case DK_CFI_REMEMBER_STATE:
1902 return parseDirectiveCFIRememberState();
1903 case DK_CFI_RESTORE_STATE:
1904 return parseDirectiveCFIRestoreState();
1905 case DK_CFI_SAME_VALUE:
1906 return parseDirectiveCFISameValue(IDLoc);
1907 case DK_CFI_RESTORE:
1908 return parseDirectiveCFIRestore(IDLoc);
1909 case DK_CFI_ESCAPE:
1910 return parseDirectiveCFIEscape();
1911 case DK_CFI_SIGNAL_FRAME:
1912 return parseDirectiveCFISignalFrame();
1913 case DK_CFI_UNDEFINED:
1914 return parseDirectiveCFIUndefined(IDLoc);
1915 case DK_CFI_REGISTER:
1916 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001917 case DK_CFI_WINDOW_SAVE:
1918 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001919 case DK_MACROS_ON:
1920 case DK_MACROS_OFF:
1921 return parseDirectiveMacrosOnOff(IDVal);
1922 case DK_MACRO:
1923 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001924 case DK_EXITM:
1925 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001926 case DK_ENDM:
1927 case DK_ENDMACRO:
1928 return parseDirectiveEndMacro(IDVal);
1929 case DK_PURGEM:
1930 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001931 case DK_END:
1932 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001933 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001934 return parseDirectiveError(IDLoc, false);
1935 case DK_ERROR:
1936 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001937 case DK_WARNING:
1938 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001939 case DK_RELOC:
1940 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001941 case DK_DCB:
1942 case DK_DCB_W:
1943 return parseDirectiveDCB(IDVal, 2);
1944 case DK_DCB_B:
1945 return parseDirectiveDCB(IDVal, 1);
1946 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001947 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001948 case DK_DCB_L:
1949 return parseDirectiveDCB(IDVal, 4);
1950 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001951 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00001952 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001953 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00001954 return TokError(Twine(IDVal) +
1955 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00001956 case DK_DS:
1957 case DK_DS_W:
1958 return parseDirectiveDS(IDVal, 2);
1959 case DK_DS_B:
1960 return parseDirectiveDS(IDVal, 1);
1961 case DK_DS_D:
1962 return parseDirectiveDS(IDVal, 8);
1963 case DK_DS_L:
1964 case DK_DS_S:
1965 return parseDirectiveDS(IDVal, 4);
1966 case DK_DS_P:
1967 case DK_DS_X:
1968 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00001969 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001970
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001971 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001972 }
Chris Lattner36e02122009-06-21 20:54:55 +00001973
Chad Rosierc7f552c2013-02-12 21:33:51 +00001974 // __asm _emit or __asm __emit
1975 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1976 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001977 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001978
1979 // __asm align
1980 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001981 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001982
Coby Tayree3847be92017-04-04 17:57:23 +00001983 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001984 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00001985 if (checkForValidSection())
1986 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001987
Chris Lattner7cbfa442010-05-19 23:34:33 +00001988 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001989 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001990 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00001991 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1992 Info.ParsedOperands);
1993 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001994
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001995 // Dump the parsed representation, if requested.
1996 if (getShowParsedOperands()) {
1997 SmallString<256> Str;
1998 raw_svector_ostream OS(Str);
1999 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002000 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002001 if (i != 0)
2002 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002003 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002004 }
2005 OS << "]";
2006
Jim Grosbach4b905842013-09-20 23:08:21 +00002007 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002008 }
2009
Nirav Dave2364748a2016-09-16 18:30:20 +00002010 // Fail even if ParseInstruction erroneously returns false.
2011 if (hasPendingError() || ParseHadError)
2012 return true;
2013
Oliver Stannard8b273082014-06-19 15:52:37 +00002014 // If we are generating dwarf for the current section then generate a .loc
2015 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002016 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002017 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002018 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002019 unsigned Line;
2020 if (ActiveMacros.empty())
2021 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2022 else
Frederic Riss16238d92015-06-25 21:57:33 +00002023 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2024 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002025
Eli Bendersky88024712013-01-16 19:32:36 +00002026 // If we previously parsed a cpp hash file line comment then make sure the
2027 // current Dwarf File is for the CppHashFilename if not then emit the
2028 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002029 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002030 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002031 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002032 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002033
Jim Grosbach4b905842013-09-20 23:08:21 +00002034 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2035 // cache with the different Loc from the call above we save the last
2036 // info we queried here with SrcMgr.FindLineNumber().
2037 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002038 if (LastQueryIDLoc == CppHashInfo.Loc &&
2039 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002040 CppHashLocLineNo = LastQueryLine;
2041 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002042 CppHashLocLineNo =
2043 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002044 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002045 LastQueryIDLoc = CppHashInfo.Loc;
2046 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002047 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002048 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002049 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002050
Jim Grosbach4b905842013-09-20 23:08:21 +00002051 getStreamer().EmitDwarfLocDirective(
2052 getContext().getGenDwarfFileNumber(), Line, 0,
2053 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2054 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002055 }
2056
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002057 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002058 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002059 uint64_t ErrorInfo;
Nirav Dave2364748a2016-09-16 18:30:20 +00002060 if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2061 Info.ParsedOperands, Out,
2062 ErrorInfo, ParsingInlineAsm))
2063 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002064 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002065 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002066}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002067
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002068// Parse and erase curly braces marking block start/end
2069bool
2070AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2071 // Identify curly brace marking block start/end
2072 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2073 return false;
2074
2075 SMLoc StartLoc = Lexer.getLoc();
2076 Lex(); // Eat the brace
2077 if (Lexer.is(AsmToken::EndOfStatement))
2078 Lex(); // Eat EndOfStatement following the brace
2079
2080 // Erase the block start/end brace from the output asm string
2081 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2082 StartLoc.getPointer());
2083 return true;
2084}
2085
Jim Grosbach4b905842013-09-20 23:08:21 +00002086/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002087/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002088bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002089 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002090 // Lexer only ever emits HashDirective if it fully formed if it's
2091 // done the checking already so this is an internal error.
2092 assert(getTok().is(AsmToken::Integer) &&
2093 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002094 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002095 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002096 assert(getTok().is(AsmToken::String) &&
2097 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002098 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002099 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002100
Kevin Enderby72553612011-09-13 23:45:18 +00002101 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002102 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002103
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002104 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002105 CppHashInfo.Loc = L;
2106 CppHashInfo.Filename = Filename;
2107 CppHashInfo.LineNumber = LineNumber;
2108 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002109 return false;
2110}
2111
Jim Grosbach4b905842013-09-20 23:08:21 +00002112/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002113/// for the Filename and LineNo if any in the diagnostic.
2114void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002115 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002116 raw_ostream &OS = errs();
2117
2118 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002119 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002120 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2121 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002122 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002123
Jim Grosbach4b905842013-09-20 23:08:21 +00002124 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002125 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002126 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2127 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2128 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002129 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2130 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002131 }
2132
Eric Christophera7c32732012-12-18 00:30:54 +00002133 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002134 // manager changed or buffer changed (like in a nested include) then just
2135 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002136 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002137 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002138 if (Parser->SavedDiagHandler)
2139 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2140 else
Craig Topper353eda42014-04-24 06:44:33 +00002141 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002142 return;
2143 }
2144
Eric Christophera7c32732012-12-18 00:30:54 +00002145 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002146 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2147 // for the diagnostic.
2148 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002149
2150 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2151 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002152 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002153 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002154 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002155
Jim Grosbach4b905842013-09-20 23:08:21 +00002156 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2157 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002158 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002159
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002160 if (Parser->SavedDiagHandler)
2161 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2162 else
Craig Topper353eda42014-04-24 06:44:33 +00002163 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002164}
2165
Rafael Espindola2c064482012-08-21 18:29:30 +00002166// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2167// difference being that that function accepts '@' as part of identifiers and
2168// we can't do that. AsmLexer.cpp should probably be changed to handle
2169// '@' as a special case when needed.
2170static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002171 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2172 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002173}
2174
Rafael Espindola34b9c512012-06-03 23:57:14 +00002175bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002176 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002177 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002178 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002179 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002180 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002181 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002182 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002183
Preston Gurd05500642012-09-19 20:36:12 +00002184 // A macro without parameters is handled differently on Darwin:
2185 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002186 while (!Body.empty()) {
2187 // Scan for the next substitution.
2188 std::size_t End = Body.size(), Pos = 0;
2189 for (; Pos != End; ++Pos) {
2190 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002191 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002192 // This macro has no parameters, look for $0, $1, etc.
2193 if (Body[Pos] != '$' || Pos + 1 == End)
2194 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002195
Rafael Espindola1134ab232011-06-05 02:43:45 +00002196 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002197 if (Next == '$' || Next == 'n' ||
2198 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002199 break;
2200 } else {
2201 // This macro has parameters, look for \foo, \bar, etc.
2202 if (Body[Pos] == '\\' && Pos + 1 != End)
2203 break;
2204 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002205 }
2206
2207 // Add the prefix.
2208 OS << Body.slice(0, Pos);
2209
2210 // Check if we reached the end.
2211 if (Pos == End)
2212 break;
2213
Benjamin Kramer513e7442014-02-20 13:36:32 +00002214 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002215 switch (Body[Pos + 1]) {
2216 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002217 case '$':
2218 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002219 break;
2220
Jim Grosbach4b905842013-09-20 23:08:21 +00002221 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002222 case 'n':
2223 OS << A.size();
2224 break;
2225
Jim Grosbach4b905842013-09-20 23:08:21 +00002226 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002227 default: {
2228 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002229 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002230 if (Index >= A.size())
2231 break;
2232
2233 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002234 for (const AsmToken &Token : A[Index])
2235 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002236 break;
2237 }
2238 }
2239 Pos += 2;
2240 } else {
2241 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002242
2243 // Check for the \@ pseudo-variable.
2244 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002245 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002246 else
2247 while (isIdentifierChar(Body[I]) && I + 1 != End)
2248 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002249
Jim Grosbach4b905842013-09-20 23:08:21 +00002250 const char *Begin = Body.data() + Pos + 1;
2251 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002252 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002253
Toma Tabacu217116e2015-04-27 10:50:29 +00002254 if (Argument == "@") {
2255 OS << NumOfMacroInstantiations;
2256 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002257 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002258 for (; Index < NParameters; ++Index)
2259 if (Parameters[Index].Name == Argument)
2260 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002261
Toma Tabacu217116e2015-04-27 10:50:29 +00002262 if (Index == NParameters) {
2263 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2264 Pos += 3;
2265 else {
2266 OS << '\\' << Argument;
2267 Pos = I;
2268 }
2269 } else {
2270 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002271 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002272 // We expect no quotes around the string's contents when
2273 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002274 if (Token.getKind() != AsmToken::String || VarargParameter)
2275 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002276 else
Craig Topper84008482015-10-10 05:38:14 +00002277 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002278
2279 Pos += 1 + Argument.size();
2280 }
Preston Gurd05500642012-09-19 20:36:12 +00002281 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002282 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002283 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002284 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002285 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002286
Rafael Espindola1134ab232011-06-05 02:43:45 +00002287 return false;
2288}
Daniel Dunbar43235712010-07-18 18:54:11 +00002289
Nico Weber2a8f9222014-07-24 16:29:04 +00002290MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002291 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002292 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002293 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002294
Jim Grosbach4b905842013-09-20 23:08:21 +00002295static bool isOperator(AsmToken::TokenKind kind) {
2296 switch (kind) {
2297 default:
2298 return false;
2299 case AsmToken::Plus:
2300 case AsmToken::Minus:
2301 case AsmToken::Tilde:
2302 case AsmToken::Slash:
2303 case AsmToken::Star:
2304 case AsmToken::Dot:
2305 case AsmToken::Equal:
2306 case AsmToken::EqualEqual:
2307 case AsmToken::Pipe:
2308 case AsmToken::PipePipe:
2309 case AsmToken::Caret:
2310 case AsmToken::Amp:
2311 case AsmToken::AmpAmp:
2312 case AsmToken::Exclaim:
2313 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002314 case AsmToken::Less:
2315 case AsmToken::LessEqual:
2316 case AsmToken::LessLess:
2317 case AsmToken::LessGreater:
2318 case AsmToken::Greater:
2319 case AsmToken::GreaterEqual:
2320 case AsmToken::GreaterGreater:
2321 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002322 }
2323}
2324
David Majnemer16252452014-01-29 00:07:39 +00002325namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002326
David Majnemer16252452014-01-29 00:07:39 +00002327class AsmLexerSkipSpaceRAII {
2328public:
2329 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2330 Lexer.setSkipSpace(SkipSpace);
2331 }
2332
2333 ~AsmLexerSkipSpaceRAII() {
2334 Lexer.setSkipSpace(true);
2335 }
2336
2337private:
2338 AsmLexer &Lexer;
2339};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002340
2341} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002342
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002343bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2344
2345 if (Vararg) {
2346 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2347 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002348 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002349 }
2350 return false;
2351 }
2352
Rafael Espindola768b41c2012-06-15 14:02:34 +00002353 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002354
David Majnemer16252452014-01-29 00:07:39 +00002355 // Darwin doesn't use spaces to delmit arguments.
2356 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002357
Scott Egertona1fa68a2016-02-11 13:48:49 +00002358 bool SpaceEaten;
2359
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002360 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002361 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002362 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002363 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002364
Scott Egertona1fa68a2016-02-11 13:48:49 +00002365 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002366
Scott Egertona1fa68a2016-02-11 13:48:49 +00002367 if (Lexer.is(AsmToken::Comma))
2368 break;
2369
2370 if (Lexer.is(AsmToken::Space)) {
2371 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002372 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002373 }
Preston Gurd05500642012-09-19 20:36:12 +00002374
2375 // Spaces can delimit parameters, but could also be part an expression.
2376 // If the token after a space is an operator, add the token and the next
2377 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002378 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002379 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002380 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002381 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002382
Scott Egertona1fa68a2016-02-11 13:48:49 +00002383 // Whitespace after an operator can be ignored.
2384 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002385 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002386
2387 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002388 }
2389 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002390 if (SpaceEaten)
2391 break;
Preston Gurd05500642012-09-19 20:36:12 +00002392 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002393
Jim Grosbach4b905842013-09-20 23:08:21 +00002394 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002395 // to be able to fill in the remaining default parameter values
2396 if (Lexer.is(AsmToken::EndOfStatement))
2397 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002398
2399 // Adjust the current parentheses level.
2400 if (Lexer.is(AsmToken::LParen))
2401 ++ParenLevel;
2402 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2403 --ParenLevel;
2404
2405 // Append the token to the current argument list.
2406 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002407 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002408 }
Preston Gurd05500642012-09-19 20:36:12 +00002409
Rafael Espindola768b41c2012-06-15 14:02:34 +00002410 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002411 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002412 return false;
2413}
2414
2415// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002416bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002417 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002418 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002419 bool NamedParametersFound = false;
2420 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002421
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002422 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002423 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002424
Rafael Espindola768b41c2012-06-15 14:02:34 +00002425 // Parse two kinds of macro invocations:
2426 // - macros defined without any parameters accept an arbitrary number of them
2427 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002428 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002429 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2430 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002431 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002432 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002433
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002434 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002435 if (parseIdentifier(FA.Name))
2436 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002437
Nirav Dave2364748a2016-09-16 18:30:20 +00002438 if (Lexer.isNot(AsmToken::Equal))
2439 return TokError("expected '=' after formal parameter identifier");
2440
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002441 Lex();
2442
2443 NamedParametersFound = true;
2444 }
2445
Nirav Dave2364748a2016-09-16 18:30:20 +00002446 if (NamedParametersFound && FA.Name.empty())
2447 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002448
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002449 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2450 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002451 return true;
2452
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002453 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002454 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002455 unsigned FAI = 0;
2456 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002457 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002458 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002459
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002460 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002461 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002462 return Error(IDLoc, "parameter named '" + FA.Name +
2463 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002464 }
2465 PI = FAI;
2466 }
2467
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002468 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002469 if (A.size() <= PI)
2470 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002471 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002472
2473 if (FALocs.size() <= PI)
2474 FALocs.resize(PI + 1);
2475
2476 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002477 }
Jim Grosbach206661622012-07-30 22:44:17 +00002478
Preston Gurd242ed3152012-09-19 20:29:04 +00002479 // At the end of the statement, fill in remaining arguments that have
2480 // default values. If there aren't any, then the next argument is
2481 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002482 if (Lexer.is(AsmToken::EndOfStatement)) {
2483 bool Failure = false;
2484 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2485 if (A[FAI].empty()) {
2486 if (M->Parameters[FAI].Required) {
2487 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2488 "missing value for required parameter "
2489 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2490 Failure = true;
2491 }
2492
2493 if (!M->Parameters[FAI].Value.empty())
2494 A[FAI] = M->Parameters[FAI].Value;
2495 }
2496 }
2497 return Failure;
2498 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002499
2500 if (Lexer.is(AsmToken::Comma))
2501 Lex();
2502 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002503
2504 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002505}
2506
Jim Grosbach4b905842013-09-20 23:08:21 +00002507const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002508 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2509 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002510}
2511
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002512void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2513 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002514}
2515
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002516void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002517
Jim Grosbach4b905842013-09-20 23:08:21 +00002518bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002519 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2520 // eliminate this, although we should protect against infinite loops.
2521 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2522 if (ActiveMacros.size() == MaxNestingDepth) {
2523 std::ostringstream MaxNestingDepthError;
2524 MaxNestingDepthError << "macros cannot be nested more than "
2525 << MaxNestingDepth << " levels deep."
2526 << " Use -asm-macro-max-nesting-depth to increase "
2527 "this limit.";
2528 return TokError(MaxNestingDepthError.str());
2529 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002530
Eli Bendersky38274122013-01-14 23:22:36 +00002531 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002532 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002533 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002534
Rafael Espindola1134ab232011-06-05 02:43:45 +00002535 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2536 // to hold the macro body with substitutions.
2537 SmallString<256> Buf;
2538 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002539 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002540
Toma Tabacu217116e2015-04-27 10:50:29 +00002541 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002542 return true;
2543
Eli Bendersky38274122013-01-14 23:22:36 +00002544 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002545 // instantiation.
2546 OS << ".endmacro\n";
2547
Rafael Espindola3560ff22014-08-27 20:03:13 +00002548 std::unique_ptr<MemoryBuffer> Instantiation =
2549 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002550
Daniel Dunbar43235712010-07-18 18:54:11 +00002551 // Create the macro instantiation object and add to the current macro
2552 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002553 MacroInstantiation *MI = new MacroInstantiation(
2554 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002555 ActiveMacros.push_back(MI);
2556
Toma Tabacu217116e2015-04-27 10:50:29 +00002557 ++NumOfMacroInstantiations;
2558
Daniel Dunbar43235712010-07-18 18:54:11 +00002559 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002560 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002561 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002562 Lex();
2563
2564 return false;
2565}
2566
Jim Grosbach4b905842013-09-20 23:08:21 +00002567void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002568 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002569 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002570 Lex();
2571
2572 // Pop the instantiation entry.
2573 delete ActiveMacros.back();
2574 ActiveMacros.pop_back();
2575}
2576
Jim Grosbach4b905842013-09-20 23:08:21 +00002577bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002578 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002579 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002580 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002581 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2582 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002583 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002584
Pete Cooper80d21cb2015-06-22 19:35:57 +00002585 if (!Sym) {
2586 // In the case where we parse an expression starting with a '.', we will
2587 // not generate an error, nor will we create a symbol. In this case we
2588 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002589 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002590 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002591
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002592 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002593 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002594 if (NoDeadStrip)
2595 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2596
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002597 return false;
2598}
2599
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002600/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002601/// ::= identifier
2602/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002603bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002604 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002605 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2606 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002607 // handle this as a context dependent token, instead we detect adjacent tokens
2608 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002609 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2610 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002611
Hans Wennborgce69d772013-10-18 20:46:28 +00002612 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002613
2614 AsmToken Buf[1];
2615 Lexer.peekTokens(Buf, false);
2616
2617 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002618 return true;
2619
Hans Wennborgce69d772013-10-18 20:46:28 +00002620 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002621 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002622 return true;
2623
Nirav Daved0463322016-10-12 13:58:07 +00002624 // eat $ or @
2625 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002626 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002627 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002628 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002629 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002630 return false;
2631 }
2632
Jim Grosbach4b905842013-09-20 23:08:21 +00002633 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002634 return true;
2635
Sean Callanan936b0d32010-01-19 21:44:56 +00002636 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002637
Sean Callanan686ed8d2010-01-19 20:22:31 +00002638 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002639
2640 return false;
2641}
2642
Jim Grosbach4b905842013-09-20 23:08:21 +00002643/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002644/// ::= .equ identifier ',' expression
2645/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002646/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002647bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002648 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002649 if (check(parseIdentifier(Name), "expected identifier") ||
2650 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2651 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2652 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002653}
2654
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002655bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002656 if (check(getTok().isNot(AsmToken::String), "expected string"))
2657 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002658
2659 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002660 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002661 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2662 if (Str[i] != '\\') {
2663 Data += Str[i];
2664 continue;
2665 }
2666
2667 // Recognize escaped characters. Note that this escape semantics currently
2668 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2669 ++i;
2670 if (i == e)
2671 return TokError("unexpected backslash at end of string");
2672
2673 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002674 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002675 // Consume up to three octal characters.
2676 unsigned Value = Str[i] - '0';
2677
Jim Grosbach4b905842013-09-20 23:08:21 +00002678 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002679 ++i;
2680 Value = Value * 8 + (Str[i] - '0');
2681
Jim Grosbach4b905842013-09-20 23:08:21 +00002682 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002683 ++i;
2684 Value = Value * 8 + (Str[i] - '0');
2685 }
2686 }
2687
2688 if (Value > 255)
2689 return TokError("invalid octal escape sequence (out of range)");
2690
Jim Grosbach4b905842013-09-20 23:08:21 +00002691 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002692 continue;
2693 }
2694
2695 // Otherwise recognize individual escapes.
2696 switch (Str[i]) {
2697 default:
2698 // Just reject invalid escape sequences for now.
2699 return TokError("invalid escape sequence (unrecognized character)");
2700
2701 case 'b': Data += '\b'; break;
2702 case 'f': Data += '\f'; break;
2703 case 'n': Data += '\n'; break;
2704 case 'r': Data += '\r'; break;
2705 case 't': Data += '\t'; break;
2706 case '"': Data += '"'; break;
2707 case '\\': Data += '\\'; break;
2708 }
2709 }
2710
Nirav Davea645433c2016-07-18 15:24:03 +00002711 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002712 return false;
2713}
2714
Jim Grosbach4b905842013-09-20 23:08:21 +00002715/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002716/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002717bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002718 auto parseOp = [&]() -> bool {
2719 std::string Data;
2720 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002721 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002722 getStreamer().EmitBytes(Data);
2723 if (ZeroTerminated)
2724 getStreamer().EmitBytes(StringRef("\0", 1));
2725 return false;
2726 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002727
Nirav Dave1a9044b2016-10-24 14:35:29 +00002728 if (parseMany(parseOp))
2729 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002730 return false;
2731}
2732
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002733/// parseDirectiveReloc
2734/// ::= .reloc expression , identifier [ , expression ]
2735bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2736 const MCExpr *Offset;
2737 const MCExpr *Expr = nullptr;
2738
2739 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002740 int64_t OffsetValue;
2741 // We can only deal with constant expressions at the moment.
2742
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002743 if (parseExpression(Offset))
2744 return true;
2745
Nirav Davea645433c2016-07-18 15:24:03 +00002746 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2747 "expression is not a constant value") ||
2748 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2749 parseToken(AsmToken::Comma, "expected comma") ||
2750 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2751 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002752
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002753 SMLoc NameLoc = Lexer.getTok().getLoc();
2754 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002755 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002756
2757 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002758 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002759 SMLoc ExprLoc = Lexer.getLoc();
2760 if (parseExpression(Expr))
2761 return true;
2762
2763 MCValue Value;
2764 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2765 return Error(ExprLoc, "expression must be relocatable");
2766 }
2767
Nirav Davea645433c2016-07-18 15:24:03 +00002768 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002769 "unexpected token in .reloc directive"))
2770 return true;
2771
2772 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2773 return Error(NameLoc, "unknown relocation name");
2774
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002775 return false;
2776}
2777
Jim Grosbach4b905842013-09-20 23:08:21 +00002778/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002779/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002780bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2781 auto parseOp = [&]() -> bool {
2782 const MCExpr *Value;
2783 SMLoc ExprLoc = getLexer().getLoc();
2784 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002785 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002786 // Special case constant expressions to match code generator.
2787 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2788 assert(Size <= 8 && "Invalid size");
2789 uint64_t IntValue = MCE->getValue();
2790 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2791 return Error(ExprLoc, "out of range literal value");
2792 getStreamer().EmitIntValue(IntValue, Size);
2793 } else
2794 getStreamer().EmitValue(Value, Size, ExprLoc);
2795 return false;
2796 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002797
Nirav Dave1a9044b2016-10-24 14:35:29 +00002798 if (parseMany(parseOp))
2799 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002800 return false;
2801}
2802
David Woodhoused6de0d92014-02-01 16:20:59 +00002803/// ParseDirectiveOctaValue
2804/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002805
2806bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2807 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002808 if (checkForValidSection())
2809 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002810 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2811 return TokError("unknown token in expression");
2812 SMLoc ExprLoc = getTok().getLoc();
2813 APInt IntValue = getTok().getAPIntVal();
2814 uint64_t hi, lo;
2815 Lex();
2816 if (!IntValue.isIntN(128))
2817 return Error(ExprLoc, "out of range literal value");
2818 if (!IntValue.isIntN(64)) {
2819 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2820 lo = IntValue.getLoBits(64).getZExtValue();
2821 } else {
2822 hi = 0;
2823 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002824 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002825 if (MAI.isLittleEndian()) {
2826 getStreamer().EmitIntValue(lo, 8);
2827 getStreamer().EmitIntValue(hi, 8);
2828 } else {
2829 getStreamer().EmitIntValue(hi, 8);
2830 getStreamer().EmitIntValue(lo, 8);
2831 }
2832 return false;
2833 };
David Woodhoused6de0d92014-02-01 16:20:59 +00002834
Nirav Dave1a9044b2016-10-24 14:35:29 +00002835 if (parseMany(parseOp))
2836 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00002837 return false;
2838}
2839
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002840bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2841 // We don't truly support arithmetic on floating point expressions, so we
2842 // have to manually parse unary prefixes.
2843 bool IsNeg = false;
2844 if (getLexer().is(AsmToken::Minus)) {
2845 Lexer.Lex();
2846 IsNeg = true;
2847 } else if (getLexer().is(AsmToken::Plus))
2848 Lexer.Lex();
2849
2850 if (Lexer.is(AsmToken::Error))
2851 return TokError(Lexer.getErr());
2852 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2853 Lexer.isNot(AsmToken::Identifier))
2854 return TokError("unexpected token in directive");
2855
2856 // Convert to an APFloat.
2857 APFloat Value(Semantics);
2858 StringRef IDVal = getTok().getString();
2859 if (getLexer().is(AsmToken::Identifier)) {
2860 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2861 Value = APFloat::getInf(Semantics);
2862 else if (!IDVal.compare_lower("nan"))
2863 Value = APFloat::getNaN(Semantics, false, ~0);
2864 else
2865 return TokError("invalid floating point literal");
2866 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2867 APFloat::opInvalidOp)
2868 return TokError("invalid floating point literal");
2869 if (IsNeg)
2870 Value.changeSign();
2871
2872 // Consume the numeric token.
2873 Lex();
2874
2875 Res = Value.bitcastToAPInt();
2876
2877 return false;
2878}
2879
Jim Grosbach4b905842013-09-20 23:08:21 +00002880/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002881/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002882bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2883 const fltSemantics &Semantics) {
2884 auto parseOp = [&]() -> bool {
2885 APInt AsInt;
2886 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002887 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002888 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2889 AsInt.getBitWidth() / 8);
2890 return false;
2891 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00002892
Nirav Dave1a9044b2016-10-24 14:35:29 +00002893 if (parseMany(parseOp))
2894 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00002895 return false;
2896}
2897
Jim Grosbach4b905842013-09-20 23:08:21 +00002898/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002899/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002900bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002901 SMLoc NumBytesLoc = Lexer.getLoc();
2902 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002903 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002904 return true;
2905
Rafael Espindolab91bac62010-10-05 19:42:57 +00002906 int64_t Val = 0;
2907 if (getLexer().is(AsmToken::Comma)) {
2908 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002909 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002910 return true;
2911 }
2912
Nirav Davea645433c2016-07-18 15:24:03 +00002913 if (parseToken(AsmToken::EndOfStatement,
2914 "unexpected token in '.zero' directive"))
2915 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002916 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002917
2918 return false;
2919}
2920
Jim Grosbach4b905842013-09-20 23:08:21 +00002921/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002922/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002923bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002924 SMLoc NumValuesLoc = Lexer.getLoc();
2925 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002926 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002927 return true;
2928
Roman Divackye33098f2013-09-24 17:44:41 +00002929 int64_t FillSize = 1;
2930 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002931
David Majnemer522d3db2014-02-01 07:19:38 +00002932 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002933
Nirav Dave1a9044b2016-10-24 14:35:29 +00002934 if (parseOptionalToken(AsmToken::Comma)) {
2935 SizeLoc = getTok().getLoc();
2936 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002937 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002938 if (parseOptionalToken(AsmToken::Comma)) {
2939 ExprLoc = getTok().getLoc();
2940 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00002941 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002942 }
2943 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002944 if (parseToken(AsmToken::EndOfStatement,
2945 "unexpected token in '.fill' directive"))
2946 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002947
David Majnemer522d3db2014-02-01 07:19:38 +00002948 if (FillSize < 0) {
2949 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002950 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002951 }
2952 if (FillSize > 8) {
2953 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2954 FillSize = 8;
2955 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002956
David Majnemer522d3db2014-02-01 07:19:38 +00002957 if (!isUInt<32>(FillExpr) && FillSize > 4)
2958 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2959
Petr Hosek67a94a72016-05-28 05:57:48 +00002960 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002961
2962 return false;
2963}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002964
Jim Grosbach4b905842013-09-20 23:08:21 +00002965/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002966/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002967bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002968 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00002969 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00002970 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002971 return true;
2972
2973 // Parse optional fill expression.
2974 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002975 if (parseOptionalToken(AsmToken::Comma))
2976 if (parseAbsoluteExpression(FillExpr))
2977 return addErrorSuffix(" in '.org' directive");
2978 if (parseToken(AsmToken::EndOfStatement))
2979 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00002980
Oliver Stannard268f42f2016-12-14 10:43:58 +00002981 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002982 return false;
2983}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002984
Jim Grosbach4b905842013-09-20 23:08:21 +00002985/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002986/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002987bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002988 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002989 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002990 SMLoc MaxBytesLoc;
2991 bool HasFillExpr = false;
2992 int64_t FillExpr = 0;
2993 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002994
2995 auto parseAlign = [&]() -> bool {
2996 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00002997 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002998 if (parseOptionalToken(AsmToken::Comma)) {
2999 // The fill expression can be omitted while specifying a maximum number of
3000 // alignment bytes, e.g:
3001 // .align 3,,4
3002 if (getTok().isNot(AsmToken::Comma)) {
3003 HasFillExpr = true;
3004 if (parseAbsoluteExpression(FillExpr))
3005 return true;
3006 }
3007 if (parseOptionalToken(AsmToken::Comma))
3008 if (parseTokenLoc(MaxBytesLoc) ||
3009 parseAbsoluteExpression(MaxBytesToFill))
3010 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003011 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003012 return parseToken(AsmToken::EndOfStatement);
3013 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003014
Nirav Dave1a9044b2016-10-24 14:35:29 +00003015 if (parseAlign())
3016 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003017
Nirav Dave2364748a2016-09-16 18:30:20 +00003018 // Always emit an alignment here even if we thrown an error.
3019 bool ReturnVal = false;
3020
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003021 // Compute alignment in bytes.
3022 if (IsPow2) {
3023 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003024 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003025 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003026 Alignment = 31;
3027 }
3028
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003029 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003030 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003031 // Reject alignments that aren't either a power of two or zero,
3032 // for gas compatibility. Alignment of zero is silently rounded
3033 // up to one.
3034 if (Alignment == 0)
3035 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003036 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003037 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003038 }
3039
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003040 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003041 if (MaxBytesLoc.isValid()) {
3042 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003043 ReturnVal |= Error(MaxBytesLoc,
3044 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003045 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003046 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003047 }
3048
3049 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003050 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003051 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003052 MaxBytesToFill = 0;
3053 }
3054 }
3055
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003056 // Check whether we should use optimal code alignment for this .align
3057 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003058 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003059 assert(Section && "must have section to emit alignment");
3060 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003061 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3062 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003063 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003064 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003065 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003066 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3067 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003068 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003069
Nirav Dave2364748a2016-09-16 18:30:20 +00003070 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003071}
3072
Jim Grosbach4b905842013-09-20 23:08:21 +00003073/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003074/// ::= .file [number] filename
3075/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003076bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003077 // FIXME: I'm not sure what this is.
3078 int64_t FileNumber = -1;
3079 SMLoc FileNumberLoc = getLexer().getLoc();
3080 if (getLexer().is(AsmToken::Integer)) {
3081 FileNumber = getTok().getIntVal();
3082 Lex();
3083
3084 if (FileNumber < 1)
3085 return TokError("file number less than one");
3086 }
3087
Nirav Davea645433c2016-07-18 15:24:03 +00003088 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003089
3090 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003091 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003092 if (check(getTok().isNot(AsmToken::String),
3093 "unexpected token in '.file' directive") ||
3094 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003095 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003096
3097 StringRef Directory;
3098 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003099 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003100 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003101 if (check(FileNumber == -1,
3102 "explicit path specified, but no file number") ||
3103 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003104 return true;
3105 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003106 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003107 } else {
3108 Filename = Path;
3109 }
3110
Nirav Davea645433c2016-07-18 15:24:03 +00003111 if (parseToken(AsmToken::EndOfStatement,
3112 "unexpected token in '.file' directive"))
3113 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003114
3115 if (FileNumber == -1)
3116 getStreamer().EmitFileDirective(Filename);
3117 else {
David Blaikie22748082016-05-26 00:22:26 +00003118 // If there is -g option as well as debug info from directive file,
3119 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003120 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003121 getContext().setGenDwarfForAssembly(false);
3122 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003123 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003124 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003125 }
3126
3127 return false;
3128}
3129
Jim Grosbach4b905842013-09-20 23:08:21 +00003130/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003131/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003132bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003133 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003134 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003135 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3136 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003137 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003138 // FIXME: Do something with the .line.
3139 }
Nirav Davea645433c2016-07-18 15:24:03 +00003140 if (parseToken(AsmToken::EndOfStatement,
3141 "unexpected token in '.line' directive"))
3142 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003143
3144 return false;
3145}
3146
Jim Grosbach4b905842013-09-20 23:08:21 +00003147/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003148/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3149/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3150/// The first number is a file number, must have been previously assigned with
3151/// a .file directive, the second number is the line number and optionally the
3152/// third number is a column position (zero if not specified). The remaining
3153/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003154bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003155 int64_t FileNumber = 0, LineNumber = 0;
3156 SMLoc Loc = getTok().getLoc();
3157 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3158 check(FileNumber < 1, Loc,
3159 "file number less than one in '.loc' directive") ||
3160 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3161 "unassigned file number in '.loc' directive"))
3162 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003163
Nirav Davea645433c2016-07-18 15:24:03 +00003164 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003165 if (getLexer().is(AsmToken::Integer)) {
3166 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003167 if (LineNumber < 0)
3168 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003169 Lex();
3170 }
3171
3172 int64_t ColumnPos = 0;
3173 if (getLexer().is(AsmToken::Integer)) {
3174 ColumnPos = getTok().getIntVal();
3175 if (ColumnPos < 0)
3176 return TokError("column position less than zero in '.loc' directive");
3177 Lex();
3178 }
3179
3180 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3181 unsigned Isa = 0;
3182 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003183
Nirav Dave1a9044b2016-10-24 14:35:29 +00003184 auto parseLocOp = [&]() -> bool {
3185 StringRef Name;
3186 SMLoc Loc = getTok().getLoc();
3187 if (parseIdentifier(Name))
3188 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003189
Nirav Dave1a9044b2016-10-24 14:35:29 +00003190 if (Name == "basic_block")
3191 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3192 else if (Name == "prologue_end")
3193 Flags |= DWARF2_FLAG_PROLOGUE_END;
3194 else if (Name == "epilogue_begin")
3195 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3196 else if (Name == "is_stmt") {
3197 Loc = getTok().getLoc();
3198 const MCExpr *Value;
3199 if (parseExpression(Value))
3200 return true;
3201 // The expression must be the constant 0 or 1.
3202 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3203 int Value = MCE->getValue();
3204 if (Value == 0)
3205 Flags &= ~DWARF2_FLAG_IS_STMT;
3206 else if (Value == 1)
3207 Flags |= DWARF2_FLAG_IS_STMT;
3208 else
3209 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003210 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003211 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003212 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003213 } else if (Name == "isa") {
3214 Loc = getTok().getLoc();
3215 const MCExpr *Value;
3216 if (parseExpression(Value))
3217 return true;
3218 // The expression must be a constant greater or equal to 0.
3219 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3220 int Value = MCE->getValue();
3221 if (Value < 0)
3222 return Error(Loc, "isa number less than zero");
3223 Isa = Value;
3224 } else {
3225 return Error(Loc, "isa number not a constant value");
3226 }
3227 } else if (Name == "discriminator") {
3228 if (parseAbsoluteExpression(Discriminator))
3229 return true;
3230 } else {
3231 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003232 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003233 return false;
3234 };
3235
Nirav Davee2369aa2016-10-26 17:28:58 +00003236 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003237 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003238
3239 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3240 Isa, Discriminator, StringRef());
3241
3242 return false;
3243}
3244
Jim Grosbach4b905842013-09-20 23:08:21 +00003245/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003246/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003247bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003248 return TokError("unsupported directive '.stabs'");
3249}
3250
Reid Kleckner2214ed82016-01-29 00:49:42 +00003251/// parseDirectiveCVFile
3252/// ::= .cv_file number filename
3253bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003254 SMLoc FileNumberLoc = getTok().getLoc();
3255 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003256 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003257
3258 if (parseIntToken(FileNumber,
3259 "expected file number in '.cv_file' directive") ||
3260 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3261 check(getTok().isNot(AsmToken::String),
3262 "unexpected token in '.cv_file' directive") ||
3263 // Usually directory and filename are together, otherwise just
3264 // directory. Allow the strings to have escaped octal character sequence.
3265 parseEscapedString(Filename) ||
3266 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003267 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003268 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003269
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003270 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003271 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003272
3273 return false;
3274}
3275
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003276bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3277 StringRef DirectiveName) {
3278 SMLoc Loc;
3279 return parseTokenLoc(Loc) ||
3280 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3281 "' directive") ||
3282 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3283 "expected function id within range [0, UINT_MAX)");
3284}
3285
3286bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3287 SMLoc Loc;
3288 return parseTokenLoc(Loc) ||
3289 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3290 "' directive") ||
3291 check(FileNumber < 1, Loc, "file number less than one in '" +
3292 DirectiveName + "' directive") ||
3293 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3294 "unassigned file number in '" + DirectiveName + "' directive");
3295}
3296
3297/// parseDirectiveCVFuncId
3298/// ::= .cv_func_id FunctionId
3299///
3300/// Introduces a function ID that can be used with .cv_loc.
3301bool AsmParser::parseDirectiveCVFuncId() {
3302 SMLoc FunctionIdLoc = getTok().getLoc();
3303 int64_t FunctionId;
3304
3305 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3306 parseToken(AsmToken::EndOfStatement,
3307 "unexpected token in '.cv_func_id' directive"))
3308 return true;
3309
3310 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003311 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003312
3313 return false;
3314}
3315
3316/// parseDirectiveCVInlineSiteId
3317/// ::= .cv_inline_site_id FunctionId
3318/// "within" IAFunc
3319/// "inlined_at" IAFile IALine [IACol]
3320///
3321/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3322/// at" source location information for use in the line table of the caller,
3323/// whether the caller is a real function or another inlined call site.
3324bool AsmParser::parseDirectiveCVInlineSiteId() {
3325 SMLoc FunctionIdLoc = getTok().getLoc();
3326 int64_t FunctionId;
3327 int64_t IAFunc;
3328 int64_t IAFile;
3329 int64_t IALine;
3330 int64_t IACol = 0;
3331
3332 // FunctionId
3333 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3334 return true;
3335
3336 // "within"
3337 if (check((getLexer().isNot(AsmToken::Identifier) ||
3338 getTok().getIdentifier() != "within"),
3339 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3340 return true;
3341 Lex();
3342
3343 // IAFunc
3344 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3345 return true;
3346
3347 // "inlined_at"
3348 if (check((getLexer().isNot(AsmToken::Identifier) ||
3349 getTok().getIdentifier() != "inlined_at"),
3350 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3351 "directive") )
3352 return true;
3353 Lex();
3354
3355 // IAFile IALine
3356 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3357 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3358 return true;
3359
3360 // [IACol]
3361 if (getLexer().is(AsmToken::Integer)) {
3362 IACol = getTok().getIntVal();
3363 Lex();
3364 }
3365
3366 if (parseToken(AsmToken::EndOfStatement,
3367 "unexpected token in '.cv_inline_site_id' directive"))
3368 return true;
3369
3370 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3371 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003372 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003373
3374 return false;
3375}
3376
Reid Kleckner2214ed82016-01-29 00:49:42 +00003377/// parseDirectiveCVLoc
3378/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3379/// [is_stmt VALUE]
3380/// The first number is a file number, must have been previously assigned with
3381/// a .file directive, the second number is the line number and optionally the
3382/// third number is a column position (zero if not specified). The remaining
3383/// optional items are .loc sub-directives.
3384bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003385 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003386 SMLoc Loc;
3387 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003388 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3389 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003390 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003391
3392 int64_t LineNumber = 0;
3393 if (getLexer().is(AsmToken::Integer)) {
3394 LineNumber = getTok().getIntVal();
3395 if (LineNumber < 0)
3396 return TokError("line number less than zero in '.cv_loc' directive");
3397 Lex();
3398 }
3399
3400 int64_t ColumnPos = 0;
3401 if (getLexer().is(AsmToken::Integer)) {
3402 ColumnPos = getTok().getIntVal();
3403 if (ColumnPos < 0)
3404 return TokError("column position less than zero in '.cv_loc' directive");
3405 Lex();
3406 }
3407
3408 bool PrologueEnd = false;
3409 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003410
3411 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003412 StringRef Name;
3413 SMLoc Loc = getTok().getLoc();
3414 if (parseIdentifier(Name))
3415 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003416 if (Name == "prologue_end")
3417 PrologueEnd = true;
3418 else if (Name == "is_stmt") {
3419 Loc = getTok().getLoc();
3420 const MCExpr *Value;
3421 if (parseExpression(Value))
3422 return true;
3423 // The expression must be the constant 0 or 1.
3424 IsStmt = ~0ULL;
3425 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3426 IsStmt = MCE->getValue();
3427
3428 if (IsStmt > 1)
3429 return Error(Loc, "is_stmt value not 0 or 1");
3430 } else {
3431 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3432 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003433 return false;
3434 };
3435
3436 if (parseMany(parseOp, false /*hasComma*/))
3437 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003438
3439 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003440 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3441 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003442 return false;
3443}
3444
3445/// parseDirectiveCVLinetable
3446/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3447bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003448 int64_t FunctionId;
3449 StringRef FnStartName, FnEndName;
3450 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003451 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003452 parseToken(AsmToken::Comma,
3453 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003454 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3455 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003456 parseToken(AsmToken::Comma,
3457 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003458 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3459 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003460 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003461
3462 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3463 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3464
3465 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3466 return false;
3467}
3468
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003469/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003470/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003471bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003472 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3473 StringRef FnStartName, FnEndName;
3474 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003475 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003476 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003477 parseIntToken(
3478 SourceFileId,
3479 "expected SourceField in '.cv_inline_linetable' directive") ||
3480 check(SourceFileId <= 0, Loc,
3481 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003482 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003483 parseIntToken(
3484 SourceLineNum,
3485 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3486 check(SourceLineNum < 0, Loc,
3487 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003488 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3489 "expected identifier in directive") ||
3490 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3491 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003492 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003493
Nirav Davea645433c2016-07-18 15:24:03 +00003494 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3495 return true;
3496
3497 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3498 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003499 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3500 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003501 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003502 return false;
3503}
3504
David Majnemer408b5e62016-02-05 01:55:49 +00003505/// parseDirectiveCVDefRange
3506/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3507bool AsmParser::parseDirectiveCVDefRange() {
3508 SMLoc Loc;
3509 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3510 while (getLexer().is(AsmToken::Identifier)) {
3511 Loc = getLexer().getLoc();
3512 StringRef GapStartName;
3513 if (parseIdentifier(GapStartName))
3514 return Error(Loc, "expected identifier in directive");
3515 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3516
3517 Loc = getLexer().getLoc();
3518 StringRef GapEndName;
3519 if (parseIdentifier(GapEndName))
3520 return Error(Loc, "expected identifier in directive");
3521 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3522
3523 Ranges.push_back({GapStartSym, GapEndSym});
3524 }
3525
David Majnemer408b5e62016-02-05 01:55:49 +00003526 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003527 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3528 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003529 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003530
3531 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3532 return false;
3533}
3534
Reid Kleckner2214ed82016-01-29 00:49:42 +00003535/// parseDirectiveCVStringTable
3536/// ::= .cv_stringtable
3537bool AsmParser::parseDirectiveCVStringTable() {
3538 getStreamer().EmitCVStringTableDirective();
3539 return false;
3540}
3541
3542/// parseDirectiveCVFileChecksums
3543/// ::= .cv_filechecksums
3544bool AsmParser::parseDirectiveCVFileChecksums() {
3545 getStreamer().EmitCVFileChecksumsDirective();
3546 return false;
3547}
3548
Jim Grosbach4b905842013-09-20 23:08:21 +00003549/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003550/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003551bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003552 StringRef Name;
3553 bool EH = false;
3554 bool Debug = false;
3555
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003556 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003557 return TokError("Expected an identifier");
3558
3559 if (Name == ".eh_frame")
3560 EH = true;
3561 else if (Name == ".debug_frame")
3562 Debug = true;
3563
3564 if (getLexer().is(AsmToken::Comma)) {
3565 Lex();
3566
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003567 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003568 return TokError("Expected an identifier");
3569
3570 if (Name == ".eh_frame")
3571 EH = true;
3572 else if (Name == ".debug_frame")
3573 Debug = true;
3574 }
3575
3576 getStreamer().EmitCFISections(EH, Debug);
3577 return false;
3578}
3579
Jim Grosbach4b905842013-09-20 23:08:21 +00003580/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003581/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003582bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003583 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003584 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3585 if (check(parseIdentifier(Simple) || Simple != "simple",
3586 "unexpected token") ||
3587 parseToken(AsmToken::EndOfStatement))
3588 return addErrorSuffix(" in '.cfi_startproc' directive");
3589 }
Nirav Davea645433c2016-07-18 15:24:03 +00003590
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003591 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003592 return false;
3593}
3594
Jim Grosbach4b905842013-09-20 23:08:21 +00003595/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003596/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003597bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003598 getStreamer().EmitCFIEndProc();
3599 return false;
3600}
3601
Jim Grosbach4b905842013-09-20 23:08:21 +00003602/// \brief parse register name or number.
3603bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003604 SMLoc DirectiveLoc) {
3605 unsigned RegNo;
3606
3607 if (getLexer().isNot(AsmToken::Integer)) {
3608 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3609 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003610 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003611 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003612 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003613
3614 return false;
3615}
3616
Jim Grosbach4b905842013-09-20 23:08:21 +00003617/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003618/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003619bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003620 int64_t Register = 0, Offset = 0;
3621 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3622 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3623 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003624 return true;
3625
3626 getStreamer().EmitCFIDefCfa(Register, Offset);
3627 return false;
3628}
3629
Jim Grosbach4b905842013-09-20 23:08:21 +00003630/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003631/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003632bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003633 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003634 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003635 return true;
3636
3637 getStreamer().EmitCFIDefCfaOffset(Offset);
3638 return false;
3639}
3640
Jim Grosbach4b905842013-09-20 23:08:21 +00003641/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003642/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003643bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003644 int64_t Register1 = 0, Register2 = 0;
3645 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3646 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3647 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003648 return true;
3649
3650 getStreamer().EmitCFIRegister(Register1, Register2);
3651 return false;
3652}
3653
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003654/// parseDirectiveCFIWindowSave
3655/// ::= .cfi_window_save
3656bool AsmParser::parseDirectiveCFIWindowSave() {
3657 getStreamer().EmitCFIWindowSave();
3658 return false;
3659}
3660
Jim Grosbach4b905842013-09-20 23:08:21 +00003661/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003662/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003663bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003664 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003665 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003666 return true;
3667
3668 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3669 return false;
3670}
3671
Jim Grosbach4b905842013-09-20 23:08:21 +00003672/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003673/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003674bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003675 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003676 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003677 return true;
3678
3679 getStreamer().EmitCFIDefCfaRegister(Register);
3680 return false;
3681}
3682
Jim Grosbach4b905842013-09-20 23:08:21 +00003683/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003684/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003685bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003686 int64_t Register = 0;
3687 int64_t Offset = 0;
3688
Nirav Davea645433c2016-07-18 15:24:03 +00003689 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3690 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3691 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003692 return true;
3693
3694 getStreamer().EmitCFIOffset(Register, Offset);
3695 return false;
3696}
3697
Jim Grosbach4b905842013-09-20 23:08:21 +00003698/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003699/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003700bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003701 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003702
Nirav Davea645433c2016-07-18 15:24:03 +00003703 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3704 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3705 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003706 return true;
3707
3708 getStreamer().EmitCFIRelOffset(Register, Offset);
3709 return false;
3710}
3711
3712static bool isValidEncoding(int64_t Encoding) {
3713 if (Encoding & ~0xff)
3714 return false;
3715
3716 if (Encoding == dwarf::DW_EH_PE_omit)
3717 return true;
3718
3719 const unsigned Format = Encoding & 0xf;
3720 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3721 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3722 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3723 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3724 return false;
3725
3726 const unsigned Application = Encoding & 0x70;
3727 if (Application != dwarf::DW_EH_PE_absptr &&
3728 Application != dwarf::DW_EH_PE_pcrel)
3729 return false;
3730
3731 return true;
3732}
3733
Jim Grosbach4b905842013-09-20 23:08:21 +00003734/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003735/// IsPersonality true for cfi_personality, false for cfi_lsda
3736/// ::= .cfi_personality encoding, [symbol_name]
3737/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003738bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003739 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003740 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003741 return true;
3742 if (Encoding == dwarf::DW_EH_PE_omit)
3743 return false;
3744
Eli Bendersky17233942013-01-15 22:59:42 +00003745 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003746 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3747 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3748 check(parseIdentifier(Name), "expected identifier in directive"))
3749 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003750
Jim Grosbach6f482002015-05-18 18:43:14 +00003751 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003752
3753 if (IsPersonality)
3754 getStreamer().EmitCFIPersonality(Sym, Encoding);
3755 else
3756 getStreamer().EmitCFILsda(Sym, Encoding);
3757 return false;
3758}
3759
Jim Grosbach4b905842013-09-20 23:08:21 +00003760/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003761/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003762bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003763 getStreamer().EmitCFIRememberState();
3764 return false;
3765}
3766
Jim Grosbach4b905842013-09-20 23:08:21 +00003767/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003768/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003769bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003770 getStreamer().EmitCFIRestoreState();
3771 return false;
3772}
3773
Jim Grosbach4b905842013-09-20 23:08:21 +00003774/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003775/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003776bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003777 int64_t Register = 0;
3778
Jim Grosbach4b905842013-09-20 23:08:21 +00003779 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003780 return true;
3781
3782 getStreamer().EmitCFISameValue(Register);
3783 return false;
3784}
3785
Jim Grosbach4b905842013-09-20 23:08:21 +00003786/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003787/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003788bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003789 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003790 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003791 return true;
3792
3793 getStreamer().EmitCFIRestore(Register);
3794 return false;
3795}
3796
Jim Grosbach4b905842013-09-20 23:08:21 +00003797/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003798/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003799bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003800 std::string Values;
3801 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003802 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003803 return true;
3804
3805 Values.push_back((uint8_t)CurrValue);
3806
3807 while (getLexer().is(AsmToken::Comma)) {
3808 Lex();
3809
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003810 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003811 return true;
3812
3813 Values.push_back((uint8_t)CurrValue);
3814 }
3815
3816 getStreamer().EmitCFIEscape(Values);
3817 return false;
3818}
3819
Jim Grosbach4b905842013-09-20 23:08:21 +00003820/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003821/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003822bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003823 if (parseToken(AsmToken::EndOfStatement,
3824 "unexpected token in '.cfi_signal_frame'"))
3825 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003826
3827 getStreamer().EmitCFISignalFrame();
3828 return false;
3829}
3830
Jim Grosbach4b905842013-09-20 23:08:21 +00003831/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003832/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003833bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003834 int64_t Register = 0;
3835
Jim Grosbach4b905842013-09-20 23:08:21 +00003836 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003837 return true;
3838
3839 getStreamer().EmitCFIUndefined(Register);
3840 return false;
3841}
3842
Jim Grosbach4b905842013-09-20 23:08:21 +00003843/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003844/// ::= .macros_on
3845/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003846bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003847 if (parseToken(AsmToken::EndOfStatement,
3848 "unexpected token in '" + Directive + "' directive"))
3849 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003850
Jim Grosbach4b905842013-09-20 23:08:21 +00003851 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003852 return false;
3853}
3854
Jim Grosbach4b905842013-09-20 23:08:21 +00003855/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003856/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003857bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003858 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003859 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003860 return TokError("expected identifier in '.macro' directive");
3861
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003862 if (getLexer().is(AsmToken::Comma))
3863 Lex();
3864
Eli Bendersky17233942013-01-15 22:59:42 +00003865 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003866 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003867
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003868 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003869 return Error(Lexer.getLoc(),
3870 "Vararg parameter '" + Parameters.back().Name +
3871 "' should be last one in the list of parameters.");
3872
David Majnemer91fc4c22014-01-29 18:57:46 +00003873 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003874 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003875 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003876
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003877 if (Lexer.is(AsmToken::Colon)) {
3878 Lex(); // consume ':'
3879
3880 SMLoc QualLoc;
3881 StringRef Qualifier;
3882
3883 QualLoc = Lexer.getLoc();
3884 if (parseIdentifier(Qualifier))
3885 return Error(QualLoc, "missing parameter qualifier for "
3886 "'" + Parameter.Name + "' in macro '" + Name + "'");
3887
3888 if (Qualifier == "req")
3889 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003890 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003891 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003892 else
3893 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3894 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3895 }
3896
David Majnemer91fc4c22014-01-29 18:57:46 +00003897 if (getLexer().is(AsmToken::Equal)) {
3898 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003899
3900 SMLoc ParamLoc;
3901
3902 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003903 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003904 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003905
3906 if (Parameter.Required)
3907 Warning(ParamLoc, "pointless default value for required parameter "
3908 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003909 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003910
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003911 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003912
3913 if (getLexer().is(AsmToken::Comma))
3914 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003915 }
3916
Nirav Dave1180e6892016-06-02 17:15:05 +00003917 // Eat just the end of statement.
3918 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003919
Nirav Dave1180e6892016-06-02 17:15:05 +00003920 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003921 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003922 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003923 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003924 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003925 // Ignore Lexing errors in macros.
3926 while (Lexer.is(AsmToken::Error)) {
3927 Lexer.Lex();
3928 }
3929
Eli Bendersky17233942013-01-15 22:59:42 +00003930 // Check whether we have reached the end of the file.
3931 if (getLexer().is(AsmToken::Eof))
3932 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3933
3934 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003935 if (getLexer().is(AsmToken::Identifier)) {
3936 if (getTok().getIdentifier() == ".endm" ||
3937 getTok().getIdentifier() == ".endmacro") {
3938 if (MacroDepth == 0) { // Outermost macro.
3939 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003940 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003941 if (getLexer().isNot(AsmToken::EndOfStatement))
3942 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3943 "' directive");
3944 break;
3945 } else {
3946 // Otherwise we just found the end of an inner macro.
3947 --MacroDepth;
3948 }
3949 } else if (getTok().getIdentifier() == ".macro") {
3950 // We allow nested macros. Those aren't instantiated until the outermost
3951 // macro is expanded so just ignore them for now.
3952 ++MacroDepth;
3953 }
Eli Bendersky17233942013-01-15 22:59:42 +00003954 }
3955
3956 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003957 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003958 }
3959
Jim Grosbach4b905842013-09-20 23:08:21 +00003960 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003961 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3962 }
3963
3964 const char *BodyStart = StartToken.getLoc().getPointer();
3965 const char *BodyEnd = EndToken.getLoc().getPointer();
3966 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003967 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003968 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003969 return false;
3970}
3971
Jim Grosbach4b905842013-09-20 23:08:21 +00003972/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003973///
3974/// With the support added for named parameters there may be code out there that
3975/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003976/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003977/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003978/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003979/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3980/// warning that the positional parameter found in body which have no effect.
3981/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003982/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003983/// intended or change the macro to use the named parameters. It is possible
3984/// this warning will trigger when the none of the named parameters are used
3985/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003986void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003987 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003988 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003989 // If this macro is not defined with named parameters the warning we are
3990 // checking for here doesn't apply.
3991 unsigned NParameters = Parameters.size();
3992 if (NParameters == 0)
3993 return;
3994
3995 bool NamedParametersFound = false;
3996 bool PositionalParametersFound = false;
3997
3998 // Look at the body of the macro for use of both the named parameters and what
3999 // are likely to be positional parameters. This is what expandMacro() is
4000 // doing when it finds the parameters in the body.
4001 while (!Body.empty()) {
4002 // Scan for the next possible parameter.
4003 std::size_t End = Body.size(), Pos = 0;
4004 for (; Pos != End; ++Pos) {
4005 // Check for a substitution or escape.
4006 // This macro is defined with parameters, look for \foo, \bar, etc.
4007 if (Body[Pos] == '\\' && Pos + 1 != End)
4008 break;
4009
4010 // This macro should have parameters, but look for $0, $1, ..., $n too.
4011 if (Body[Pos] != '$' || Pos + 1 == End)
4012 continue;
4013 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004014 if (Next == '$' || Next == 'n' ||
4015 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004016 break;
4017 }
4018
4019 // Check if we reached the end.
4020 if (Pos == End)
4021 break;
4022
4023 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004024 switch (Body[Pos + 1]) {
4025 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004026 case '$':
4027 break;
4028
Jim Grosbach4b905842013-09-20 23:08:21 +00004029 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004030 case 'n':
4031 PositionalParametersFound = true;
4032 break;
4033
Jim Grosbach4b905842013-09-20 23:08:21 +00004034 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004035 default: {
4036 PositionalParametersFound = true;
4037 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004038 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004039 }
4040 Pos += 2;
4041 } else {
4042 unsigned I = Pos + 1;
4043 while (isIdentifierChar(Body[I]) && I + 1 != End)
4044 ++I;
4045
Jim Grosbach4b905842013-09-20 23:08:21 +00004046 const char *Begin = Body.data() + Pos + 1;
4047 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004048 unsigned Index = 0;
4049 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004050 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004051 break;
4052
4053 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004054 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4055 Pos += 3;
4056 else {
4057 Pos = I;
4058 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004059 } else {
4060 NamedParametersFound = true;
4061 Pos += 1 + Argument.size();
4062 }
4063 }
4064 // Update the scan point.
4065 Body = Body.substr(Pos);
4066 }
4067
4068 if (!NamedParametersFound && PositionalParametersFound)
4069 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4070 "used in macro body, possible positional parameter "
4071 "found in body which will have no effect");
4072}
4073
Nico Weber155dccd12014-07-24 17:08:39 +00004074/// parseDirectiveExitMacro
4075/// ::= .exitm
4076bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004077 if (parseToken(AsmToken::EndOfStatement,
4078 "unexpected token in '" + Directive + "' directive"))
4079 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004080
4081 if (!isInsideMacroInstantiation())
4082 return TokError("unexpected '" + Directive + "' in file, "
4083 "no current macro definition");
4084
4085 // Exit all conditionals that are active in the current macro.
4086 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4087 TheCondState = TheCondStack.back();
4088 TheCondStack.pop_back();
4089 }
4090
4091 handleMacroExit();
4092 return false;
4093}
4094
Jim Grosbach4b905842013-09-20 23:08:21 +00004095/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004096/// ::= .endm
4097/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004098bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004099 if (getLexer().isNot(AsmToken::EndOfStatement))
4100 return TokError("unexpected token in '" + Directive + "' directive");
4101
4102 // If we are inside a macro instantiation, terminate the current
4103 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004104 if (isInsideMacroInstantiation()) {
4105 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004106 return false;
4107 }
4108
4109 // Otherwise, this .endmacro is a stray entry in the file; well formed
4110 // .endmacro directives are handled during the macro definition parsing.
4111 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004112 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004113}
4114
Jim Grosbach4b905842013-09-20 23:08:21 +00004115/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004116/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004117bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004118 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004119 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004120 if (parseTokenLoc(Loc) ||
4121 check(parseIdentifier(Name), Loc,
4122 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004123 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004124 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004125 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004126
Nirav Dave1ab71992016-07-18 19:35:21 +00004127 if (!lookupMacro(Name))
4128 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4129
Jim Grosbach4b905842013-09-20 23:08:21 +00004130 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004131 return false;
4132}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004133
Jim Grosbach4b905842013-09-20 23:08:21 +00004134/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004135/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004136bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004137 // Expect a single argument: an expression that evaluates to a constant
4138 // in the inclusive range 0-30.
4139 SMLoc ExprLoc = getLexer().getLoc();
4140 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004141 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004142 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4143 "in '.bundle_align_mode' "
4144 "directive") ||
4145 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4146 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004147 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004148
4149 // Because of AlignSizePow2's verified range we can safely truncate it to
4150 // unsigned.
4151 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4152 return false;
4153}
4154
Jim Grosbach4b905842013-09-20 23:08:21 +00004155/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004156/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004157bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004158 if (checkForValidSection())
4159 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004160 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004161
Nirav Dave1a9044b2016-10-24 14:35:29 +00004162 StringRef Option;
4163 SMLoc Loc = getTok().getLoc();
4164 const char *kInvalidOptionError =
4165 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004166
Nirav Dave1a9044b2016-10-24 14:35:29 +00004167 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004168 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4169 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004170 parseToken(AsmToken::EndOfStatement,
4171 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004172 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004173 AlignToEnd = true;
4174 }
4175
Eli Bendersky802b6282013-01-07 21:51:08 +00004176 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004177 return false;
4178}
4179
Jim Grosbach4b905842013-09-20 23:08:21 +00004180/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004181/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004182bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004183 if (checkForValidSection() ||
4184 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004185 "unexpected token in '.bundle_unlock' directive"))
4186 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004187
4188 getStreamer().EmitBundleUnlock();
4189 return false;
4190}
4191
Jim Grosbach4b905842013-09-20 23:08:21 +00004192/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004193/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004194bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004195 SMLoc NumBytesLoc = Lexer.getLoc();
4196 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004197 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004198 return true;
4199
4200 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004201 if (parseOptionalToken(AsmToken::Comma))
4202 if (parseAbsoluteExpression(FillExpr))
4203 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4204 if (parseToken(AsmToken::EndOfStatement))
4205 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004206
Eli Bendersky17233942013-01-15 22:59:42 +00004207 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004208 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004209
4210 return false;
4211}
4212
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004213/// parseDirectiveDCB
4214/// ::= .dcb.{b, l, w} expression, expression
4215bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004216 SMLoc NumValuesLoc = Lexer.getLoc();
4217 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004218 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004219 return true;
4220
4221 if (NumValues < 0) {
4222 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4223 return false;
4224 }
4225
4226 if (parseToken(AsmToken::Comma,
4227 "unexpected token in '" + Twine(IDVal) + "' directive"))
4228 return true;
4229
4230 const MCExpr *Value;
4231 SMLoc ExprLoc = getLexer().getLoc();
4232 if (parseExpression(Value))
4233 return true;
4234
4235 // Special case constant expressions to match code generator.
4236 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4237 assert(Size <= 8 && "Invalid size");
4238 uint64_t IntValue = MCE->getValue();
4239 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4240 return Error(ExprLoc, "literal value out of range for directive");
4241 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4242 getStreamer().EmitIntValue(IntValue, Size);
4243 } else {
4244 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4245 getStreamer().EmitValue(Value, Size, ExprLoc);
4246 }
4247
4248 if (parseToken(AsmToken::EndOfStatement,
4249 "unexpected token in '" + Twine(IDVal) + "' directive"))
4250 return true;
4251
4252 return false;
4253}
4254
4255/// parseDirectiveRealDCB
4256/// ::= .dcb.{d, s} expression, expression
4257bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004258 SMLoc NumValuesLoc = Lexer.getLoc();
4259 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004260 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004261 return true;
4262
4263 if (NumValues < 0) {
4264 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4265 return false;
4266 }
4267
4268 if (parseToken(AsmToken::Comma,
4269 "unexpected token in '" + Twine(IDVal) + "' directive"))
4270 return true;
4271
4272 APInt AsInt;
4273 if (parseRealValue(Semantics, AsInt))
4274 return true;
4275
4276 if (parseToken(AsmToken::EndOfStatement,
4277 "unexpected token in '" + Twine(IDVal) + "' directive"))
4278 return true;
4279
4280 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4281 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4282 AsInt.getBitWidth() / 8);
4283
4284 return false;
4285}
4286
Petr Hosek85b2f672016-09-23 21:53:36 +00004287/// parseDirectiveDS
4288/// ::= .ds.{b, d, l, p, s, w, x} expression
4289bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004290 SMLoc NumValuesLoc = Lexer.getLoc();
4291 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004292 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004293 return true;
4294
4295 if (NumValues < 0) {
4296 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4297 return false;
4298 }
4299
4300 if (parseToken(AsmToken::EndOfStatement,
4301 "unexpected token in '" + Twine(IDVal) + "' directive"))
4302 return true;
4303
4304 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4305 getStreamer().emitFill(Size, 0);
4306
4307 return false;
4308}
4309
Jim Grosbach4b905842013-09-20 23:08:21 +00004310/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004311/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004312bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004313 if (checkForValidSection())
4314 return true;
4315
Nirav Dave1a9044b2016-10-24 14:35:29 +00004316 auto parseOp = [&]() -> bool {
4317 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004318 if (parseExpression(Value))
4319 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004320 if (Signed)
4321 getStreamer().EmitSLEB128Value(Value);
4322 else
4323 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004324 return false;
4325 };
Eli Bendersky17233942013-01-15 22:59:42 +00004326
Nirav Dave1a9044b2016-10-24 14:35:29 +00004327 if (parseMany(parseOp))
4328 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004329
4330 return false;
4331}
4332
Jim Grosbach4b905842013-09-20 23:08:21 +00004333/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004334/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004335bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004336 auto parseOp = [&]() -> bool {
4337 StringRef Name;
4338 SMLoc Loc = getTok().getLoc();
4339 if (parseIdentifier(Name))
4340 return Error(Loc, "expected identifier");
4341 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004342
Nirav Dave1a9044b2016-10-24 14:35:29 +00004343 // Assembler local symbols don't make any sense here. Complain loudly.
4344 if (Sym->isTemporary())
4345 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004346
Nirav Dave1a9044b2016-10-24 14:35:29 +00004347 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4348 return Error(Loc, "unable to emit symbol attribute");
4349 return false;
4350 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004351
Nirav Dave1a9044b2016-10-24 14:35:29 +00004352 if (parseMany(parseOp))
4353 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004354 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004355}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004356
Jim Grosbach4b905842013-09-20 23:08:21 +00004357/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004358/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004359bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004360 if (checkForValidSection())
4361 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004362
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004363 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004364 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004365 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004366 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004367
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004368 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004369 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004370
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004371 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004372 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004373 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004374
4375 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004376 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004377 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004378 return true;
4379
4380 int64_t Pow2Alignment = 0;
4381 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004382 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004383 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004384 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004385 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004386 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004387
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004388 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4389 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004390 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4391
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004392 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004393 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4394 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004395 if (!isPowerOf2_64(Pow2Alignment))
4396 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4397 Pow2Alignment = Log2_64(Pow2Alignment);
4398 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004399 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004400
Nirav Dave1a9044b2016-10-24 14:35:29 +00004401 if (parseToken(AsmToken::EndOfStatement,
4402 "unexpected token in '.comm' or '.lcomm' directive"))
4403 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004404
Chris Lattner28ad7542009-07-09 17:25:12 +00004405 // NOTE: a size of zero for a .comm should create a undefined symbol
4406 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004407 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004408 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004409 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004410
Eric Christopherbc818852010-05-14 01:38:54 +00004411 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004412 // may internally end up wanting an alignment in bytes.
4413 // FIXME: Diagnose overflow.
4414 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004415 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004416 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004417
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004418 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004419 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004420 return Error(IDLoc, "invalid symbol redefinition");
4421
Chris Lattner28ad7542009-07-09 17:25:12 +00004422 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004423 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004424 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004425 return false;
4426 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004427
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004428 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004429 return false;
4430}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004431
Jim Grosbach4b905842013-09-20 23:08:21 +00004432/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004433/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004434bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004435 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004436 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004437
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004438 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004439 if (parseToken(AsmToken::EndOfStatement,
4440 "unexpected token in '.abort' directive"))
4441 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004442
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004443 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004444 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004445 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004446 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004447 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004448
4449 return false;
4450}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004451
Jim Grosbach4b905842013-09-20 23:08:21 +00004452/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004453/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004454bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004455 // Allow the strings to have escaped octal character sequence.
4456 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004457 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004458
Nirav Davea645433c2016-07-18 15:24:03 +00004459 if (check(getTok().isNot(AsmToken::String),
4460 "expected string in '.include' directive") ||
4461 parseEscapedString(Filename) ||
4462 check(getTok().isNot(AsmToken::EndOfStatement),
4463 "unexpected token in '.include' directive") ||
4464 // Attempt to switch the lexer to the included file before consuming the
4465 // end of statement to avoid losing it when we switch.
4466 check(enterIncludeFile(Filename), IncludeLoc,
4467 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004468 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004469
4470 return false;
4471}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004472
Jim Grosbach4b905842013-09-20 23:08:21 +00004473/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004474/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004475bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004476 // Allow the strings to have escaped octal character sequence.
4477 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004478 SMLoc IncbinLoc = getTok().getLoc();
4479 if (check(getTok().isNot(AsmToken::String),
4480 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004481 parseEscapedString(Filename))
4482 return true;
4483
4484 int64_t Skip = 0;
4485 const MCExpr *Count = nullptr;
4486 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004487 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004488 // The skip expression can be omitted while specifying the count, e.g:
4489 // .incbin "filename",,4
4490 if (getTok().isNot(AsmToken::Comma)) {
4491 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4492 return true;
4493 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004494 if (parseOptionalToken(AsmToken::Comma)) {
4495 CountLoc = getTok().getLoc();
4496 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004497 return true;
4498 }
4499 }
4500
4501 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004502 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004503 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004504
Petr Hosek2f4ac442016-09-23 00:41:06 +00004505 if (check(Skip < 0, SkipLoc, "skip is negative"))
4506 return true;
4507
Nirav Dave1ab71992016-07-18 19:35:21 +00004508 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004509 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004510 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004511 return false;
4512}
4513
Jim Grosbach4b905842013-09-20 23:08:21 +00004514/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004515/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4516bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004517 TheCondStack.push_back(TheCondState);
4518 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004519 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004520 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004521 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004522 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004523 if (parseAbsoluteExpression(ExprValue) ||
4524 parseToken(AsmToken::EndOfStatement,
4525 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004526 return true;
4527
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004528 switch (DirKind) {
4529 default:
4530 llvm_unreachable("unsupported directive");
4531 case DK_IF:
4532 case DK_IFNE:
4533 break;
4534 case DK_IFEQ:
4535 ExprValue = ExprValue == 0;
4536 break;
4537 case DK_IFGE:
4538 ExprValue = ExprValue >= 0;
4539 break;
4540 case DK_IFGT:
4541 ExprValue = ExprValue > 0;
4542 break;
4543 case DK_IFLE:
4544 ExprValue = ExprValue <= 0;
4545 break;
4546 case DK_IFLT:
4547 ExprValue = ExprValue < 0;
4548 break;
4549 }
4550
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004551 TheCondState.CondMet = ExprValue;
4552 TheCondState.Ignore = !TheCondState.CondMet;
4553 }
4554
4555 return false;
4556}
4557
Jim Grosbach4b905842013-09-20 23:08:21 +00004558/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004559/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004560bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004561 TheCondStack.push_back(TheCondState);
4562 TheCondState.TheCond = AsmCond::IfCond;
4563
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004564 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004565 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004566 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004567 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004568
Nirav Davea645433c2016-07-18 15:24:03 +00004569 if (parseToken(AsmToken::EndOfStatement,
4570 "unexpected token in '.ifb' directive"))
4571 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004572
4573 TheCondState.CondMet = ExpectBlank == Str.empty();
4574 TheCondState.Ignore = !TheCondState.CondMet;
4575 }
4576
4577 return false;
4578}
4579
Jim Grosbach4b905842013-09-20 23:08:21 +00004580/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004581/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004582/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004583bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004584 TheCondStack.push_back(TheCondState);
4585 TheCondState.TheCond = AsmCond::IfCond;
4586
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004587 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004588 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004589 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004590 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004591
Nirav Davea645433c2016-07-18 15:24:03 +00004592 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4593 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004594
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004595 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004596
Nirav Davea645433c2016-07-18 15:24:03 +00004597 if (parseToken(AsmToken::EndOfStatement,
4598 "unexpected token in '.ifc' directive"))
4599 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004600
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004601 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004602 TheCondState.Ignore = !TheCondState.CondMet;
4603 }
4604
4605 return false;
4606}
4607
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004608/// parseDirectiveIfeqs
4609/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004610bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004611 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004612 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004613 return TokError("expected string parameter for '.ifeqs' directive");
4614 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004615 }
4616
4617 StringRef String1 = getTok().getStringContents();
4618 Lex();
4619
4620 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004621 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004622 return TokError(
4623 "expected comma after first string for '.ifeqs' directive");
4624 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004625 }
4626
4627 Lex();
4628
4629 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004630 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004631 return TokError("expected string parameter for '.ifeqs' directive");
4632 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004633 }
4634
4635 StringRef String2 = getTok().getStringContents();
4636 Lex();
4637
4638 TheCondStack.push_back(TheCondState);
4639 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004640 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004641 TheCondState.Ignore = !TheCondState.CondMet;
4642
4643 return false;
4644}
4645
Jim Grosbach4b905842013-09-20 23:08:21 +00004646/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004647/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004648bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004649 StringRef Name;
4650 TheCondStack.push_back(TheCondState);
4651 TheCondState.TheCond = AsmCond::IfCond;
4652
4653 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004654 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004655 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004656 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4657 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4658 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004659
Jim Grosbach6f482002015-05-18 18:43:14 +00004660 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004661
4662 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004663 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004664 else
Craig Topper353eda42014-04-24 06:44:33 +00004665 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004666 TheCondState.Ignore = !TheCondState.CondMet;
4667 }
4668
4669 return false;
4670}
4671
Jim Grosbach4b905842013-09-20 23:08:21 +00004672/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004673/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004674bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004675 if (TheCondState.TheCond != AsmCond::IfCond &&
4676 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004677 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4678 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004679 TheCondState.TheCond = AsmCond::ElseIfCond;
4680
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004681 bool LastIgnoreState = false;
4682 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004683 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004684 if (LastIgnoreState || TheCondState.CondMet) {
4685 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004686 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004687 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004688 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004689 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004690 return true;
4691
Nirav Dave1a9044b2016-10-24 14:35:29 +00004692 if (parseToken(AsmToken::EndOfStatement,
4693 "unexpected token in '.elseif' directive"))
4694 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004695
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004696 TheCondState.CondMet = ExprValue;
4697 TheCondState.Ignore = !TheCondState.CondMet;
4698 }
4699
4700 return false;
4701}
4702
Jim Grosbach4b905842013-09-20 23:08:21 +00004703/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004704/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004705bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004706 if (parseToken(AsmToken::EndOfStatement,
4707 "unexpected token in '.else' directive"))
4708 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004709
4710 if (TheCondState.TheCond != AsmCond::IfCond &&
4711 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004712 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4713 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004714 TheCondState.TheCond = AsmCond::ElseCond;
4715 bool LastIgnoreState = false;
4716 if (!TheCondStack.empty())
4717 LastIgnoreState = TheCondStack.back().Ignore;
4718 if (LastIgnoreState || TheCondState.CondMet)
4719 TheCondState.Ignore = true;
4720 else
4721 TheCondState.Ignore = false;
4722
4723 return false;
4724}
4725
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004726/// parseDirectiveEnd
4727/// ::= .end
4728bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004729 if (parseToken(AsmToken::EndOfStatement,
4730 "unexpected token in '.end' directive"))
4731 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004732
4733 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004734 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004735
4736 return false;
4737}
4738
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004739/// parseDirectiveError
4740/// ::= .err
4741/// ::= .error [string]
4742bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4743 if (!TheCondStack.empty()) {
4744 if (TheCondStack.back().Ignore) {
4745 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004746 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004747 }
4748 }
4749
4750 if (!WithMessage)
4751 return Error(L, ".err encountered");
4752
4753 StringRef Message = ".error directive invoked in source file";
4754 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004755 if (Lexer.isNot(AsmToken::String))
4756 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004757
4758 Message = getTok().getStringContents();
4759 Lex();
4760 }
4761
Nirav Dave2364748a2016-09-16 18:30:20 +00004762 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004763}
4764
Nico Weber404012b2014-07-24 16:26:06 +00004765/// parseDirectiveWarning
4766/// ::= .warning [string]
4767bool AsmParser::parseDirectiveWarning(SMLoc L) {
4768 if (!TheCondStack.empty()) {
4769 if (TheCondStack.back().Ignore) {
4770 eatToEndOfStatement();
4771 return false;
4772 }
4773 }
4774
4775 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00004776
4777 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004778 if (Lexer.isNot(AsmToken::String))
4779 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004780
4781 Message = getTok().getStringContents();
4782 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00004783 if (parseToken(AsmToken::EndOfStatement,
4784 "expected end of statement in '.warning' directive"))
4785 return true;
Nico Weber404012b2014-07-24 16:26:06 +00004786 }
4787
Nirav Dave2364748a2016-09-16 18:30:20 +00004788 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004789}
4790
Jim Grosbach4b905842013-09-20 23:08:21 +00004791/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004792/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004793bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004794 if (parseToken(AsmToken::EndOfStatement,
4795 "unexpected token in '.endif' directive"))
4796 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004797
Jim Grosbach4b905842013-09-20 23:08:21 +00004798 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004799 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4800 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004801 if (!TheCondStack.empty()) {
4802 TheCondState = TheCondStack.back();
4803 TheCondStack.pop_back();
4804 }
4805
4806 return false;
4807}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004808
Eli Bendersky17233942013-01-15 22:59:42 +00004809void AsmParser::initializeDirectiveKindMap() {
4810 DirectiveKindMap[".set"] = DK_SET;
4811 DirectiveKindMap[".equ"] = DK_EQU;
4812 DirectiveKindMap[".equiv"] = DK_EQUIV;
4813 DirectiveKindMap[".ascii"] = DK_ASCII;
4814 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4815 DirectiveKindMap[".string"] = DK_STRING;
4816 DirectiveKindMap[".byte"] = DK_BYTE;
4817 DirectiveKindMap[".short"] = DK_SHORT;
4818 DirectiveKindMap[".value"] = DK_VALUE;
4819 DirectiveKindMap[".2byte"] = DK_2BYTE;
4820 DirectiveKindMap[".long"] = DK_LONG;
4821 DirectiveKindMap[".int"] = DK_INT;
4822 DirectiveKindMap[".4byte"] = DK_4BYTE;
4823 DirectiveKindMap[".quad"] = DK_QUAD;
4824 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004825 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004826 DirectiveKindMap[".single"] = DK_SINGLE;
4827 DirectiveKindMap[".float"] = DK_FLOAT;
4828 DirectiveKindMap[".double"] = DK_DOUBLE;
4829 DirectiveKindMap[".align"] = DK_ALIGN;
4830 DirectiveKindMap[".align32"] = DK_ALIGN32;
4831 DirectiveKindMap[".balign"] = DK_BALIGN;
4832 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4833 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4834 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4835 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4836 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4837 DirectiveKindMap[".org"] = DK_ORG;
4838 DirectiveKindMap[".fill"] = DK_FILL;
4839 DirectiveKindMap[".zero"] = DK_ZERO;
4840 DirectiveKindMap[".extern"] = DK_EXTERN;
4841 DirectiveKindMap[".globl"] = DK_GLOBL;
4842 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004843 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4844 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4845 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4846 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4847 DirectiveKindMap[".reference"] = DK_REFERENCE;
4848 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4849 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4850 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4851 DirectiveKindMap[".comm"] = DK_COMM;
4852 DirectiveKindMap[".common"] = DK_COMMON;
4853 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4854 DirectiveKindMap[".abort"] = DK_ABORT;
4855 DirectiveKindMap[".include"] = DK_INCLUDE;
4856 DirectiveKindMap[".incbin"] = DK_INCBIN;
4857 DirectiveKindMap[".code16"] = DK_CODE16;
4858 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4859 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004860 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004861 DirectiveKindMap[".irp"] = DK_IRP;
4862 DirectiveKindMap[".irpc"] = DK_IRPC;
4863 DirectiveKindMap[".endr"] = DK_ENDR;
4864 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4865 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4866 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4867 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004868 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4869 DirectiveKindMap[".ifge"] = DK_IFGE;
4870 DirectiveKindMap[".ifgt"] = DK_IFGT;
4871 DirectiveKindMap[".ifle"] = DK_IFLE;
4872 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004873 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004874 DirectiveKindMap[".ifb"] = DK_IFB;
4875 DirectiveKindMap[".ifnb"] = DK_IFNB;
4876 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004877 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004878 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004879 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004880 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4881 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4882 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4883 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4884 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004885 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004886 DirectiveKindMap[".endif"] = DK_ENDIF;
4887 DirectiveKindMap[".skip"] = DK_SKIP;
4888 DirectiveKindMap[".space"] = DK_SPACE;
4889 DirectiveKindMap[".file"] = DK_FILE;
4890 DirectiveKindMap[".line"] = DK_LINE;
4891 DirectiveKindMap[".loc"] = DK_LOC;
4892 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004893 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004894 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004895 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4896 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004897 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004898 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00004899 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004900 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4901 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004902 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4903 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4904 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4905 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4906 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4907 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4908 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4909 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4910 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4911 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4912 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4913 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4914 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4915 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4916 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4917 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4918 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4919 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4920 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4921 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4922 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004923 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004924 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4925 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4926 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004927 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004928 DirectiveKindMap[".endm"] = DK_ENDM;
4929 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4930 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004931 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004932 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004933 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004934 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00004935 DirectiveKindMap[".dc"] = DK_DC;
4936 DirectiveKindMap[".dc.a"] = DK_DC_A;
4937 DirectiveKindMap[".dc.b"] = DK_DC_B;
4938 DirectiveKindMap[".dc.d"] = DK_DC_D;
4939 DirectiveKindMap[".dc.l"] = DK_DC_L;
4940 DirectiveKindMap[".dc.s"] = DK_DC_S;
4941 DirectiveKindMap[".dc.w"] = DK_DC_W;
4942 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004943 DirectiveKindMap[".dcb"] = DK_DCB;
4944 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4945 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4946 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4947 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4948 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4949 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00004950 DirectiveKindMap[".ds"] = DK_DS;
4951 DirectiveKindMap[".ds.b"] = DK_DS_B;
4952 DirectiveKindMap[".ds.d"] = DK_DS_D;
4953 DirectiveKindMap[".ds.l"] = DK_DS_L;
4954 DirectiveKindMap[".ds.p"] = DK_DS_P;
4955 DirectiveKindMap[".ds.s"] = DK_DS_S;
4956 DirectiveKindMap[".ds.w"] = DK_DS_W;
4957 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004958}
4959
Jim Grosbach4b905842013-09-20 23:08:21 +00004960MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004961 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004962
Rafael Espindola34b9c512012-06-03 23:57:14 +00004963 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004964 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004965 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004966 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004967 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004968 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004969 }
4970
Rafael Espindola34b9c512012-06-03 23:57:14 +00004971 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004972 (getTok().getIdentifier() == ".rept" ||
4973 getTok().getIdentifier() == ".irp" ||
4974 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004975 ++NestLevel;
4976 }
4977
4978 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004979 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004980 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004981 EndToken = getTok();
4982 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004983 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004984 printError(getTok().getLoc(),
4985 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004986 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004987 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004988 break;
4989 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004990 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004991 }
4992
Rafael Espindola34b9c512012-06-03 23:57:14 +00004993 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004994 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004995 }
4996
4997 const char *BodyStart = StartToken.getLoc().getPointer();
4998 const char *BodyEnd = EndToken.getLoc().getPointer();
4999 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5000
Rafael Espindola34b9c512012-06-03 23:57:14 +00005001 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005002 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005003 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005004}
5005
Jim Grosbach4b905842013-09-20 23:08:21 +00005006void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005007 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005008 OS << ".endr\n";
5009
Rafael Espindola3560ff22014-08-27 20:03:13 +00005010 std::unique_ptr<MemoryBuffer> Instantiation =
5011 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005012
Rafael Espindola34b9c512012-06-03 23:57:14 +00005013 // Create the macro instantiation object and add to the current macro
5014 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005015 MacroInstantiation *MI = new MacroInstantiation(
5016 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005017 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005018
Rafael Espindola34b9c512012-06-03 23:57:14 +00005019 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005020 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005021 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005022 Lex();
5023}
5024
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005025/// parseDirectiveRept
5026/// ::= .rep | .rept count
5027bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005028 const MCExpr *CountExpr;
5029 SMLoc CountLoc = getTok().getLoc();
5030 if (parseExpression(CountExpr))
5031 return true;
5032
Rafael Espindola34b9c512012-06-03 23:57:14 +00005033 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005034 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005035 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5036 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005037
Nirav Davea645433c2016-07-18 15:24:03 +00005038 if (check(Count < 0, CountLoc, "Count is negative") ||
5039 parseToken(AsmToken::EndOfStatement,
5040 "unexpected token in '" + Dir + "' directive"))
5041 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005042
5043 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005044 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005045 if (!M)
5046 return true;
5047
5048 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5049 // to hold the macro body with substitutions.
5050 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005051 raw_svector_ostream OS(Buf);
5052 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005053 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5054 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005055 return true;
5056 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005057 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005058
5059 return false;
5060}
5061
Jim Grosbach4b905842013-09-20 23:08:21 +00005062/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005063/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005064bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005065 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005066 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005067 if (check(parseIdentifier(Parameter.Name),
5068 "expected identifier in '.irp' directive") ||
5069 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5070 parseMacroArguments(nullptr, A) ||
5071 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005072 return true;
5073
Rafael Espindola768b41c2012-06-15 14:02:34 +00005074 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005075 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005076 if (!M)
5077 return true;
5078
5079 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5080 // to hold the macro body with substitutions.
5081 SmallString<256> Buf;
5082 raw_svector_ostream OS(Buf);
5083
Craig Topper84008482015-10-10 05:38:14 +00005084 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005085 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5086 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005087 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005088 return true;
5089 }
5090
Jim Grosbach4b905842013-09-20 23:08:21 +00005091 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005092
5093 return false;
5094}
5095
Jim Grosbach4b905842013-09-20 23:08:21 +00005096/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005097/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005098bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005099 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005100 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005101
5102 if (check(parseIdentifier(Parameter.Name),
5103 "expected identifier in '.irpc' directive") ||
5104 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5105 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005106 return true;
5107
5108 if (A.size() != 1 || A.front().size() != 1)
5109 return TokError("unexpected token in '.irpc' directive");
5110
5111 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005112 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5113 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005114
5115 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005116 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005117 if (!M)
5118 return true;
5119
5120 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5121 // to hold the macro body with substitutions.
5122 SmallString<256> Buf;
5123 raw_svector_ostream OS(Buf);
5124
5125 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005126 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005127 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005128 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005129
Toma Tabacu217116e2015-04-27 10:50:29 +00005130 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5131 // This is undocumented, but GAS seems to support it.
5132 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005133 return true;
5134 }
5135
Jim Grosbach4b905842013-09-20 23:08:21 +00005136 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005137
5138 return false;
5139}
5140
Jim Grosbach4b905842013-09-20 23:08:21 +00005141bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005142 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005143 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005144
5145 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005146 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005147 assert(getLexer().is(AsmToken::EndOfStatement));
5148
Jim Grosbach4b905842013-09-20 23:08:21 +00005149 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005150 return false;
5151}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005152
Jim Grosbach4b905842013-09-20 23:08:21 +00005153bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005154 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005155 const MCExpr *Value;
5156 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005157 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005158 return true;
5159 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5160 if (!MCE)
5161 return Error(ExprLoc, "unexpected expression in _emit");
5162 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005163 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005164 return Error(ExprLoc, "literal value out of range for directive");
5165
Craig Topper7d5b2312015-10-10 05:25:02 +00005166 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005167 return false;
5168}
5169
Jim Grosbach4b905842013-09-20 23:08:21 +00005170bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005171 const MCExpr *Value;
5172 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005173 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005174 return true;
5175 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5176 if (!MCE)
5177 return Error(ExprLoc, "unexpected expression in align");
5178 uint64_t IntValue = MCE->getValue();
5179 if (!isPowerOf2_64(IntValue))
5180 return Error(ExprLoc, "literal value not a power of two greater then zero");
5181
Craig Topper7d5b2312015-10-10 05:25:02 +00005182 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005183 return false;
5184}
5185
Chad Rosierf43fcf52013-02-13 21:27:17 +00005186// We are comparing pointers, but the pointers are relative to a single string.
5187// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005188static int rewritesSort(const AsmRewrite *AsmRewriteA,
5189 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005190 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5191 return -1;
5192 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5193 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005194
Chad Rosierfce4fab2013-04-08 17:43:47 +00005195 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5196 // rewrite to the same location. Make sure the SizeDirective rewrite is
5197 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5198 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005199 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5200 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005201 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005202
Jim Grosbach4b905842013-09-20 23:08:21 +00005203 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5204 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005205 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005206 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005207}
5208
Jim Grosbach4b905842013-09-20 23:08:21 +00005209bool AsmParser::parseMSInlineAsm(
5210 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005211 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005212 SmallVectorImpl<std::string> &Constraints,
5213 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5214 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005215 SmallVector<void *, 4> InputDecls;
5216 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005217 SmallVector<bool, 4> InputDeclsAddressOf;
5218 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005219 SmallVector<std::string, 4> InputConstraints;
5220 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005221 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005222
Benjamin Kramer1a136112013-02-15 20:37:21 +00005223 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005224
5225 // Prime the lexer.
5226 Lex();
5227
5228 // While we have input, parse each statement.
5229 unsigned InputIdx = 0;
5230 unsigned OutputIdx = 0;
5231 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005232 // Parse curly braces marking block start/end
5233 if (parseCurlyBlockScope(AsmStrRewrites))
5234 continue;
5235
Eli Friedman0f4871d2012-10-22 23:58:19 +00005236 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005237 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005238
Nirav Dave2364748a2016-09-16 18:30:20 +00005239 if (StatementErr || Info.ParseError) {
5240 // Emit pending errors if any exist.
5241 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005242 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005243 }
5244
5245 // No pending error should exist here.
5246 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005247
Benjamin Kramer1a136112013-02-15 20:37:21 +00005248 if (Info.Opcode == ~0U)
5249 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005250
Benjamin Kramer1a136112013-02-15 20:37:21 +00005251 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005252
Benjamin Kramer1a136112013-02-15 20:37:21 +00005253 // Build the list of clobbers, outputs and inputs.
5254 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005255 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005256
Benjamin Kramer1a136112013-02-15 20:37:21 +00005257 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005258 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005259 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005260
Benjamin Kramer1a136112013-02-15 20:37:21 +00005261 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005262 if (Operand.isReg() && !Operand.needAddressOf() &&
5263 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005264 unsigned NumDefs = Desc.getNumDefs();
5265 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005266 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5267 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005268 continue;
5269 }
5270
5271 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005272 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005273 if (SymName.empty())
5274 continue;
5275
David Blaikie960ea3f2014-06-08 16:18:35 +00005276 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005277 if (!OpDecl)
5278 continue;
5279
5280 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005281 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005282 if (isOutput) {
5283 ++InputIdx;
5284 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005285 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005286 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005287 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005288 } else {
5289 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005290 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5291 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005292 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005293 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005294 }
Reid Kleckneree088972013-12-10 18:27:32 +00005295
5296 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005297 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5298 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005299 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005300 }
5301
5302 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005303 NumOutputs = OutputDecls.size();
5304 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005305
5306 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005307 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5308 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5309 ClobberRegs.end());
5310 Clobbers.assign(ClobberRegs.size(), std::string());
5311 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5312 raw_string_ostream OS(Clobbers[I]);
5313 IP->printRegName(OS, ClobberRegs[I]);
5314 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005315
5316 // Merge the various outputs and inputs. Output are expected first.
5317 if (NumOutputs || NumInputs) {
5318 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005319 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005320 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005321 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005322 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005323 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005324 }
5325 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005326 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005327 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005328 }
5329 }
5330
5331 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005332 std::string AsmStringIR;
5333 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005334 StringRef ASMString =
5335 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5336 const char *AsmStart = ASMString.begin();
5337 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005338 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005339 for (const AsmRewrite &AR : AsmStrRewrites) {
5340 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005341 if (Kind == AOK_Delete)
5342 continue;
5343
David Majnemer8114c1a2014-06-23 02:17:16 +00005344 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005345 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005346
Chad Rosier120eefd2013-03-19 17:32:17 +00005347 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005348 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005349 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005350
Chad Rosier37e755c2012-10-23 17:43:43 +00005351 // Skip the original expression.
5352 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005353 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005354 continue;
5355 }
5356
Chad Rosierff10ed12013-04-12 16:26:42 +00005357 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005358 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005359 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005360 default:
5361 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005362 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005363 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005364 break;
5365 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005366 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005367 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005368 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005369 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005370 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005371 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005372 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005373 break;
5374 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005375 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005376 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005377 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005378 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005379 default: break;
5380 case 8: OS << "byte ptr "; break;
5381 case 16: OS << "word ptr "; break;
5382 case 32: OS << "dword ptr "; break;
5383 case 64: OS << "qword ptr "; break;
5384 case 80: OS << "xword ptr "; break;
5385 case 128: OS << "xmmword ptr "; break;
5386 case 256: OS << "ymmword ptr "; break;
5387 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005388 break;
5389 case AOK_Emit:
5390 OS << ".byte";
5391 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005392 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005393 // MS alignment directives are measured in bytes. If the native assembler
5394 // measures alignment in bytes, we can pass it straight through.
5395 OS << ".align";
5396 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5397 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005398
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005399 // Alignment is in log2 form, so print that instead and skip the original
5400 // immediate.
5401 unsigned Val = AR.Val;
5402 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005403 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005404 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5405 break;
5406 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005407 case AOK_EVEN:
5408 OS << ".even";
5409 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005410 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005411 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005412 OS.flush();
5413 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005414 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005415 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005416 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005417 case AOK_EndOfStatement:
5418 OS << "\n\t";
5419 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005420 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005421
Chad Rosier8bce6642012-10-18 15:49:34 +00005422 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005423 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005424 }
5425
5426 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005427 if (AsmStart != AsmEnd)
5428 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005429
5430 AsmString = OS.str();
5431 return false;
5432}
5433
Pete Cooper80d21cb2015-06-22 19:35:57 +00005434namespace llvm {
5435namespace MCParserUtils {
5436
5437/// Returns whether the given symbol is used anywhere in the given expression,
5438/// or subexpressions.
5439static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5440 switch (Value->getKind()) {
5441 case MCExpr::Binary: {
5442 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5443 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5444 isSymbolUsedInExpression(Sym, BE->getRHS());
5445 }
5446 case MCExpr::Target:
5447 case MCExpr::Constant:
5448 return false;
5449 case MCExpr::SymbolRef: {
5450 const MCSymbol &S =
5451 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5452 if (S.isVariable())
5453 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5454 return &S == Sym;
5455 }
5456 case MCExpr::Unary:
5457 return isSymbolUsedInExpression(
5458 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5459 }
5460
5461 llvm_unreachable("Unknown expr kind!");
5462}
5463
5464bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5465 MCAsmParser &Parser, MCSymbol *&Sym,
5466 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005467
5468 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005469 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005470
5471 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005472 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005473 }
5474
5475 // Note: we don't count b as used in "a = b". This is to allow
5476 // a = b
5477 // b = c
5478
Nirav Dave1a9044b2016-10-24 14:35:29 +00005479 if (Parser.parseToken(AsmToken::EndOfStatement))
5480 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005481
5482 // Validate that the LHS is allowed to be a variable (either it has not been
5483 // used as a symbol, or it is an absolute symbol).
5484 Sym = Parser.getContext().lookupSymbol(Name);
5485 if (Sym) {
5486 // Diagnose assignment to a label.
5487 //
5488 // FIXME: Diagnostics. Note the location of the definition as a label.
5489 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5490 if (isSymbolUsedInExpression(Sym, Value))
5491 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005492 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5493 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005494 ; // Allow redefinitions of undefined symbols only used in directives.
5495 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5496 ; // Allow redefinitions of variables that haven't yet been used.
5497 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5498 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5499 else if (!Sym->isVariable())
5500 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5501 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5502 return Parser.Error(EqualLoc,
5503 "invalid reassignment of non-absolute variable '" +
5504 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005505 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005506 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005507 return false;
5508 } else
5509 Sym = Parser.getContext().getOrCreateSymbol(Name);
5510
5511 Sym->setRedefinable(allow_redef);
5512
5513 return false;
5514}
5515
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005516} // end namespace MCParserUtils
5517} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005518
Daniel Dunbar01e36072010-07-17 02:26:10 +00005519/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005520MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005521 MCStreamer &Out, const MCAsmInfo &MAI,
5522 unsigned CB) {
5523 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005524}