blob: 2fa9c03b608ea099fb6f6771d107db2e657565c3 [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
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000137 ParseStatementInfo() = delete;
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;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000740 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000741
Kevin Enderby6469fc22011-11-01 22:27:22 +0000742 // If we are generating dwarf for assembly source files save the initial text
743 // section and generate a .file directive.
744 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000745 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000746 if (!Sec->getBeginSymbol()) {
747 MCSymbol *SectionStartSym = getContext().createTempSymbol();
748 getStreamer().EmitLabel(SectionStartSym);
749 Sec->setBeginSymbol(SectionStartSym);
750 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000751 bool InsertResult = getContext().addGenDwarfSection(Sec);
752 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000753 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000754 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
755 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000756 }
757
Chris Lattner73f36112009-07-02 21:53:43 +0000758 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000759 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000760 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000761 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000762 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000763
Nirav Dave2364748a2016-09-16 18:30:20 +0000764 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
765 // for printing ErrMsg via Lex() only if no (presumably better) parser error
766 // exists.
767 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000768 Lex();
769 }
770
Nirav Dave2364748a2016-09-16 18:30:20 +0000771 // parseStatement returned true so may need to emit an error.
772 printPendingErrors();
773
774 // Skipping to the next line if needed.
775 if (!getLexer().isAtStartOfStatement())
776 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000777 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000778
Nirav Dave2364748a2016-09-16 18:30:20 +0000779 // All errors should have been emitted.
780 assert(!hasPendingError() && "unexpected error from parseStatement");
781
Oliver Stannard21718282016-07-26 14:19:47 +0000782 getTargetParser().flushPendingInstructions(getStreamer());
783
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000784 if (TheCondState.TheCond != StartingCondState.TheCond ||
785 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000786 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000787 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000788 const auto &LineTables = getContext().getMCDwarfLineTables();
789 if (!LineTables.empty()) {
790 unsigned Index = 0;
791 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
792 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000793 printError(getTok().getLoc(), "unassigned file number: " +
794 Twine(Index) +
795 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000796 ++Index;
797 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000798 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000799
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000800 // Check to see that all assembler local symbols were actually defined.
801 // Targets that don't do subsections via symbols may not want this, though,
802 // so conservatively exclude them. Only do this if we're finalizing, though,
803 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000804 if (!NoFinalize) {
805 if (MAI.hasSubsectionsViaSymbols()) {
806 for (const auto &TableEntry : getContext().getSymbols()) {
807 MCSymbol *Sym = TableEntry.getValue();
808 // Variable symbols may not be marked as defined, so check those
809 // explicitly. If we know it's a variable, we have a definition for
810 // the purposes of this check.
811 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
812 // FIXME: We would really like to refer back to where the symbol was
813 // first referenced for a source location. We need to add something
814 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000815 printError(getTok().getLoc(), "assembler local symbol '" +
816 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000817 }
818 }
819
820 // Temporary symbols like the ones for directional jumps don't go in the
821 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000822 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
823 if (std::get<2>(LocSym)->isUndefined()) {
824 // Reset the state of any "# line file" directives we've seen to the
825 // context as it was at the diagnostic site.
826 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000827 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000828 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000829 }
830 }
831
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000832 // Finalize the output stream if there are no errors and if the client wants
833 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000834 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000835 Out.Finish();
836
Oliver Stannard07b43d32015-11-17 09:58:07 +0000837 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000838}
839
Nirav Davef43cc9f2016-10-10 15:24:54 +0000840bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000841 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000842 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000843 return Error(getTok().getLoc(),
844 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000845 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000846 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000847}
848
Jim Grosbach4b905842013-09-20 23:08:21 +0000849/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000850void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000851 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000852 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000853
Chris Lattnere5074c42009-06-22 01:29:09 +0000854 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000855 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000856 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000857}
858
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000859StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000860 const char *Start = getTok().getLoc().getPointer();
861
Jim Grosbach4b905842013-09-20 23:08:21 +0000862 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000863 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000864
865 const char *End = getTok().getLoc().getPointer();
866 return StringRef(Start, End - Start);
867}
Chris Lattner78db3622009-06-22 05:51:26 +0000868
Jim Grosbach4b905842013-09-20 23:08:21 +0000869StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000870 const char *Start = getTok().getLoc().getPointer();
871
872 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000873 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000874 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000875
876 const char *End = getTok().getLoc().getPointer();
877 return StringRef(Start, End - Start);
878}
879
Jim Grosbach4b905842013-09-20 23:08:21 +0000880/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000881/// NOTE: This assumes the leading '(' has already been consumed.
882///
883/// parenexpr ::= expr)
884///
Jim Grosbach4b905842013-09-20 23:08:21 +0000885bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
886 if (parseExpression(Res))
887 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000888 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000889 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000890 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000891 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000892 return false;
893}
Chris Lattner78db3622009-06-22 05:51:26 +0000894
Jim Grosbach4b905842013-09-20 23:08:21 +0000895/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000896/// NOTE: This assumes the leading '[' has already been consumed.
897///
898/// bracketexpr ::= expr]
899///
Jim Grosbach4b905842013-09-20 23:08:21 +0000900bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
901 if (parseExpression(Res))
902 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000903 EndLoc = getTok().getEndLoc();
904 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
905 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000906 return false;
907}
908
Jim Grosbach4b905842013-09-20 23:08:21 +0000909/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000910/// primaryexpr ::= (parenexpr
911/// primaryexpr ::= symbol
912/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000913/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000914/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000915bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000916 SMLoc FirstTokenLoc = getLexer().getLoc();
917 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
918 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000919 default:
920 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000921 // If we have an error assume that we've already handled it.
922 case AsmToken::Error:
923 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000924 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000925 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000926 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000927 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +0000928 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000929 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000930 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000931 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000932 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000933 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000934 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000935 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +0000936 // We may have failed but $ may be a valid token.
937 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000938 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +0000939 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +0000940 // This is a '$' reference, which references the current PC. Emit a
941 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000942 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000943 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000944 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000945 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000946 EndLoc = FirstTokenLoc;
947 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000948 }
949 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000950 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000951 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000952 // Parse symbol variant
953 std::pair<StringRef, StringRef> Split;
954 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000955 if (FirstTokenKind == AsmToken::String) {
956 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000957 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000958 SMLoc AtLoc = getLexer().getLoc();
959 StringRef VName;
960 if (parseIdentifier(VName))
961 return Error(AtLoc, "expected symbol variant after '@'");
962
963 Split = std::make_pair(Identifier, VName);
964 }
965 } else {
966 Split = Identifier.split('@');
967 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000968 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000969 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000970 StringRef VName;
971 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000972 // eat ')'.
973 if (parseToken(AsmToken::RParen,
974 "unexpected token in variant, expected ')'"))
975 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000976 Split = std::make_pair(Identifier, VName);
977 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000978
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000979 EndLoc = SMLoc::getFromPointer(Identifier.end());
980
Daniel Dunbard20cda02009-10-16 01:34:54 +0000981 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000982 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +0000983 if (SymbolName.empty())
984 return true;
985
Hans Wennborgce69d772013-10-18 20:46:28 +0000986 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000987
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000988 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000989 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000990 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000991 if (Variant != MCSymbolRefExpr::VK_Invalid) {
992 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000993 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000994 Variant = MCSymbolRefExpr::VK_None;
995 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000996 return Error(SMLoc::getFromPointer(Split.second.begin()),
997 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000998 }
999 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001000
Jim Grosbach6f482002015-05-18 18:43:14 +00001001 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001002
Daniel Dunbard20cda02009-10-16 01:34:54 +00001003 // If this is an absolute variable reference, substitute it now to preserve
1004 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001005 if (Sym->isVariable() &&
1006 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001007 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001008 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001009
Vedant Kumar86dbd922015-08-31 17:44:53 +00001010 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001011 return false;
1012 }
1013
1014 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001015 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001016 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001017 }
David Woodhousef42a6662014-02-01 16:20:54 +00001018 case AsmToken::BigNum:
1019 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001020 case AsmToken::Integer: {
1021 SMLoc Loc = getTok().getLoc();
1022 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001023 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001024 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001025 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001026 // Look for 'b' or 'f' following an Integer as a directional label
1027 if (Lexer.getKind() == AsmToken::Identifier) {
1028 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001029 // Lookup the symbol variant if used.
1030 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1031 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1032 if (Split.first.size() != IDVal.size()) {
1033 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001034 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001035 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001036 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001037 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001038 if (IDVal == "f" || IDVal == "b") {
1039 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001040 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001041 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001042 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001043 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001044 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001045 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001046 Lex(); // Eat identifier.
1047 }
1048 }
Chris Lattner78db3622009-06-22 05:51:26 +00001049 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001050 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001051 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001052 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001053 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001054 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001055 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001056 Lex(); // Eat token.
1057 return false;
1058 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001059 case AsmToken::Dot: {
1060 // This is a '.' reference, which references the current PC. Emit a
1061 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001062 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001063 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001064 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001065 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001066 Lex(); // Eat identifier.
1067 return false;
1068 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001069 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001070 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001071 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001072 case AsmToken::LBrac:
1073 if (!PlatformParser->HasBracketExpressions())
1074 return TokError("brackets expression not supported on this target");
1075 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001076 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001077 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001078 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001079 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001080 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001081 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001082 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001083 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001084 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001085 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001086 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001087 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001088 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001089 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001090 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001091 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001092 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001093 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001094 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001095 // MIPS unary expression operators. The lexer won't generate these tokens if
1096 // MCAsmInfo::HasMipsExpressions is false for the target.
1097 case AsmToken::PercentCall16:
1098 case AsmToken::PercentCall_Hi:
1099 case AsmToken::PercentCall_Lo:
1100 case AsmToken::PercentDtprel_Hi:
1101 case AsmToken::PercentDtprel_Lo:
1102 case AsmToken::PercentGot:
1103 case AsmToken::PercentGot_Disp:
1104 case AsmToken::PercentGot_Hi:
1105 case AsmToken::PercentGot_Lo:
1106 case AsmToken::PercentGot_Ofst:
1107 case AsmToken::PercentGot_Page:
1108 case AsmToken::PercentGottprel:
1109 case AsmToken::PercentGp_Rel:
1110 case AsmToken::PercentHi:
1111 case AsmToken::PercentHigher:
1112 case AsmToken::PercentHighest:
1113 case AsmToken::PercentLo:
1114 case AsmToken::PercentNeg:
1115 case AsmToken::PercentPcrel_Hi:
1116 case AsmToken::PercentPcrel_Lo:
1117 case AsmToken::PercentTlsgd:
1118 case AsmToken::PercentTlsldm:
1119 case AsmToken::PercentTprel_Hi:
1120 case AsmToken::PercentTprel_Lo:
1121 Lex(); // Eat the operator.
1122 if (Lexer.isNot(AsmToken::LParen))
1123 return TokError("expected '(' after operator");
1124 Lex(); // Eat the operator.
1125 if (parseExpression(Res, EndLoc))
1126 return true;
1127 if (Lexer.isNot(AsmToken::RParen))
1128 return TokError("expected ')'");
1129 Lex(); // Eat the operator.
1130 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1131 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001132 }
1133}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001134
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001135bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001136 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001137 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001138}
1139
Daniel Dunbar55f16672010-09-17 02:47:07 +00001140const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001141AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001142 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001143 // Ask the target implementation about this expression first.
1144 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1145 if (NewE)
1146 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001147 // Recurse over the given expression, rebuilding it to apply the given variant
1148 // if there is exactly one symbol.
1149 switch (E->getKind()) {
1150 case MCExpr::Target:
1151 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001152 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001153
1154 case MCExpr::SymbolRef: {
1155 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1156
1157 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001158 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1159 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001160 return E;
1161 }
1162
Jim Grosbach13760bd2015-05-30 01:25:56 +00001163 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001164 }
1165
1166 case MCExpr::Unary: {
1167 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001168 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001169 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001170 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001171 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001172 }
1173
1174 case MCExpr::Binary: {
1175 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001176 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1177 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001178
1179 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001180 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001181
Jim Grosbach4b905842013-09-20 23:08:21 +00001182 if (!LHS)
1183 LHS = BE->getLHS();
1184 if (!RHS)
1185 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001186
Jim Grosbach13760bd2015-05-30 01:25:56 +00001187 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001188 }
1189 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001190
Craig Toppera2886c22012-02-07 05:05:23 +00001191 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001192}
1193
Jim Grosbach4b905842013-09-20 23:08:21 +00001194/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001195///
Jim Grosbachbd164242011-08-20 16:24:13 +00001196/// expr ::= expr &&,|| expr -> lowest.
1197/// expr ::= expr |,^,&,! expr
1198/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1199/// expr ::= expr <<,>> expr
1200/// expr ::= expr +,- expr
1201/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001202/// expr ::= primaryexpr
1203///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001204bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001205 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001206 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001207 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001208 return true;
1209
Daniel Dunbar55f16672010-09-17 02:47:07 +00001210 // As a special case, we support 'a op b @ modifier' by rewriting the
1211 // expression to include the modifier. This is inefficient, but in general we
1212 // expect users to use 'a@modifier op b'.
1213 if (Lexer.getKind() == AsmToken::At) {
1214 Lex();
1215
1216 if (Lexer.isNot(AsmToken::Identifier))
1217 return TokError("unexpected symbol modifier following '@'");
1218
1219 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001220 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001221 if (Variant == MCSymbolRefExpr::VK_Invalid)
1222 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1223
Jim Grosbach4b905842013-09-20 23:08:21 +00001224 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001225 if (!ModifiedRes) {
1226 return TokError("invalid modifier '" + getTok().getIdentifier() +
1227 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001228 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001229
Daniel Dunbar55f16672010-09-17 02:47:07 +00001230 Res = ModifiedRes;
1231 Lex();
1232 }
1233
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001234 // Try to constant fold it up front, if possible.
1235 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001236 if (Res->evaluateAsAbsolute(Value))
1237 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001238
1239 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001240}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001241
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001242bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001243 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001244 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001245}
1246
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001247bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1248 SMLoc &EndLoc) {
1249 if (parseParenExpr(Res, EndLoc))
1250 return true;
1251
1252 for (; ParenDepth > 0; --ParenDepth) {
1253 if (parseBinOpRHS(1, Res, EndLoc))
1254 return true;
1255
1256 // We don't Lex() the last RParen.
1257 // This is the same behavior as parseParenExpression().
1258 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001259 EndLoc = getTok().getEndLoc();
1260 if (parseToken(AsmToken::RParen,
1261 "expected ')' in parentheses expression"))
1262 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001263 }
1264 }
1265 return false;
1266}
1267
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001268bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001269 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001270
Daniel Dunbar75630b32009-06-30 02:10:03 +00001271 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001272 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001273 return true;
1274
Jim Grosbach13760bd2015-05-30 01:25:56 +00001275 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001276 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001277
1278 return false;
1279}
1280
David Majnemer0993e0b2015-10-26 03:15:34 +00001281static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1282 MCBinaryExpr::Opcode &Kind,
1283 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001284 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001285 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001286 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001287
Jim Grosbach4b905842013-09-20 23:08:21 +00001288 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001289 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001290 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001291 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001292 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001293 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001294 return 1;
1295
Jim Grosbach4b905842013-09-20 23:08:21 +00001296 // Low Precedence: |, &, ^
1297 //
1298 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001299 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001300 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001301 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001302 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001303 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001304 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001305 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001306 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001307 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001308
Jim Grosbach4b905842013-09-20 23:08:21 +00001309 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001310 case AsmToken::EqualEqual:
1311 Kind = MCBinaryExpr::EQ;
1312 return 3;
1313 case AsmToken::ExclaimEqual:
1314 case AsmToken::LessGreater:
1315 Kind = MCBinaryExpr::NE;
1316 return 3;
1317 case AsmToken::Less:
1318 Kind = MCBinaryExpr::LT;
1319 return 3;
1320 case AsmToken::LessEqual:
1321 Kind = MCBinaryExpr::LTE;
1322 return 3;
1323 case AsmToken::Greater:
1324 Kind = MCBinaryExpr::GT;
1325 return 3;
1326 case AsmToken::GreaterEqual:
1327 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001328 return 3;
1329
Jim Grosbach4b905842013-09-20 23:08:21 +00001330 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001331 case AsmToken::LessLess:
1332 Kind = MCBinaryExpr::Shl;
1333 return 4;
1334 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001335 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001336 return 4;
1337
Jim Grosbach4b905842013-09-20 23:08:21 +00001338 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001339 case AsmToken::Plus:
1340 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001341 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001342 case AsmToken::Minus:
1343 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001344 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001345
Jim Grosbach4b905842013-09-20 23:08:21 +00001346 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001347 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001348 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001349 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001350 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001351 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001352 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001353 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001354 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001355 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001356 }
1357}
1358
David Majnemer0993e0b2015-10-26 03:15:34 +00001359static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1360 MCBinaryExpr::Opcode &Kind,
1361 bool ShouldUseLogicalShr) {
1362 switch (K) {
1363 default:
1364 return 0; // not a binop.
1365
1366 // Lowest Precedence: &&, ||
1367 case AsmToken::AmpAmp:
1368 Kind = MCBinaryExpr::LAnd;
1369 return 2;
1370 case AsmToken::PipePipe:
1371 Kind = MCBinaryExpr::LOr;
1372 return 1;
1373
1374 // Low Precedence: ==, !=, <>, <, <=, >, >=
1375 case AsmToken::EqualEqual:
1376 Kind = MCBinaryExpr::EQ;
1377 return 3;
1378 case AsmToken::ExclaimEqual:
1379 case AsmToken::LessGreater:
1380 Kind = MCBinaryExpr::NE;
1381 return 3;
1382 case AsmToken::Less:
1383 Kind = MCBinaryExpr::LT;
1384 return 3;
1385 case AsmToken::LessEqual:
1386 Kind = MCBinaryExpr::LTE;
1387 return 3;
1388 case AsmToken::Greater:
1389 Kind = MCBinaryExpr::GT;
1390 return 3;
1391 case AsmToken::GreaterEqual:
1392 Kind = MCBinaryExpr::GTE;
1393 return 3;
1394
1395 // Low Intermediate Precedence: +, -
1396 case AsmToken::Plus:
1397 Kind = MCBinaryExpr::Add;
1398 return 4;
1399 case AsmToken::Minus:
1400 Kind = MCBinaryExpr::Sub;
1401 return 4;
1402
1403 // High Intermediate Precedence: |, &, ^
1404 //
1405 // FIXME: gas seems to support '!' as an infix operator?
1406 case AsmToken::Pipe:
1407 Kind = MCBinaryExpr::Or;
1408 return 5;
1409 case AsmToken::Caret:
1410 Kind = MCBinaryExpr::Xor;
1411 return 5;
1412 case AsmToken::Amp:
1413 Kind = MCBinaryExpr::And;
1414 return 5;
1415
1416 // Highest Precedence: *, /, %, <<, >>
1417 case AsmToken::Star:
1418 Kind = MCBinaryExpr::Mul;
1419 return 6;
1420 case AsmToken::Slash:
1421 Kind = MCBinaryExpr::Div;
1422 return 6;
1423 case AsmToken::Percent:
1424 Kind = MCBinaryExpr::Mod;
1425 return 6;
1426 case AsmToken::LessLess:
1427 Kind = MCBinaryExpr::Shl;
1428 return 6;
1429 case AsmToken::GreaterGreater:
1430 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1431 return 6;
1432 }
1433}
1434
1435unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1436 MCBinaryExpr::Opcode &Kind) {
1437 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1438 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1439 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1440}
1441
Jim Grosbach4b905842013-09-20 23:08:21 +00001442/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001443/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001444bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001445 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001446 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001447 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001448 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001449 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001450
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001451 // If the next token is lower precedence than we are allowed to eat, return
1452 // successfully with what we ate already.
1453 if (TokPrec < Precedence)
1454 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001455
Sean Callanan686ed8d2010-01-19 20:22:31 +00001456 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001457
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001458 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001459 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001460 if (parsePrimaryExpr(RHS, EndLoc))
1461 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001462
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001463 // If BinOp binds less tightly with RHS than the operator after RHS, let
1464 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001465 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001466 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001467 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1468 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001469
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001470 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001471 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001472 }
1473}
1474
Chris Lattner36e02122009-06-21 20:54:55 +00001475/// ParseStatement:
1476/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001477/// ::= Label* Directive ...Operands... EndOfStatement
1478/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001479bool AsmParser::parseStatement(ParseStatementInfo &Info,
1480 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001481 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001482 // Eat initial spaces and comments
1483 while (Lexer.is(AsmToken::Space))
1484 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001485 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001486 // if this is a line comment we can drop it safely
1487 if (getTok().getString().front() == '\r' ||
1488 getTok().getString().front() == '\n')
1489 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001490 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001491 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001492 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001493 if (Lexer.is(AsmToken::Hash)) {
1494 // Seeing a hash here means that it was an end-of-line comment in
1495 // an asm syntax where hash's are not comment and the previous
1496 // statement parser did not check the end of statement. Relex as
1497 // EndOfStatement.
1498 StringRef CommentStr = parseStringToEndOfStatement();
1499 Lexer.Lex();
1500 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1501 return false;
1502 }
Nirav Davefd910412016-06-17 16:06:17 +00001503 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001504 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001505 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001506 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001507 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001508 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001509 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001510 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001511 if (Lexer.is(AsmToken::Integer)) {
1512 LocalLabelVal = getTok().getIntVal();
1513 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001514 if (!TheCondState.Ignore) {
1515 Lex(); // always eat a token
1516 return Error(IDLoc, "unexpected token at start of statement");
1517 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001518 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001519 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001520 IDVal = getTok().getString();
1521 Lex(); // Consume the integer token to be used as an identifier token.
1522 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001523 if (!TheCondState.Ignore) {
1524 Lex(); // always eat a token
1525 return Error(IDLoc, "unexpected token at start of statement");
1526 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001527 }
1528 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001529 } else if (Lexer.is(AsmToken::Dot)) {
1530 // Treat '.' as a valid identifier in this context.
1531 Lex();
1532 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001533 } else if (Lexer.is(AsmToken::LCurly)) {
1534 // Treat '{' as a valid identifier in this context.
1535 Lex();
1536 IDVal = "{";
1537
1538 } else if (Lexer.is(AsmToken::RCurly)) {
1539 // Treat '}' as a valid identifier in this context.
1540 Lex();
1541 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001542 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001543 if (!TheCondState.Ignore) {
1544 Lex(); // always eat a token
1545 return Error(IDLoc, "unexpected token at start of statement");
1546 }
Chris Lattner926885c2010-04-17 18:14:27 +00001547 IDVal = "";
1548 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001549
Chris Lattner926885c2010-04-17 18:14:27 +00001550 // Handle conditional assembly here before checking for skipping. We
1551 // have to do this so that .endif isn't skipped in a ".if 0" block for
1552 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001553 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001554 DirectiveKindMap.find(IDVal);
1555 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1556 ? DK_NO_DIRECTIVE
1557 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001558 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001559 default:
1560 break;
1561 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001562 case DK_IFEQ:
1563 case DK_IFGE:
1564 case DK_IFGT:
1565 case DK_IFLE:
1566 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001567 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001568 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001569 case DK_IFB:
1570 return parseDirectiveIfb(IDLoc, true);
1571 case DK_IFNB:
1572 return parseDirectiveIfb(IDLoc, false);
1573 case DK_IFC:
1574 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001575 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001576 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001577 case DK_IFNC:
1578 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001579 case DK_IFNES:
1580 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001581 case DK_IFDEF:
1582 return parseDirectiveIfdef(IDLoc, true);
1583 case DK_IFNDEF:
1584 case DK_IFNOTDEF:
1585 return parseDirectiveIfdef(IDLoc, false);
1586 case DK_ELSEIF:
1587 return parseDirectiveElseIf(IDLoc);
1588 case DK_ELSE:
1589 return parseDirectiveElse(IDLoc);
1590 case DK_ENDIF:
1591 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001592 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001593
Eli Bendersky88024712013-01-16 19:32:36 +00001594 // Ignore the statement if in the middle of inactive conditional
1595 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001596 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001597 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001598 return false;
1599 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001600
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001601 // FIXME: Recurse on local labels?
1602
1603 // See what kind of statement we have.
1604 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001605 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001606 if (!getTargetParser().isLabel(ID))
1607 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001608 if (checkForValidSection())
1609 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001610
Chris Lattner36e02122009-06-21 20:54:55 +00001611 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001612 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001613
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001614 // Diagnose attempt to use '.' as a label.
1615 if (IDVal == ".")
1616 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1617
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001618 // Diagnose attempt to use a variable as a label.
1619 //
1620 // FIXME: Diagnostics. Note the location of the definition as a label.
1621 // FIXME: This doesn't diagnose assignment to a symbol which has been
1622 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001623 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001624 if (LocalLabelVal == -1) {
1625 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001626 StringRef RewrittenLabel =
1627 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001628 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001629 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001630 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1631 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001632 IDVal = RewrittenLabel;
1633 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001634 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001635 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001636 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001637 // End of Labels should be treated as end of line for lexing
1638 // purposes but that information is not available to the Lexer who
1639 // does not understand Labels. This may cause us to see a Hash
1640 // here instead of a preprocessor line comment.
1641 if (getTok().is(AsmToken::Hash)) {
1642 StringRef CommentStr = parseStringToEndOfStatement();
1643 Lexer.Lex();
1644 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1645 }
1646
Nirav Dave8ea792d2016-07-13 14:03:12 +00001647 // Consume any end of statement token, if present, to avoid spurious
1648 // AddBlankLine calls().
1649 if (getTok().is(AsmToken::EndOfStatement)) {
1650 Lex();
1651 }
1652
Daniel Dunbare73b2672009-08-26 22:13:22 +00001653 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001654 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001655 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001656
Kevin Enderbye7739d42011-12-09 18:09:40 +00001657 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001658 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001659 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001660 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1661 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001662
Tim Northover1744d0a2013-10-25 12:49:50 +00001663 getTargetParser().onLabelParsed(Sym);
1664
Eli Friedman0f4871d2012-10-22 23:58:19 +00001665 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001666 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001667
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001668 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001669 if (!getTargetParser().equalIsAsmAssignment())
1670 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001671 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001672 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001673
Jim Grosbach4b905842013-09-20 23:08:21 +00001674 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001675
1676 default: // Normal instruction or directive.
1677 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001678 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001679
1680 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001681 if (areMacrosEnabled())
1682 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1683 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001684 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001685
Michael J. Spencer530ce852010-10-09 11:00:50 +00001686 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001687
Eli Bendersky17233942013-01-15 22:59:42 +00001688 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001689 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001690 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001691 //
Eli Bendersky17233942013-01-15 22:59:42 +00001692 // 1. The target-specific assembly parser. Some directives are target
1693 // specific or may potentially behave differently on certain targets.
1694 // 2. Asm parser extensions. For example, platform-specific parsers
1695 // (like the ELF parser) register themselves as extensions.
1696 // 3. The generic directive parser implemented by this class. These are
1697 // all the directives that behave in a target and platform independent
1698 // manner, or at least have a default behavior that's shared between
1699 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001700
Oliver Stannard21718282016-07-26 14:19:47 +00001701 getTargetParser().flushPendingInstructions(getStreamer());
1702
Nirav Dave2364748a2016-09-16 18:30:20 +00001703 SMLoc StartTokLoc = getTok().getLoc();
1704 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1705
1706 if (hasPendingError())
1707 return true;
1708 // Currently the return value should be true if we are
1709 // uninterested but as this is at odds with the standard parsing
1710 // convention (return true = error) we have instances of a parsed
1711 // directive that fails returning true as an error. Catch these
1712 // cases as best as possible errors here.
1713 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1714 return true;
1715 // Return if we did some parsing or believe we succeeded.
1716 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001717 return false;
1718
Alp Tokercb402912014-01-24 17:20:08 +00001719 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001720 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001721 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1722 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001723 if (Handler.first)
1724 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1725
1726 // Finally, if no one else is interested in this directive, it must be
1727 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001728 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001729 default:
1730 break;
1731 case DK_SET:
1732 case DK_EQU:
1733 return parseDirectiveSet(IDVal, true);
1734 case DK_EQUIV:
1735 return parseDirectiveSet(IDVal, false);
1736 case DK_ASCII:
1737 return parseDirectiveAscii(IDVal, false);
1738 case DK_ASCIZ:
1739 case DK_STRING:
1740 return parseDirectiveAscii(IDVal, true);
1741 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001742 case DK_DC_B:
1743 return parseDirectiveValue(IDVal, 1);
1744 case DK_DC:
1745 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001746 case DK_SHORT:
1747 case DK_VALUE:
1748 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001749 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001750 case DK_LONG:
1751 case DK_INT:
1752 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001753 case DK_DC_L:
1754 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001755 case DK_QUAD:
1756 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001757 return parseDirectiveValue(IDVal, 8);
1758 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001759 return parseDirectiveValue(
1760 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001761 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001762 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001763 case DK_SINGLE:
1764 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001765 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001766 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001767 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001768 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001769 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001770 case DK_ALIGN: {
1771 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1772 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1773 }
1774 case DK_ALIGN32: {
1775 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1776 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1777 }
1778 case DK_BALIGN:
1779 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1780 case DK_BALIGNW:
1781 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1782 case DK_BALIGNL:
1783 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1784 case DK_P2ALIGN:
1785 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1786 case DK_P2ALIGNW:
1787 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1788 case DK_P2ALIGNL:
1789 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1790 case DK_ORG:
1791 return parseDirectiveOrg();
1792 case DK_FILL:
1793 return parseDirectiveFill();
1794 case DK_ZERO:
1795 return parseDirectiveZero();
1796 case DK_EXTERN:
1797 eatToEndOfStatement(); // .extern is the default, ignore it.
1798 return false;
1799 case DK_GLOBL:
1800 case DK_GLOBAL:
1801 return parseDirectiveSymbolAttribute(MCSA_Global);
1802 case DK_LAZY_REFERENCE:
1803 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1804 case DK_NO_DEAD_STRIP:
1805 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1806 case DK_SYMBOL_RESOLVER:
1807 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1808 case DK_PRIVATE_EXTERN:
1809 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1810 case DK_REFERENCE:
1811 return parseDirectiveSymbolAttribute(MCSA_Reference);
1812 case DK_WEAK_DEFINITION:
1813 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1814 case DK_WEAK_REFERENCE:
1815 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1816 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1817 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1818 case DK_COMM:
1819 case DK_COMMON:
1820 return parseDirectiveComm(/*IsLocal=*/false);
1821 case DK_LCOMM:
1822 return parseDirectiveComm(/*IsLocal=*/true);
1823 case DK_ABORT:
1824 return parseDirectiveAbort();
1825 case DK_INCLUDE:
1826 return parseDirectiveInclude();
1827 case DK_INCBIN:
1828 return parseDirectiveIncbin();
1829 case DK_CODE16:
1830 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001831 return TokError(Twine(IDVal) +
1832 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001833 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001834 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001835 case DK_IRP:
1836 return parseDirectiveIrp(IDLoc);
1837 case DK_IRPC:
1838 return parseDirectiveIrpc(IDLoc);
1839 case DK_ENDR:
1840 return parseDirectiveEndr(IDLoc);
1841 case DK_BUNDLE_ALIGN_MODE:
1842 return parseDirectiveBundleAlignMode();
1843 case DK_BUNDLE_LOCK:
1844 return parseDirectiveBundleLock();
1845 case DK_BUNDLE_UNLOCK:
1846 return parseDirectiveBundleUnlock();
1847 case DK_SLEB128:
1848 return parseDirectiveLEB128(true);
1849 case DK_ULEB128:
1850 return parseDirectiveLEB128(false);
1851 case DK_SPACE:
1852 case DK_SKIP:
1853 return parseDirectiveSpace(IDVal);
1854 case DK_FILE:
1855 return parseDirectiveFile(IDLoc);
1856 case DK_LINE:
1857 return parseDirectiveLine();
1858 case DK_LOC:
1859 return parseDirectiveLoc();
1860 case DK_STABS:
1861 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001862 case DK_CV_FILE:
1863 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001864 case DK_CV_FUNC_ID:
1865 return parseDirectiveCVFuncId();
1866 case DK_CV_INLINE_SITE_ID:
1867 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001868 case DK_CV_LOC:
1869 return parseDirectiveCVLoc();
1870 case DK_CV_LINETABLE:
1871 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001872 case DK_CV_INLINE_LINETABLE:
1873 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001874 case DK_CV_DEF_RANGE:
1875 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001876 case DK_CV_STRINGTABLE:
1877 return parseDirectiveCVStringTable();
1878 case DK_CV_FILECHECKSUMS:
1879 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001880 case DK_CFI_SECTIONS:
1881 return parseDirectiveCFISections();
1882 case DK_CFI_STARTPROC:
1883 return parseDirectiveCFIStartProc();
1884 case DK_CFI_ENDPROC:
1885 return parseDirectiveCFIEndProc();
1886 case DK_CFI_DEF_CFA:
1887 return parseDirectiveCFIDefCfa(IDLoc);
1888 case DK_CFI_DEF_CFA_OFFSET:
1889 return parseDirectiveCFIDefCfaOffset();
1890 case DK_CFI_ADJUST_CFA_OFFSET:
1891 return parseDirectiveCFIAdjustCfaOffset();
1892 case DK_CFI_DEF_CFA_REGISTER:
1893 return parseDirectiveCFIDefCfaRegister(IDLoc);
1894 case DK_CFI_OFFSET:
1895 return parseDirectiveCFIOffset(IDLoc);
1896 case DK_CFI_REL_OFFSET:
1897 return parseDirectiveCFIRelOffset(IDLoc);
1898 case DK_CFI_PERSONALITY:
1899 return parseDirectiveCFIPersonalityOrLsda(true);
1900 case DK_CFI_LSDA:
1901 return parseDirectiveCFIPersonalityOrLsda(false);
1902 case DK_CFI_REMEMBER_STATE:
1903 return parseDirectiveCFIRememberState();
1904 case DK_CFI_RESTORE_STATE:
1905 return parseDirectiveCFIRestoreState();
1906 case DK_CFI_SAME_VALUE:
1907 return parseDirectiveCFISameValue(IDLoc);
1908 case DK_CFI_RESTORE:
1909 return parseDirectiveCFIRestore(IDLoc);
1910 case DK_CFI_ESCAPE:
1911 return parseDirectiveCFIEscape();
1912 case DK_CFI_SIGNAL_FRAME:
1913 return parseDirectiveCFISignalFrame();
1914 case DK_CFI_UNDEFINED:
1915 return parseDirectiveCFIUndefined(IDLoc);
1916 case DK_CFI_REGISTER:
1917 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001918 case DK_CFI_WINDOW_SAVE:
1919 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001920 case DK_MACROS_ON:
1921 case DK_MACROS_OFF:
1922 return parseDirectiveMacrosOnOff(IDVal);
1923 case DK_MACRO:
1924 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001925 case DK_EXITM:
1926 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001927 case DK_ENDM:
1928 case DK_ENDMACRO:
1929 return parseDirectiveEndMacro(IDVal);
1930 case DK_PURGEM:
1931 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001932 case DK_END:
1933 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001934 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001935 return parseDirectiveError(IDLoc, false);
1936 case DK_ERROR:
1937 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001938 case DK_WARNING:
1939 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001940 case DK_RELOC:
1941 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001942 case DK_DCB:
1943 case DK_DCB_W:
1944 return parseDirectiveDCB(IDVal, 2);
1945 case DK_DCB_B:
1946 return parseDirectiveDCB(IDVal, 1);
1947 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001948 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001949 case DK_DCB_L:
1950 return parseDirectiveDCB(IDVal, 4);
1951 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001952 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00001953 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001954 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00001955 return TokError(Twine(IDVal) +
1956 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00001957 case DK_DS:
1958 case DK_DS_W:
1959 return parseDirectiveDS(IDVal, 2);
1960 case DK_DS_B:
1961 return parseDirectiveDS(IDVal, 1);
1962 case DK_DS_D:
1963 return parseDirectiveDS(IDVal, 8);
1964 case DK_DS_L:
1965 case DK_DS_S:
1966 return parseDirectiveDS(IDVal, 4);
1967 case DK_DS_P:
1968 case DK_DS_X:
1969 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00001970 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001971
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001972 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001973 }
Chris Lattner36e02122009-06-21 20:54:55 +00001974
Chad Rosierc7f552c2013-02-12 21:33:51 +00001975 // __asm _emit or __asm __emit
1976 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1977 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001978 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001979
1980 // __asm align
1981 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001982 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001983
Coby Tayree3847be92017-04-04 17:57:23 +00001984 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001985 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00001986 if (checkForValidSection())
1987 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001988
Chris Lattner7cbfa442010-05-19 23:34:33 +00001989 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001990 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001991 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00001992 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1993 Info.ParsedOperands);
1994 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001995
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001996 // Dump the parsed representation, if requested.
1997 if (getShowParsedOperands()) {
1998 SmallString<256> Str;
1999 raw_svector_ostream OS(Str);
2000 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002001 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002002 if (i != 0)
2003 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002004 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002005 }
2006 OS << "]";
2007
Jim Grosbach4b905842013-09-20 23:08:21 +00002008 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002009 }
2010
Nirav Dave2364748a2016-09-16 18:30:20 +00002011 // Fail even if ParseInstruction erroneously returns false.
2012 if (hasPendingError() || ParseHadError)
2013 return true;
2014
Oliver Stannard8b273082014-06-19 15:52:37 +00002015 // If we are generating dwarf for the current section then generate a .loc
2016 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002017 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002018 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002019 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002020 unsigned Line;
2021 if (ActiveMacros.empty())
2022 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2023 else
Frederic Riss16238d92015-06-25 21:57:33 +00002024 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2025 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002026
Eli Bendersky88024712013-01-16 19:32:36 +00002027 // If we previously parsed a cpp hash file line comment then make sure the
2028 // current Dwarf File is for the CppHashFilename if not then emit the
2029 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002030 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002031 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002032 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002033 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002034
Jim Grosbach4b905842013-09-20 23:08:21 +00002035 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2036 // cache with the different Loc from the call above we save the last
2037 // info we queried here with SrcMgr.FindLineNumber().
2038 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002039 if (LastQueryIDLoc == CppHashInfo.Loc &&
2040 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002041 CppHashLocLineNo = LastQueryLine;
2042 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002043 CppHashLocLineNo =
2044 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002045 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002046 LastQueryIDLoc = CppHashInfo.Loc;
2047 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002048 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002049 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002050 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002051
Jim Grosbach4b905842013-09-20 23:08:21 +00002052 getStreamer().EmitDwarfLocDirective(
2053 getContext().getGenDwarfFileNumber(), Line, 0,
2054 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2055 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002056 }
2057
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002058 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002059 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002060 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002061 if (getTargetParser().MatchAndEmitInstruction(
2062 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2063 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002064 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002065 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002066 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002067}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002068
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002069// Parse and erase curly braces marking block start/end
2070bool
2071AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2072 // Identify curly brace marking block start/end
2073 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2074 return false;
2075
2076 SMLoc StartLoc = Lexer.getLoc();
2077 Lex(); // Eat the brace
2078 if (Lexer.is(AsmToken::EndOfStatement))
2079 Lex(); // Eat EndOfStatement following the brace
2080
2081 // Erase the block start/end brace from the output asm string
2082 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2083 StartLoc.getPointer());
2084 return true;
2085}
2086
Jim Grosbach4b905842013-09-20 23:08:21 +00002087/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002088/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002089bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002090 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002091 // Lexer only ever emits HashDirective if it fully formed if it's
2092 // done the checking already so this is an internal error.
2093 assert(getTok().is(AsmToken::Integer) &&
2094 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002095 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002096 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002097 assert(getTok().is(AsmToken::String) &&
2098 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002099 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002100 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002101
Kevin Enderby72553612011-09-13 23:45:18 +00002102 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002103 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002104
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002105 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002106 CppHashInfo.Loc = L;
2107 CppHashInfo.Filename = Filename;
2108 CppHashInfo.LineNumber = LineNumber;
2109 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002110 return false;
2111}
2112
Jim Grosbach4b905842013-09-20 23:08:21 +00002113/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002114/// for the Filename and LineNo if any in the diagnostic.
2115void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002116 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002117 raw_ostream &OS = errs();
2118
2119 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002120 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002121 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2122 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002123 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002124
Jim Grosbach4b905842013-09-20 23:08:21 +00002125 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002126 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002127 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2128 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2129 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002130 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2131 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002132 }
2133
Eric Christophera7c32732012-12-18 00:30:54 +00002134 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002135 // manager changed or buffer changed (like in a nested include) then just
2136 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002137 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002138 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002139 if (Parser->SavedDiagHandler)
2140 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2141 else
Craig Topper353eda42014-04-24 06:44:33 +00002142 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002143 return;
2144 }
2145
Eric Christophera7c32732012-12-18 00:30:54 +00002146 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002147 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2148 // for the diagnostic.
2149 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002150
2151 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2152 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002153 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002154 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002155 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002156
Jim Grosbach4b905842013-09-20 23:08:21 +00002157 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2158 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002159 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002160
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002161 if (Parser->SavedDiagHandler)
2162 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2163 else
Craig Topper353eda42014-04-24 06:44:33 +00002164 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002165}
2166
Rafael Espindola2c064482012-08-21 18:29:30 +00002167// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2168// difference being that that function accepts '@' as part of identifiers and
2169// we can't do that. AsmLexer.cpp should probably be changed to handle
2170// '@' as a special case when needed.
2171static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002172 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2173 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002174}
2175
Rafael Espindola34b9c512012-06-03 23:57:14 +00002176bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002177 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002178 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002179 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002180 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002181 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002182 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002183 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002184
Preston Gurd05500642012-09-19 20:36:12 +00002185 // A macro without parameters is handled differently on Darwin:
2186 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002187 while (!Body.empty()) {
2188 // Scan for the next substitution.
2189 std::size_t End = Body.size(), Pos = 0;
2190 for (; Pos != End; ++Pos) {
2191 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002192 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002193 // This macro has no parameters, look for $0, $1, etc.
2194 if (Body[Pos] != '$' || Pos + 1 == End)
2195 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002196
Rafael Espindola1134ab232011-06-05 02:43:45 +00002197 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002198 if (Next == '$' || Next == 'n' ||
2199 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002200 break;
2201 } else {
2202 // This macro has parameters, look for \foo, \bar, etc.
2203 if (Body[Pos] == '\\' && Pos + 1 != End)
2204 break;
2205 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002206 }
2207
2208 // Add the prefix.
2209 OS << Body.slice(0, Pos);
2210
2211 // Check if we reached the end.
2212 if (Pos == End)
2213 break;
2214
Benjamin Kramer513e7442014-02-20 13:36:32 +00002215 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002216 switch (Body[Pos + 1]) {
2217 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002218 case '$':
2219 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002220 break;
2221
Jim Grosbach4b905842013-09-20 23:08:21 +00002222 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002223 case 'n':
2224 OS << A.size();
2225 break;
2226
Jim Grosbach4b905842013-09-20 23:08:21 +00002227 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002228 default: {
2229 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002230 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002231 if (Index >= A.size())
2232 break;
2233
2234 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002235 for (const AsmToken &Token : A[Index])
2236 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002237 break;
2238 }
2239 }
2240 Pos += 2;
2241 } else {
2242 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002243
2244 // Check for the \@ pseudo-variable.
2245 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002246 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002247 else
2248 while (isIdentifierChar(Body[I]) && I + 1 != End)
2249 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002250
Jim Grosbach4b905842013-09-20 23:08:21 +00002251 const char *Begin = Body.data() + Pos + 1;
2252 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002253 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002254
Toma Tabacu217116e2015-04-27 10:50:29 +00002255 if (Argument == "@") {
2256 OS << NumOfMacroInstantiations;
2257 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002258 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002259 for (; Index < NParameters; ++Index)
2260 if (Parameters[Index].Name == Argument)
2261 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002262
Toma Tabacu217116e2015-04-27 10:50:29 +00002263 if (Index == NParameters) {
2264 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2265 Pos += 3;
2266 else {
2267 OS << '\\' << Argument;
2268 Pos = I;
2269 }
2270 } else {
2271 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002272 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002273 // We expect no quotes around the string's contents when
2274 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002275 if (Token.getKind() != AsmToken::String || VarargParameter)
2276 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002277 else
Craig Topper84008482015-10-10 05:38:14 +00002278 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002279
2280 Pos += 1 + Argument.size();
2281 }
Preston Gurd05500642012-09-19 20:36:12 +00002282 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002283 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002284 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002285 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002286 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002287
Rafael Espindola1134ab232011-06-05 02:43:45 +00002288 return false;
2289}
Daniel Dunbar43235712010-07-18 18:54:11 +00002290
Nico Weber2a8f9222014-07-24 16:29:04 +00002291MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002292 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002293 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002294 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002295
Jim Grosbach4b905842013-09-20 23:08:21 +00002296static bool isOperator(AsmToken::TokenKind kind) {
2297 switch (kind) {
2298 default:
2299 return false;
2300 case AsmToken::Plus:
2301 case AsmToken::Minus:
2302 case AsmToken::Tilde:
2303 case AsmToken::Slash:
2304 case AsmToken::Star:
2305 case AsmToken::Dot:
2306 case AsmToken::Equal:
2307 case AsmToken::EqualEqual:
2308 case AsmToken::Pipe:
2309 case AsmToken::PipePipe:
2310 case AsmToken::Caret:
2311 case AsmToken::Amp:
2312 case AsmToken::AmpAmp:
2313 case AsmToken::Exclaim:
2314 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002315 case AsmToken::Less:
2316 case AsmToken::LessEqual:
2317 case AsmToken::LessLess:
2318 case AsmToken::LessGreater:
2319 case AsmToken::Greater:
2320 case AsmToken::GreaterEqual:
2321 case AsmToken::GreaterGreater:
2322 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002323 }
2324}
2325
David Majnemer16252452014-01-29 00:07:39 +00002326namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002327
David Majnemer16252452014-01-29 00:07:39 +00002328class AsmLexerSkipSpaceRAII {
2329public:
2330 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2331 Lexer.setSkipSpace(SkipSpace);
2332 }
2333
2334 ~AsmLexerSkipSpaceRAII() {
2335 Lexer.setSkipSpace(true);
2336 }
2337
2338private:
2339 AsmLexer &Lexer;
2340};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002341
2342} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002343
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002344bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2345
2346 if (Vararg) {
2347 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2348 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002349 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002350 }
2351 return false;
2352 }
2353
Rafael Espindola768b41c2012-06-15 14:02:34 +00002354 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002355
David Majnemer16252452014-01-29 00:07:39 +00002356 // Darwin doesn't use spaces to delmit arguments.
2357 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002358
Scott Egertona1fa68a2016-02-11 13:48:49 +00002359 bool SpaceEaten;
2360
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002361 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002362 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002363 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002364 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002365
Scott Egertona1fa68a2016-02-11 13:48:49 +00002366 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002367
Scott Egertona1fa68a2016-02-11 13:48:49 +00002368 if (Lexer.is(AsmToken::Comma))
2369 break;
2370
2371 if (Lexer.is(AsmToken::Space)) {
2372 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002373 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002374 }
Preston Gurd05500642012-09-19 20:36:12 +00002375
2376 // Spaces can delimit parameters, but could also be part an expression.
2377 // If the token after a space is an operator, add the token and the next
2378 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002379 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002380 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002381 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002382 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002383
Scott Egertona1fa68a2016-02-11 13:48:49 +00002384 // Whitespace after an operator can be ignored.
2385 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002386 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002387
2388 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002389 }
2390 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002391 if (SpaceEaten)
2392 break;
Preston Gurd05500642012-09-19 20:36:12 +00002393 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002394
Jim Grosbach4b905842013-09-20 23:08:21 +00002395 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002396 // to be able to fill in the remaining default parameter values
2397 if (Lexer.is(AsmToken::EndOfStatement))
2398 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002399
2400 // Adjust the current parentheses level.
2401 if (Lexer.is(AsmToken::LParen))
2402 ++ParenLevel;
2403 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2404 --ParenLevel;
2405
2406 // Append the token to the current argument list.
2407 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002408 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002409 }
Preston Gurd05500642012-09-19 20:36:12 +00002410
Rafael Espindola768b41c2012-06-15 14:02:34 +00002411 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002412 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002413 return false;
2414}
2415
2416// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002417bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002418 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002419 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002420 bool NamedParametersFound = false;
2421 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002422
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002423 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002424 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002425
Rafael Espindola768b41c2012-06-15 14:02:34 +00002426 // Parse two kinds of macro invocations:
2427 // - macros defined without any parameters accept an arbitrary number of them
2428 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002429 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002430 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2431 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002432 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002433 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002434
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002435 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002436 if (parseIdentifier(FA.Name))
2437 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002438
Nirav Dave2364748a2016-09-16 18:30:20 +00002439 if (Lexer.isNot(AsmToken::Equal))
2440 return TokError("expected '=' after formal parameter identifier");
2441
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002442 Lex();
2443
2444 NamedParametersFound = true;
2445 }
2446
Nirav Dave2364748a2016-09-16 18:30:20 +00002447 if (NamedParametersFound && FA.Name.empty())
2448 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002449
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002450 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2451 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002452 return true;
2453
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002454 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002455 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002456 unsigned FAI = 0;
2457 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002458 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002459 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002460
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002461 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002462 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002463 return Error(IDLoc, "parameter named '" + FA.Name +
2464 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002465 }
2466 PI = FAI;
2467 }
2468
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002469 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002470 if (A.size() <= PI)
2471 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002472 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002473
2474 if (FALocs.size() <= PI)
2475 FALocs.resize(PI + 1);
2476
2477 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002478 }
Jim Grosbach206661622012-07-30 22:44:17 +00002479
Preston Gurd242ed3152012-09-19 20:29:04 +00002480 // At the end of the statement, fill in remaining arguments that have
2481 // default values. If there aren't any, then the next argument is
2482 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002483 if (Lexer.is(AsmToken::EndOfStatement)) {
2484 bool Failure = false;
2485 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2486 if (A[FAI].empty()) {
2487 if (M->Parameters[FAI].Required) {
2488 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2489 "missing value for required parameter "
2490 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2491 Failure = true;
2492 }
2493
2494 if (!M->Parameters[FAI].Value.empty())
2495 A[FAI] = M->Parameters[FAI].Value;
2496 }
2497 }
2498 return Failure;
2499 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002500
2501 if (Lexer.is(AsmToken::Comma))
2502 Lex();
2503 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002504
2505 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002506}
2507
Jim Grosbach4b905842013-09-20 23:08:21 +00002508const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002509 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2510 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002511}
2512
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002513void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2514 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002515}
2516
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002517void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002518
Jim Grosbach4b905842013-09-20 23:08:21 +00002519bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002520 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2521 // eliminate this, although we should protect against infinite loops.
2522 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2523 if (ActiveMacros.size() == MaxNestingDepth) {
2524 std::ostringstream MaxNestingDepthError;
2525 MaxNestingDepthError << "macros cannot be nested more than "
2526 << MaxNestingDepth << " levels deep."
2527 << " Use -asm-macro-max-nesting-depth to increase "
2528 "this limit.";
2529 return TokError(MaxNestingDepthError.str());
2530 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002531
Eli Bendersky38274122013-01-14 23:22:36 +00002532 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002533 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002534 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002535
Rafael Espindola1134ab232011-06-05 02:43:45 +00002536 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2537 // to hold the macro body with substitutions.
2538 SmallString<256> Buf;
2539 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002540 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002541
Toma Tabacu217116e2015-04-27 10:50:29 +00002542 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002543 return true;
2544
Eli Bendersky38274122013-01-14 23:22:36 +00002545 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002546 // instantiation.
2547 OS << ".endmacro\n";
2548
Rafael Espindola3560ff22014-08-27 20:03:13 +00002549 std::unique_ptr<MemoryBuffer> Instantiation =
2550 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002551
Daniel Dunbar43235712010-07-18 18:54:11 +00002552 // Create the macro instantiation object and add to the current macro
2553 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002554 MacroInstantiation *MI = new MacroInstantiation(
2555 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002556 ActiveMacros.push_back(MI);
2557
Toma Tabacu217116e2015-04-27 10:50:29 +00002558 ++NumOfMacroInstantiations;
2559
Daniel Dunbar43235712010-07-18 18:54:11 +00002560 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002561 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002562 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002563 Lex();
2564
2565 return false;
2566}
2567
Jim Grosbach4b905842013-09-20 23:08:21 +00002568void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002569 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002570 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002571 Lex();
2572
2573 // Pop the instantiation entry.
2574 delete ActiveMacros.back();
2575 ActiveMacros.pop_back();
2576}
2577
Jim Grosbach4b905842013-09-20 23:08:21 +00002578bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002579 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002580 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002581 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002582 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2583 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002584 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002585
Pete Cooper80d21cb2015-06-22 19:35:57 +00002586 if (!Sym) {
2587 // In the case where we parse an expression starting with a '.', we will
2588 // not generate an error, nor will we create a symbol. In this case we
2589 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002590 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002591 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002592
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002593 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002594 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002595 if (NoDeadStrip)
2596 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2597
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002598 return false;
2599}
2600
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002601/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002602/// ::= identifier
2603/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002604bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002605 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002606 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2607 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002608 // handle this as a context dependent token, instead we detect adjacent tokens
2609 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002610 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2611 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002612
Hans Wennborgce69d772013-10-18 20:46:28 +00002613 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002614
2615 AsmToken Buf[1];
2616 Lexer.peekTokens(Buf, false);
2617
2618 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002619 return true;
2620
Hans Wennborgce69d772013-10-18 20:46:28 +00002621 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002622 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002623 return true;
2624
Nirav Daved0463322016-10-12 13:58:07 +00002625 // eat $ or @
2626 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002627 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002628 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002629 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002630 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002631 return false;
2632 }
2633
Jim Grosbach4b905842013-09-20 23:08:21 +00002634 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002635 return true;
2636
Sean Callanan936b0d32010-01-19 21:44:56 +00002637 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002638
Sean Callanan686ed8d2010-01-19 20:22:31 +00002639 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002640
2641 return false;
2642}
2643
Jim Grosbach4b905842013-09-20 23:08:21 +00002644/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002645/// ::= .equ identifier ',' expression
2646/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002647/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002648bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002649 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002650 if (check(parseIdentifier(Name), "expected identifier") ||
2651 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2652 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2653 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002654}
2655
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002656bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002657 if (check(getTok().isNot(AsmToken::String), "expected string"))
2658 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002659
2660 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002661 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002662 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2663 if (Str[i] != '\\') {
2664 Data += Str[i];
2665 continue;
2666 }
2667
2668 // Recognize escaped characters. Note that this escape semantics currently
2669 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2670 ++i;
2671 if (i == e)
2672 return TokError("unexpected backslash at end of string");
2673
2674 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002675 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002676 // Consume up to three octal characters.
2677 unsigned Value = Str[i] - '0';
2678
Jim Grosbach4b905842013-09-20 23:08:21 +00002679 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002680 ++i;
2681 Value = Value * 8 + (Str[i] - '0');
2682
Jim Grosbach4b905842013-09-20 23:08:21 +00002683 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002684 ++i;
2685 Value = Value * 8 + (Str[i] - '0');
2686 }
2687 }
2688
2689 if (Value > 255)
2690 return TokError("invalid octal escape sequence (out of range)");
2691
Jim Grosbach4b905842013-09-20 23:08:21 +00002692 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002693 continue;
2694 }
2695
2696 // Otherwise recognize individual escapes.
2697 switch (Str[i]) {
2698 default:
2699 // Just reject invalid escape sequences for now.
2700 return TokError("invalid escape sequence (unrecognized character)");
2701
2702 case 'b': Data += '\b'; break;
2703 case 'f': Data += '\f'; break;
2704 case 'n': Data += '\n'; break;
2705 case 'r': Data += '\r'; break;
2706 case 't': Data += '\t'; break;
2707 case '"': Data += '"'; break;
2708 case '\\': Data += '\\'; break;
2709 }
2710 }
2711
Nirav Davea645433c2016-07-18 15:24:03 +00002712 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002713 return false;
2714}
2715
Jim Grosbach4b905842013-09-20 23:08:21 +00002716/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002717/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002718bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002719 auto parseOp = [&]() -> bool {
2720 std::string Data;
2721 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002722 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002723 getStreamer().EmitBytes(Data);
2724 if (ZeroTerminated)
2725 getStreamer().EmitBytes(StringRef("\0", 1));
2726 return false;
2727 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002728
Nirav Dave1a9044b2016-10-24 14:35:29 +00002729 if (parseMany(parseOp))
2730 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002731 return false;
2732}
2733
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002734/// parseDirectiveReloc
2735/// ::= .reloc expression , identifier [ , expression ]
2736bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2737 const MCExpr *Offset;
2738 const MCExpr *Expr = nullptr;
2739
2740 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002741 int64_t OffsetValue;
2742 // We can only deal with constant expressions at the moment.
2743
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002744 if (parseExpression(Offset))
2745 return true;
2746
Nirav Davea645433c2016-07-18 15:24:03 +00002747 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2748 "expression is not a constant value") ||
2749 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2750 parseToken(AsmToken::Comma, "expected comma") ||
2751 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2752 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002753
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002754 SMLoc NameLoc = Lexer.getTok().getLoc();
2755 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002756 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002757
2758 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002759 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002760 SMLoc ExprLoc = Lexer.getLoc();
2761 if (parseExpression(Expr))
2762 return true;
2763
2764 MCValue Value;
2765 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2766 return Error(ExprLoc, "expression must be relocatable");
2767 }
2768
Nirav Davea645433c2016-07-18 15:24:03 +00002769 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002770 "unexpected token in .reloc directive"))
2771 return true;
2772
2773 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2774 return Error(NameLoc, "unknown relocation name");
2775
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002776 return false;
2777}
2778
Jim Grosbach4b905842013-09-20 23:08:21 +00002779/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002780/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002781bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2782 auto parseOp = [&]() -> bool {
2783 const MCExpr *Value;
2784 SMLoc ExprLoc = getLexer().getLoc();
2785 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002786 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002787 // Special case constant expressions to match code generator.
2788 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2789 assert(Size <= 8 && "Invalid size");
2790 uint64_t IntValue = MCE->getValue();
2791 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2792 return Error(ExprLoc, "out of range literal value");
2793 getStreamer().EmitIntValue(IntValue, Size);
2794 } else
2795 getStreamer().EmitValue(Value, Size, ExprLoc);
2796 return false;
2797 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002798
Nirav Dave1a9044b2016-10-24 14:35:29 +00002799 if (parseMany(parseOp))
2800 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002801 return false;
2802}
2803
David Woodhoused6de0d92014-02-01 16:20:59 +00002804/// ParseDirectiveOctaValue
2805/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002806
2807bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2808 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002809 if (checkForValidSection())
2810 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002811 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2812 return TokError("unknown token in expression");
2813 SMLoc ExprLoc = getTok().getLoc();
2814 APInt IntValue = getTok().getAPIntVal();
2815 uint64_t hi, lo;
2816 Lex();
2817 if (!IntValue.isIntN(128))
2818 return Error(ExprLoc, "out of range literal value");
2819 if (!IntValue.isIntN(64)) {
2820 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2821 lo = IntValue.getLoBits(64).getZExtValue();
2822 } else {
2823 hi = 0;
2824 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002825 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002826 if (MAI.isLittleEndian()) {
2827 getStreamer().EmitIntValue(lo, 8);
2828 getStreamer().EmitIntValue(hi, 8);
2829 } else {
2830 getStreamer().EmitIntValue(hi, 8);
2831 getStreamer().EmitIntValue(lo, 8);
2832 }
2833 return false;
2834 };
David Woodhoused6de0d92014-02-01 16:20:59 +00002835
Nirav Dave1a9044b2016-10-24 14:35:29 +00002836 if (parseMany(parseOp))
2837 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00002838 return false;
2839}
2840
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002841bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2842 // We don't truly support arithmetic on floating point expressions, so we
2843 // have to manually parse unary prefixes.
2844 bool IsNeg = false;
2845 if (getLexer().is(AsmToken::Minus)) {
2846 Lexer.Lex();
2847 IsNeg = true;
2848 } else if (getLexer().is(AsmToken::Plus))
2849 Lexer.Lex();
2850
2851 if (Lexer.is(AsmToken::Error))
2852 return TokError(Lexer.getErr());
2853 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2854 Lexer.isNot(AsmToken::Identifier))
2855 return TokError("unexpected token in directive");
2856
2857 // Convert to an APFloat.
2858 APFloat Value(Semantics);
2859 StringRef IDVal = getTok().getString();
2860 if (getLexer().is(AsmToken::Identifier)) {
2861 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2862 Value = APFloat::getInf(Semantics);
2863 else if (!IDVal.compare_lower("nan"))
2864 Value = APFloat::getNaN(Semantics, false, ~0);
2865 else
2866 return TokError("invalid floating point literal");
2867 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2868 APFloat::opInvalidOp)
2869 return TokError("invalid floating point literal");
2870 if (IsNeg)
2871 Value.changeSign();
2872
2873 // Consume the numeric token.
2874 Lex();
2875
2876 Res = Value.bitcastToAPInt();
2877
2878 return false;
2879}
2880
Jim Grosbach4b905842013-09-20 23:08:21 +00002881/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002882/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002883bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2884 const fltSemantics &Semantics) {
2885 auto parseOp = [&]() -> bool {
2886 APInt AsInt;
2887 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002888 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002889 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2890 AsInt.getBitWidth() / 8);
2891 return false;
2892 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00002893
Nirav Dave1a9044b2016-10-24 14:35:29 +00002894 if (parseMany(parseOp))
2895 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00002896 return false;
2897}
2898
Jim Grosbach4b905842013-09-20 23:08:21 +00002899/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002900/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002901bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002902 SMLoc NumBytesLoc = Lexer.getLoc();
2903 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002904 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002905 return true;
2906
Rafael Espindolab91bac62010-10-05 19:42:57 +00002907 int64_t Val = 0;
2908 if (getLexer().is(AsmToken::Comma)) {
2909 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002910 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002911 return true;
2912 }
2913
Nirav Davea645433c2016-07-18 15:24:03 +00002914 if (parseToken(AsmToken::EndOfStatement,
2915 "unexpected token in '.zero' directive"))
2916 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002917 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002918
2919 return false;
2920}
2921
Jim Grosbach4b905842013-09-20 23:08:21 +00002922/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002923/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002924bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002925 SMLoc NumValuesLoc = Lexer.getLoc();
2926 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002927 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002928 return true;
2929
Roman Divackye33098f2013-09-24 17:44:41 +00002930 int64_t FillSize = 1;
2931 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002932
David Majnemer522d3db2014-02-01 07:19:38 +00002933 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002934
Nirav Dave1a9044b2016-10-24 14:35:29 +00002935 if (parseOptionalToken(AsmToken::Comma)) {
2936 SizeLoc = getTok().getLoc();
2937 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002938 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002939 if (parseOptionalToken(AsmToken::Comma)) {
2940 ExprLoc = getTok().getLoc();
2941 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00002942 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002943 }
2944 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002945 if (parseToken(AsmToken::EndOfStatement,
2946 "unexpected token in '.fill' directive"))
2947 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002948
David Majnemer522d3db2014-02-01 07:19:38 +00002949 if (FillSize < 0) {
2950 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002951 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002952 }
2953 if (FillSize > 8) {
2954 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2955 FillSize = 8;
2956 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002957
David Majnemer522d3db2014-02-01 07:19:38 +00002958 if (!isUInt<32>(FillExpr) && FillSize > 4)
2959 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2960
Petr Hosek67a94a72016-05-28 05:57:48 +00002961 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002962
2963 return false;
2964}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002965
Jim Grosbach4b905842013-09-20 23:08:21 +00002966/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002967/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002968bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002969 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00002970 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00002971 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002972 return true;
2973
2974 // Parse optional fill expression.
2975 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002976 if (parseOptionalToken(AsmToken::Comma))
2977 if (parseAbsoluteExpression(FillExpr))
2978 return addErrorSuffix(" in '.org' directive");
2979 if (parseToken(AsmToken::EndOfStatement))
2980 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00002981
Oliver Stannard268f42f2016-12-14 10:43:58 +00002982 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002983 return false;
2984}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002985
Jim Grosbach4b905842013-09-20 23:08:21 +00002986/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002987/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002988bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002989 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002990 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002991 SMLoc MaxBytesLoc;
2992 bool HasFillExpr = false;
2993 int64_t FillExpr = 0;
2994 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002995
2996 auto parseAlign = [&]() -> bool {
2997 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00002998 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002999 if (parseOptionalToken(AsmToken::Comma)) {
3000 // The fill expression can be omitted while specifying a maximum number of
3001 // alignment bytes, e.g:
3002 // .align 3,,4
3003 if (getTok().isNot(AsmToken::Comma)) {
3004 HasFillExpr = true;
3005 if (parseAbsoluteExpression(FillExpr))
3006 return true;
3007 }
3008 if (parseOptionalToken(AsmToken::Comma))
3009 if (parseTokenLoc(MaxBytesLoc) ||
3010 parseAbsoluteExpression(MaxBytesToFill))
3011 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003012 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003013 return parseToken(AsmToken::EndOfStatement);
3014 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003015
Nirav Dave1a9044b2016-10-24 14:35:29 +00003016 if (parseAlign())
3017 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003018
Nirav Dave2364748a2016-09-16 18:30:20 +00003019 // Always emit an alignment here even if we thrown an error.
3020 bool ReturnVal = false;
3021
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003022 // Compute alignment in bytes.
3023 if (IsPow2) {
3024 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003025 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003026 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003027 Alignment = 31;
3028 }
3029
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003030 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003031 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003032 // Reject alignments that aren't either a power of two or zero,
3033 // for gas compatibility. Alignment of zero is silently rounded
3034 // up to one.
3035 if (Alignment == 0)
3036 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003037 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003038 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003039 }
3040
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003041 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003042 if (MaxBytesLoc.isValid()) {
3043 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003044 ReturnVal |= Error(MaxBytesLoc,
3045 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003046 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003047 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003048 }
3049
3050 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003051 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003052 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003053 MaxBytesToFill = 0;
3054 }
3055 }
3056
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003057 // Check whether we should use optimal code alignment for this .align
3058 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003059 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003060 assert(Section && "must have section to emit alignment");
3061 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003062 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3063 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003064 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003065 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003066 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003067 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3068 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003069 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003070
Nirav Dave2364748a2016-09-16 18:30:20 +00003071 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003072}
3073
Jim Grosbach4b905842013-09-20 23:08:21 +00003074/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003075/// ::= .file [number] filename
3076/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003077bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003078 // FIXME: I'm not sure what this is.
3079 int64_t FileNumber = -1;
3080 SMLoc FileNumberLoc = getLexer().getLoc();
3081 if (getLexer().is(AsmToken::Integer)) {
3082 FileNumber = getTok().getIntVal();
3083 Lex();
3084
3085 if (FileNumber < 1)
3086 return TokError("file number less than one");
3087 }
3088
Nirav Davea645433c2016-07-18 15:24:03 +00003089 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003090
3091 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003092 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003093 if (check(getTok().isNot(AsmToken::String),
3094 "unexpected token in '.file' directive") ||
3095 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003096 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003097
3098 StringRef Directory;
3099 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003100 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003101 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003102 if (check(FileNumber == -1,
3103 "explicit path specified, but no file number") ||
3104 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003105 return true;
3106 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003107 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003108 } else {
3109 Filename = Path;
3110 }
3111
Nirav Davea645433c2016-07-18 15:24:03 +00003112 if (parseToken(AsmToken::EndOfStatement,
3113 "unexpected token in '.file' directive"))
3114 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003115
3116 if (FileNumber == -1)
3117 getStreamer().EmitFileDirective(Filename);
3118 else {
David Blaikie22748082016-05-26 00:22:26 +00003119 // If there is -g option as well as debug info from directive file,
3120 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003121 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003122 getContext().setGenDwarfForAssembly(false);
3123 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003124 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003125 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003126 }
3127
3128 return false;
3129}
3130
Jim Grosbach4b905842013-09-20 23:08:21 +00003131/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003132/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003133bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003134 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003135 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003136 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3137 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003138 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003139 // FIXME: Do something with the .line.
3140 }
Nirav Davea645433c2016-07-18 15:24:03 +00003141 if (parseToken(AsmToken::EndOfStatement,
3142 "unexpected token in '.line' directive"))
3143 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003144
3145 return false;
3146}
3147
Jim Grosbach4b905842013-09-20 23:08:21 +00003148/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003149/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3150/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3151/// The first number is a file number, must have been previously assigned with
3152/// a .file directive, the second number is the line number and optionally the
3153/// third number is a column position (zero if not specified). The remaining
3154/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003155bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003156 int64_t FileNumber = 0, LineNumber = 0;
3157 SMLoc Loc = getTok().getLoc();
3158 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3159 check(FileNumber < 1, Loc,
3160 "file number less than one in '.loc' directive") ||
3161 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3162 "unassigned file number in '.loc' directive"))
3163 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003164
Nirav Davea645433c2016-07-18 15:24:03 +00003165 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003166 if (getLexer().is(AsmToken::Integer)) {
3167 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003168 if (LineNumber < 0)
3169 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003170 Lex();
3171 }
3172
3173 int64_t ColumnPos = 0;
3174 if (getLexer().is(AsmToken::Integer)) {
3175 ColumnPos = getTok().getIntVal();
3176 if (ColumnPos < 0)
3177 return TokError("column position less than zero in '.loc' directive");
3178 Lex();
3179 }
3180
3181 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3182 unsigned Isa = 0;
3183 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003184
Nirav Dave1a9044b2016-10-24 14:35:29 +00003185 auto parseLocOp = [&]() -> bool {
3186 StringRef Name;
3187 SMLoc Loc = getTok().getLoc();
3188 if (parseIdentifier(Name))
3189 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003190
Nirav Dave1a9044b2016-10-24 14:35:29 +00003191 if (Name == "basic_block")
3192 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3193 else if (Name == "prologue_end")
3194 Flags |= DWARF2_FLAG_PROLOGUE_END;
3195 else if (Name == "epilogue_begin")
3196 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3197 else if (Name == "is_stmt") {
3198 Loc = getTok().getLoc();
3199 const MCExpr *Value;
3200 if (parseExpression(Value))
3201 return true;
3202 // The expression must be the constant 0 or 1.
3203 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3204 int Value = MCE->getValue();
3205 if (Value == 0)
3206 Flags &= ~DWARF2_FLAG_IS_STMT;
3207 else if (Value == 1)
3208 Flags |= DWARF2_FLAG_IS_STMT;
3209 else
3210 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003211 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003212 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003213 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003214 } else if (Name == "isa") {
3215 Loc = getTok().getLoc();
3216 const MCExpr *Value;
3217 if (parseExpression(Value))
3218 return true;
3219 // The expression must be a constant greater or equal to 0.
3220 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3221 int Value = MCE->getValue();
3222 if (Value < 0)
3223 return Error(Loc, "isa number less than zero");
3224 Isa = Value;
3225 } else {
3226 return Error(Loc, "isa number not a constant value");
3227 }
3228 } else if (Name == "discriminator") {
3229 if (parseAbsoluteExpression(Discriminator))
3230 return true;
3231 } else {
3232 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003233 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003234 return false;
3235 };
3236
Nirav Davee2369aa2016-10-26 17:28:58 +00003237 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003238 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003239
3240 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3241 Isa, Discriminator, StringRef());
3242
3243 return false;
3244}
3245
Jim Grosbach4b905842013-09-20 23:08:21 +00003246/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003247/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003248bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003249 return TokError("unsupported directive '.stabs'");
3250}
3251
Reid Kleckner2214ed82016-01-29 00:49:42 +00003252/// parseDirectiveCVFile
3253/// ::= .cv_file number filename
3254bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003255 SMLoc FileNumberLoc = getTok().getLoc();
3256 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003257 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003258
3259 if (parseIntToken(FileNumber,
3260 "expected file number in '.cv_file' directive") ||
3261 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3262 check(getTok().isNot(AsmToken::String),
3263 "unexpected token in '.cv_file' directive") ||
3264 // Usually directory and filename are together, otherwise just
3265 // directory. Allow the strings to have escaped octal character sequence.
3266 parseEscapedString(Filename) ||
3267 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003268 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003269 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003270
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003271 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003272 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003273
3274 return false;
3275}
3276
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003277bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3278 StringRef DirectiveName) {
3279 SMLoc Loc;
3280 return parseTokenLoc(Loc) ||
3281 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3282 "' directive") ||
3283 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3284 "expected function id within range [0, UINT_MAX)");
3285}
3286
3287bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3288 SMLoc Loc;
3289 return parseTokenLoc(Loc) ||
3290 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3291 "' directive") ||
3292 check(FileNumber < 1, Loc, "file number less than one in '" +
3293 DirectiveName + "' directive") ||
3294 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3295 "unassigned file number in '" + DirectiveName + "' directive");
3296}
3297
3298/// parseDirectiveCVFuncId
3299/// ::= .cv_func_id FunctionId
3300///
3301/// Introduces a function ID that can be used with .cv_loc.
3302bool AsmParser::parseDirectiveCVFuncId() {
3303 SMLoc FunctionIdLoc = getTok().getLoc();
3304 int64_t FunctionId;
3305
3306 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3307 parseToken(AsmToken::EndOfStatement,
3308 "unexpected token in '.cv_func_id' directive"))
3309 return true;
3310
3311 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003312 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003313
3314 return false;
3315}
3316
3317/// parseDirectiveCVInlineSiteId
3318/// ::= .cv_inline_site_id FunctionId
3319/// "within" IAFunc
3320/// "inlined_at" IAFile IALine [IACol]
3321///
3322/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3323/// at" source location information for use in the line table of the caller,
3324/// whether the caller is a real function or another inlined call site.
3325bool AsmParser::parseDirectiveCVInlineSiteId() {
3326 SMLoc FunctionIdLoc = getTok().getLoc();
3327 int64_t FunctionId;
3328 int64_t IAFunc;
3329 int64_t IAFile;
3330 int64_t IALine;
3331 int64_t IACol = 0;
3332
3333 // FunctionId
3334 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3335 return true;
3336
3337 // "within"
3338 if (check((getLexer().isNot(AsmToken::Identifier) ||
3339 getTok().getIdentifier() != "within"),
3340 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3341 return true;
3342 Lex();
3343
3344 // IAFunc
3345 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3346 return true;
3347
3348 // "inlined_at"
3349 if (check((getLexer().isNot(AsmToken::Identifier) ||
3350 getTok().getIdentifier() != "inlined_at"),
3351 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3352 "directive") )
3353 return true;
3354 Lex();
3355
3356 // IAFile IALine
3357 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3358 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3359 return true;
3360
3361 // [IACol]
3362 if (getLexer().is(AsmToken::Integer)) {
3363 IACol = getTok().getIntVal();
3364 Lex();
3365 }
3366
3367 if (parseToken(AsmToken::EndOfStatement,
3368 "unexpected token in '.cv_inline_site_id' directive"))
3369 return true;
3370
3371 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3372 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003373 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003374
3375 return false;
3376}
3377
Reid Kleckner2214ed82016-01-29 00:49:42 +00003378/// parseDirectiveCVLoc
3379/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3380/// [is_stmt VALUE]
3381/// The first number is a file number, must have been previously assigned with
3382/// a .file directive, the second number is the line number and optionally the
3383/// third number is a column position (zero if not specified). The remaining
3384/// optional items are .loc sub-directives.
3385bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003386 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003387 SMLoc Loc;
3388 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003389 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3390 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003391 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003392
3393 int64_t LineNumber = 0;
3394 if (getLexer().is(AsmToken::Integer)) {
3395 LineNumber = getTok().getIntVal();
3396 if (LineNumber < 0)
3397 return TokError("line number less than zero in '.cv_loc' directive");
3398 Lex();
3399 }
3400
3401 int64_t ColumnPos = 0;
3402 if (getLexer().is(AsmToken::Integer)) {
3403 ColumnPos = getTok().getIntVal();
3404 if (ColumnPos < 0)
3405 return TokError("column position less than zero in '.cv_loc' directive");
3406 Lex();
3407 }
3408
3409 bool PrologueEnd = false;
3410 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003411
3412 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003413 StringRef Name;
3414 SMLoc Loc = getTok().getLoc();
3415 if (parseIdentifier(Name))
3416 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003417 if (Name == "prologue_end")
3418 PrologueEnd = true;
3419 else if (Name == "is_stmt") {
3420 Loc = getTok().getLoc();
3421 const MCExpr *Value;
3422 if (parseExpression(Value))
3423 return true;
3424 // The expression must be the constant 0 or 1.
3425 IsStmt = ~0ULL;
3426 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3427 IsStmt = MCE->getValue();
3428
3429 if (IsStmt > 1)
3430 return Error(Loc, "is_stmt value not 0 or 1");
3431 } else {
3432 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3433 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003434 return false;
3435 };
3436
3437 if (parseMany(parseOp, false /*hasComma*/))
3438 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003439
3440 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003441 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3442 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003443 return false;
3444}
3445
3446/// parseDirectiveCVLinetable
3447/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3448bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003449 int64_t FunctionId;
3450 StringRef FnStartName, FnEndName;
3451 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003452 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003453 parseToken(AsmToken::Comma,
3454 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003455 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3456 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003457 parseToken(AsmToken::Comma,
3458 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003459 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3460 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003461 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003462
3463 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3464 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3465
3466 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3467 return false;
3468}
3469
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003470/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003471/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003472bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003473 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3474 StringRef FnStartName, FnEndName;
3475 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003476 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003477 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003478 parseIntToken(
3479 SourceFileId,
3480 "expected SourceField in '.cv_inline_linetable' directive") ||
3481 check(SourceFileId <= 0, Loc,
3482 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003483 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003484 parseIntToken(
3485 SourceLineNum,
3486 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3487 check(SourceLineNum < 0, Loc,
3488 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003489 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3490 "expected identifier in directive") ||
3491 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3492 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003493 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003494
Nirav Davea645433c2016-07-18 15:24:03 +00003495 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3496 return true;
3497
3498 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3499 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003500 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3501 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003502 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003503 return false;
3504}
3505
David Majnemer408b5e62016-02-05 01:55:49 +00003506/// parseDirectiveCVDefRange
3507/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3508bool AsmParser::parseDirectiveCVDefRange() {
3509 SMLoc Loc;
3510 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3511 while (getLexer().is(AsmToken::Identifier)) {
3512 Loc = getLexer().getLoc();
3513 StringRef GapStartName;
3514 if (parseIdentifier(GapStartName))
3515 return Error(Loc, "expected identifier in directive");
3516 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3517
3518 Loc = getLexer().getLoc();
3519 StringRef GapEndName;
3520 if (parseIdentifier(GapEndName))
3521 return Error(Loc, "expected identifier in directive");
3522 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3523
3524 Ranges.push_back({GapStartSym, GapEndSym});
3525 }
3526
David Majnemer408b5e62016-02-05 01:55:49 +00003527 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003528 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3529 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003530 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003531
3532 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3533 return false;
3534}
3535
Reid Kleckner2214ed82016-01-29 00:49:42 +00003536/// parseDirectiveCVStringTable
3537/// ::= .cv_stringtable
3538bool AsmParser::parseDirectiveCVStringTable() {
3539 getStreamer().EmitCVStringTableDirective();
3540 return false;
3541}
3542
3543/// parseDirectiveCVFileChecksums
3544/// ::= .cv_filechecksums
3545bool AsmParser::parseDirectiveCVFileChecksums() {
3546 getStreamer().EmitCVFileChecksumsDirective();
3547 return false;
3548}
3549
Jim Grosbach4b905842013-09-20 23:08:21 +00003550/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003551/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003552bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003553 StringRef Name;
3554 bool EH = false;
3555 bool Debug = false;
3556
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003557 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003558 return TokError("Expected an identifier");
3559
3560 if (Name == ".eh_frame")
3561 EH = true;
3562 else if (Name == ".debug_frame")
3563 Debug = true;
3564
3565 if (getLexer().is(AsmToken::Comma)) {
3566 Lex();
3567
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003568 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003569 return TokError("Expected an identifier");
3570
3571 if (Name == ".eh_frame")
3572 EH = true;
3573 else if (Name == ".debug_frame")
3574 Debug = true;
3575 }
3576
3577 getStreamer().EmitCFISections(EH, Debug);
3578 return false;
3579}
3580
Jim Grosbach4b905842013-09-20 23:08:21 +00003581/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003582/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003583bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003584 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003585 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3586 if (check(parseIdentifier(Simple) || Simple != "simple",
3587 "unexpected token") ||
3588 parseToken(AsmToken::EndOfStatement))
3589 return addErrorSuffix(" in '.cfi_startproc' directive");
3590 }
Nirav Davea645433c2016-07-18 15:24:03 +00003591
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003592 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003593 return false;
3594}
3595
Jim Grosbach4b905842013-09-20 23:08:21 +00003596/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003597/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003598bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003599 getStreamer().EmitCFIEndProc();
3600 return false;
3601}
3602
Jim Grosbach4b905842013-09-20 23:08:21 +00003603/// \brief parse register name or number.
3604bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003605 SMLoc DirectiveLoc) {
3606 unsigned RegNo;
3607
3608 if (getLexer().isNot(AsmToken::Integer)) {
3609 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3610 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003611 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003612 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003613 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003614
3615 return false;
3616}
3617
Jim Grosbach4b905842013-09-20 23:08:21 +00003618/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003619/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003620bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003621 int64_t Register = 0, Offset = 0;
3622 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3623 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3624 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003625 return true;
3626
3627 getStreamer().EmitCFIDefCfa(Register, Offset);
3628 return false;
3629}
3630
Jim Grosbach4b905842013-09-20 23:08:21 +00003631/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003632/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003633bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003634 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003635 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003636 return true;
3637
3638 getStreamer().EmitCFIDefCfaOffset(Offset);
3639 return false;
3640}
3641
Jim Grosbach4b905842013-09-20 23:08:21 +00003642/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003643/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003644bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003645 int64_t Register1 = 0, Register2 = 0;
3646 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3647 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3648 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003649 return true;
3650
3651 getStreamer().EmitCFIRegister(Register1, Register2);
3652 return false;
3653}
3654
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003655/// parseDirectiveCFIWindowSave
3656/// ::= .cfi_window_save
3657bool AsmParser::parseDirectiveCFIWindowSave() {
3658 getStreamer().EmitCFIWindowSave();
3659 return false;
3660}
3661
Jim Grosbach4b905842013-09-20 23:08:21 +00003662/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003663/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003664bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003665 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003666 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003667 return true;
3668
3669 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3670 return false;
3671}
3672
Jim Grosbach4b905842013-09-20 23:08:21 +00003673/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003674/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003675bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003676 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003677 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003678 return true;
3679
3680 getStreamer().EmitCFIDefCfaRegister(Register);
3681 return false;
3682}
3683
Jim Grosbach4b905842013-09-20 23:08:21 +00003684/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003685/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003686bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003687 int64_t Register = 0;
3688 int64_t Offset = 0;
3689
Nirav Davea645433c2016-07-18 15:24:03 +00003690 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3691 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3692 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003693 return true;
3694
3695 getStreamer().EmitCFIOffset(Register, Offset);
3696 return false;
3697}
3698
Jim Grosbach4b905842013-09-20 23:08:21 +00003699/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003700/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003701bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003702 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003703
Nirav Davea645433c2016-07-18 15:24:03 +00003704 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3705 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3706 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003707 return true;
3708
3709 getStreamer().EmitCFIRelOffset(Register, Offset);
3710 return false;
3711}
3712
3713static bool isValidEncoding(int64_t Encoding) {
3714 if (Encoding & ~0xff)
3715 return false;
3716
3717 if (Encoding == dwarf::DW_EH_PE_omit)
3718 return true;
3719
3720 const unsigned Format = Encoding & 0xf;
3721 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3722 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3723 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3724 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3725 return false;
3726
3727 const unsigned Application = Encoding & 0x70;
3728 if (Application != dwarf::DW_EH_PE_absptr &&
3729 Application != dwarf::DW_EH_PE_pcrel)
3730 return false;
3731
3732 return true;
3733}
3734
Jim Grosbach4b905842013-09-20 23:08:21 +00003735/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003736/// IsPersonality true for cfi_personality, false for cfi_lsda
3737/// ::= .cfi_personality encoding, [symbol_name]
3738/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003739bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003740 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003741 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003742 return true;
3743 if (Encoding == dwarf::DW_EH_PE_omit)
3744 return false;
3745
Eli Bendersky17233942013-01-15 22:59:42 +00003746 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003747 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3748 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3749 check(parseIdentifier(Name), "expected identifier in directive"))
3750 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003751
Jim Grosbach6f482002015-05-18 18:43:14 +00003752 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003753
3754 if (IsPersonality)
3755 getStreamer().EmitCFIPersonality(Sym, Encoding);
3756 else
3757 getStreamer().EmitCFILsda(Sym, Encoding);
3758 return false;
3759}
3760
Jim Grosbach4b905842013-09-20 23:08:21 +00003761/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003762/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003763bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003764 getStreamer().EmitCFIRememberState();
3765 return false;
3766}
3767
Jim Grosbach4b905842013-09-20 23:08:21 +00003768/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003769/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003770bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003771 getStreamer().EmitCFIRestoreState();
3772 return false;
3773}
3774
Jim Grosbach4b905842013-09-20 23:08:21 +00003775/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003776/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003777bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003778 int64_t Register = 0;
3779
Jim Grosbach4b905842013-09-20 23:08:21 +00003780 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003781 return true;
3782
3783 getStreamer().EmitCFISameValue(Register);
3784 return false;
3785}
3786
Jim Grosbach4b905842013-09-20 23:08:21 +00003787/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003788/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003789bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003790 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003791 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003792 return true;
3793
3794 getStreamer().EmitCFIRestore(Register);
3795 return false;
3796}
3797
Jim Grosbach4b905842013-09-20 23:08:21 +00003798/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003799/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003800bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003801 std::string Values;
3802 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003803 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003804 return true;
3805
3806 Values.push_back((uint8_t)CurrValue);
3807
3808 while (getLexer().is(AsmToken::Comma)) {
3809 Lex();
3810
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003811 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003812 return true;
3813
3814 Values.push_back((uint8_t)CurrValue);
3815 }
3816
3817 getStreamer().EmitCFIEscape(Values);
3818 return false;
3819}
3820
Jim Grosbach4b905842013-09-20 23:08:21 +00003821/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003822/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003823bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003824 if (parseToken(AsmToken::EndOfStatement,
3825 "unexpected token in '.cfi_signal_frame'"))
3826 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003827
3828 getStreamer().EmitCFISignalFrame();
3829 return false;
3830}
3831
Jim Grosbach4b905842013-09-20 23:08:21 +00003832/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003833/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003834bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003835 int64_t Register = 0;
3836
Jim Grosbach4b905842013-09-20 23:08:21 +00003837 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003838 return true;
3839
3840 getStreamer().EmitCFIUndefined(Register);
3841 return false;
3842}
3843
Jim Grosbach4b905842013-09-20 23:08:21 +00003844/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003845/// ::= .macros_on
3846/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003847bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003848 if (parseToken(AsmToken::EndOfStatement,
3849 "unexpected token in '" + Directive + "' directive"))
3850 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003851
Jim Grosbach4b905842013-09-20 23:08:21 +00003852 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003853 return false;
3854}
3855
Jim Grosbach4b905842013-09-20 23:08:21 +00003856/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003857/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003858bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003859 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003860 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003861 return TokError("expected identifier in '.macro' directive");
3862
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003863 if (getLexer().is(AsmToken::Comma))
3864 Lex();
3865
Eli Bendersky17233942013-01-15 22:59:42 +00003866 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003867 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003868
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003869 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003870 return Error(Lexer.getLoc(),
3871 "Vararg parameter '" + Parameters.back().Name +
3872 "' should be last one in the list of parameters.");
3873
David Majnemer91fc4c22014-01-29 18:57:46 +00003874 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003875 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003876 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003877
Coby Tayreebedaae02017-04-08 20:29:03 +00003878 // Emit an error if two (or more) named parameters share the same name
3879 for (const MCAsmMacroParameter& CurrParam : Parameters)
3880 if (CurrParam.Name.equals(Parameter.Name))
3881 return TokError("macro '" + Name + "' has multiple parameters"
3882 " named '" + Parameter.Name + "'");
3883
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003884 if (Lexer.is(AsmToken::Colon)) {
3885 Lex(); // consume ':'
3886
3887 SMLoc QualLoc;
3888 StringRef Qualifier;
3889
3890 QualLoc = Lexer.getLoc();
3891 if (parseIdentifier(Qualifier))
3892 return Error(QualLoc, "missing parameter qualifier for "
3893 "'" + Parameter.Name + "' in macro '" + Name + "'");
3894
3895 if (Qualifier == "req")
3896 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003897 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003898 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003899 else
3900 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3901 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3902 }
3903
David Majnemer91fc4c22014-01-29 18:57:46 +00003904 if (getLexer().is(AsmToken::Equal)) {
3905 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003906
3907 SMLoc ParamLoc;
3908
3909 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003910 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003911 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003912
3913 if (Parameter.Required)
3914 Warning(ParamLoc, "pointless default value for required parameter "
3915 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003916 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003917
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003918 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003919
3920 if (getLexer().is(AsmToken::Comma))
3921 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003922 }
3923
Nirav Dave1180e6892016-06-02 17:15:05 +00003924 // Eat just the end of statement.
3925 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003926
Nirav Dave1180e6892016-06-02 17:15:05 +00003927 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003928 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003929 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003930 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003931 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003932 // Ignore Lexing errors in macros.
3933 while (Lexer.is(AsmToken::Error)) {
3934 Lexer.Lex();
3935 }
3936
Eli Bendersky17233942013-01-15 22:59:42 +00003937 // Check whether we have reached the end of the file.
3938 if (getLexer().is(AsmToken::Eof))
3939 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3940
3941 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003942 if (getLexer().is(AsmToken::Identifier)) {
3943 if (getTok().getIdentifier() == ".endm" ||
3944 getTok().getIdentifier() == ".endmacro") {
3945 if (MacroDepth == 0) { // Outermost macro.
3946 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003947 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003948 if (getLexer().isNot(AsmToken::EndOfStatement))
3949 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3950 "' directive");
3951 break;
3952 } else {
3953 // Otherwise we just found the end of an inner macro.
3954 --MacroDepth;
3955 }
3956 } else if (getTok().getIdentifier() == ".macro") {
3957 // We allow nested macros. Those aren't instantiated until the outermost
3958 // macro is expanded so just ignore them for now.
3959 ++MacroDepth;
3960 }
Eli Bendersky17233942013-01-15 22:59:42 +00003961 }
3962
3963 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003964 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003965 }
3966
Jim Grosbach4b905842013-09-20 23:08:21 +00003967 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003968 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3969 }
3970
3971 const char *BodyStart = StartToken.getLoc().getPointer();
3972 const char *BodyEnd = EndToken.getLoc().getPointer();
3973 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003974 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003975 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003976 return false;
3977}
3978
Jim Grosbach4b905842013-09-20 23:08:21 +00003979/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003980///
3981/// With the support added for named parameters there may be code out there that
3982/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003983/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003984/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003985/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003986/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3987/// warning that the positional parameter found in body which have no effect.
3988/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003989/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003990/// intended or change the macro to use the named parameters. It is possible
3991/// this warning will trigger when the none of the named parameters are used
3992/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003993void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003994 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003995 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003996 // If this macro is not defined with named parameters the warning we are
3997 // checking for here doesn't apply.
3998 unsigned NParameters = Parameters.size();
3999 if (NParameters == 0)
4000 return;
4001
4002 bool NamedParametersFound = false;
4003 bool PositionalParametersFound = false;
4004
4005 // Look at the body of the macro for use of both the named parameters and what
4006 // are likely to be positional parameters. This is what expandMacro() is
4007 // doing when it finds the parameters in the body.
4008 while (!Body.empty()) {
4009 // Scan for the next possible parameter.
4010 std::size_t End = Body.size(), Pos = 0;
4011 for (; Pos != End; ++Pos) {
4012 // Check for a substitution or escape.
4013 // This macro is defined with parameters, look for \foo, \bar, etc.
4014 if (Body[Pos] == '\\' && Pos + 1 != End)
4015 break;
4016
4017 // This macro should have parameters, but look for $0, $1, ..., $n too.
4018 if (Body[Pos] != '$' || Pos + 1 == End)
4019 continue;
4020 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004021 if (Next == '$' || Next == 'n' ||
4022 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004023 break;
4024 }
4025
4026 // Check if we reached the end.
4027 if (Pos == End)
4028 break;
4029
4030 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004031 switch (Body[Pos + 1]) {
4032 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004033 case '$':
4034 break;
4035
Jim Grosbach4b905842013-09-20 23:08:21 +00004036 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004037 case 'n':
4038 PositionalParametersFound = true;
4039 break;
4040
Jim Grosbach4b905842013-09-20 23:08:21 +00004041 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004042 default: {
4043 PositionalParametersFound = true;
4044 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004045 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004046 }
4047 Pos += 2;
4048 } else {
4049 unsigned I = Pos + 1;
4050 while (isIdentifierChar(Body[I]) && I + 1 != End)
4051 ++I;
4052
Jim Grosbach4b905842013-09-20 23:08:21 +00004053 const char *Begin = Body.data() + Pos + 1;
4054 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004055 unsigned Index = 0;
4056 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004057 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004058 break;
4059
4060 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004061 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4062 Pos += 3;
4063 else {
4064 Pos = I;
4065 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004066 } else {
4067 NamedParametersFound = true;
4068 Pos += 1 + Argument.size();
4069 }
4070 }
4071 // Update the scan point.
4072 Body = Body.substr(Pos);
4073 }
4074
4075 if (!NamedParametersFound && PositionalParametersFound)
4076 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4077 "used in macro body, possible positional parameter "
4078 "found in body which will have no effect");
4079}
4080
Nico Weber155dccd12014-07-24 17:08:39 +00004081/// parseDirectiveExitMacro
4082/// ::= .exitm
4083bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004084 if (parseToken(AsmToken::EndOfStatement,
4085 "unexpected token in '" + Directive + "' directive"))
4086 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004087
4088 if (!isInsideMacroInstantiation())
4089 return TokError("unexpected '" + Directive + "' in file, "
4090 "no current macro definition");
4091
4092 // Exit all conditionals that are active in the current macro.
4093 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4094 TheCondState = TheCondStack.back();
4095 TheCondStack.pop_back();
4096 }
4097
4098 handleMacroExit();
4099 return false;
4100}
4101
Jim Grosbach4b905842013-09-20 23:08:21 +00004102/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004103/// ::= .endm
4104/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004105bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004106 if (getLexer().isNot(AsmToken::EndOfStatement))
4107 return TokError("unexpected token in '" + Directive + "' directive");
4108
4109 // If we are inside a macro instantiation, terminate the current
4110 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004111 if (isInsideMacroInstantiation()) {
4112 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004113 return false;
4114 }
4115
4116 // Otherwise, this .endmacro is a stray entry in the file; well formed
4117 // .endmacro directives are handled during the macro definition parsing.
4118 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004119 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004120}
4121
Jim Grosbach4b905842013-09-20 23:08:21 +00004122/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004123/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004124bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004125 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004126 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004127 if (parseTokenLoc(Loc) ||
4128 check(parseIdentifier(Name), Loc,
4129 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004130 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004131 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004132 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004133
Nirav Dave1ab71992016-07-18 19:35:21 +00004134 if (!lookupMacro(Name))
4135 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4136
Jim Grosbach4b905842013-09-20 23:08:21 +00004137 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004138 return false;
4139}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004140
Jim Grosbach4b905842013-09-20 23:08:21 +00004141/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004142/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004143bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004144 // Expect a single argument: an expression that evaluates to a constant
4145 // in the inclusive range 0-30.
4146 SMLoc ExprLoc = getLexer().getLoc();
4147 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004148 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004149 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4150 "in '.bundle_align_mode' "
4151 "directive") ||
4152 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4153 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004154 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004155
4156 // Because of AlignSizePow2's verified range we can safely truncate it to
4157 // unsigned.
4158 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4159 return false;
4160}
4161
Jim Grosbach4b905842013-09-20 23:08:21 +00004162/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004163/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004164bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004165 if (checkForValidSection())
4166 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004167 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004168
Nirav Dave1a9044b2016-10-24 14:35:29 +00004169 StringRef Option;
4170 SMLoc Loc = getTok().getLoc();
4171 const char *kInvalidOptionError =
4172 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004173
Nirav Dave1a9044b2016-10-24 14:35:29 +00004174 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004175 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4176 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004177 parseToken(AsmToken::EndOfStatement,
4178 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004179 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004180 AlignToEnd = true;
4181 }
4182
Eli Bendersky802b6282013-01-07 21:51:08 +00004183 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004184 return false;
4185}
4186
Jim Grosbach4b905842013-09-20 23:08:21 +00004187/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004188/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004189bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004190 if (checkForValidSection() ||
4191 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004192 "unexpected token in '.bundle_unlock' directive"))
4193 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004194
4195 getStreamer().EmitBundleUnlock();
4196 return false;
4197}
4198
Jim Grosbach4b905842013-09-20 23:08:21 +00004199/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004200/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004201bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004202 SMLoc NumBytesLoc = Lexer.getLoc();
4203 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004204 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004205 return true;
4206
4207 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004208 if (parseOptionalToken(AsmToken::Comma))
4209 if (parseAbsoluteExpression(FillExpr))
4210 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4211 if (parseToken(AsmToken::EndOfStatement))
4212 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004213
Eli Bendersky17233942013-01-15 22:59:42 +00004214 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004215 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004216
4217 return false;
4218}
4219
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004220/// parseDirectiveDCB
4221/// ::= .dcb.{b, l, w} expression, expression
4222bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004223 SMLoc NumValuesLoc = Lexer.getLoc();
4224 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004225 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004226 return true;
4227
4228 if (NumValues < 0) {
4229 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4230 return false;
4231 }
4232
4233 if (parseToken(AsmToken::Comma,
4234 "unexpected token in '" + Twine(IDVal) + "' directive"))
4235 return true;
4236
4237 const MCExpr *Value;
4238 SMLoc ExprLoc = getLexer().getLoc();
4239 if (parseExpression(Value))
4240 return true;
4241
4242 // Special case constant expressions to match code generator.
4243 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4244 assert(Size <= 8 && "Invalid size");
4245 uint64_t IntValue = MCE->getValue();
4246 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4247 return Error(ExprLoc, "literal value out of range for directive");
4248 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4249 getStreamer().EmitIntValue(IntValue, Size);
4250 } else {
4251 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4252 getStreamer().EmitValue(Value, Size, ExprLoc);
4253 }
4254
4255 if (parseToken(AsmToken::EndOfStatement,
4256 "unexpected token in '" + Twine(IDVal) + "' directive"))
4257 return true;
4258
4259 return false;
4260}
4261
4262/// parseDirectiveRealDCB
4263/// ::= .dcb.{d, s} expression, expression
4264bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004265 SMLoc NumValuesLoc = Lexer.getLoc();
4266 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004267 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004268 return true;
4269
4270 if (NumValues < 0) {
4271 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4272 return false;
4273 }
4274
4275 if (parseToken(AsmToken::Comma,
4276 "unexpected token in '" + Twine(IDVal) + "' directive"))
4277 return true;
4278
4279 APInt AsInt;
4280 if (parseRealValue(Semantics, AsInt))
4281 return true;
4282
4283 if (parseToken(AsmToken::EndOfStatement,
4284 "unexpected token in '" + Twine(IDVal) + "' directive"))
4285 return true;
4286
4287 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4288 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4289 AsInt.getBitWidth() / 8);
4290
4291 return false;
4292}
4293
Petr Hosek85b2f672016-09-23 21:53:36 +00004294/// parseDirectiveDS
4295/// ::= .ds.{b, d, l, p, s, w, x} expression
4296bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004297 SMLoc NumValuesLoc = Lexer.getLoc();
4298 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004299 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004300 return true;
4301
4302 if (NumValues < 0) {
4303 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4304 return false;
4305 }
4306
4307 if (parseToken(AsmToken::EndOfStatement,
4308 "unexpected token in '" + Twine(IDVal) + "' directive"))
4309 return true;
4310
4311 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4312 getStreamer().emitFill(Size, 0);
4313
4314 return false;
4315}
4316
Jim Grosbach4b905842013-09-20 23:08:21 +00004317/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004318/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004319bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004320 if (checkForValidSection())
4321 return true;
4322
Nirav Dave1a9044b2016-10-24 14:35:29 +00004323 auto parseOp = [&]() -> bool {
4324 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004325 if (parseExpression(Value))
4326 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004327 if (Signed)
4328 getStreamer().EmitSLEB128Value(Value);
4329 else
4330 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004331 return false;
4332 };
Eli Bendersky17233942013-01-15 22:59:42 +00004333
Nirav Dave1a9044b2016-10-24 14:35:29 +00004334 if (parseMany(parseOp))
4335 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004336
4337 return false;
4338}
4339
Jim Grosbach4b905842013-09-20 23:08:21 +00004340/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004341/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004342bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004343 auto parseOp = [&]() -> bool {
4344 StringRef Name;
4345 SMLoc Loc = getTok().getLoc();
4346 if (parseIdentifier(Name))
4347 return Error(Loc, "expected identifier");
4348 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004349
Nirav Dave1a9044b2016-10-24 14:35:29 +00004350 // Assembler local symbols don't make any sense here. Complain loudly.
4351 if (Sym->isTemporary())
4352 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004353
Nirav Dave1a9044b2016-10-24 14:35:29 +00004354 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4355 return Error(Loc, "unable to emit symbol attribute");
4356 return false;
4357 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004358
Nirav Dave1a9044b2016-10-24 14:35:29 +00004359 if (parseMany(parseOp))
4360 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004361 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004362}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004363
Jim Grosbach4b905842013-09-20 23:08:21 +00004364/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004365/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004366bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004367 if (checkForValidSection())
4368 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004369
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004370 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004371 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004372 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004373 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004374
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004375 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004376 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004377
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004378 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004379 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004380 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004381
4382 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004383 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004384 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004385 return true;
4386
4387 int64_t Pow2Alignment = 0;
4388 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004389 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004390 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004391 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004392 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004393 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004394
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004395 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4396 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004397 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4398
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004399 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004400 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4401 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004402 if (!isPowerOf2_64(Pow2Alignment))
4403 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4404 Pow2Alignment = Log2_64(Pow2Alignment);
4405 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004406 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004407
Nirav Dave1a9044b2016-10-24 14:35:29 +00004408 if (parseToken(AsmToken::EndOfStatement,
4409 "unexpected token in '.comm' or '.lcomm' directive"))
4410 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004411
Chris Lattner28ad7542009-07-09 17:25:12 +00004412 // NOTE: a size of zero for a .comm should create a undefined symbol
4413 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004414 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004415 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004416 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004417
Eric Christopherbc818852010-05-14 01:38:54 +00004418 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004419 // may internally end up wanting an alignment in bytes.
4420 // FIXME: Diagnose overflow.
4421 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004422 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004423 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004424
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004425 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004426 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004427 return Error(IDLoc, "invalid symbol redefinition");
4428
Chris Lattner28ad7542009-07-09 17:25:12 +00004429 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004430 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004431 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004432 return false;
4433 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004434
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004435 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004436 return false;
4437}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004438
Jim Grosbach4b905842013-09-20 23:08:21 +00004439/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004440/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004441bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004442 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004443 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004444
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004445 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004446 if (parseToken(AsmToken::EndOfStatement,
4447 "unexpected token in '.abort' directive"))
4448 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004449
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004450 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004451 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004452 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004453 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004454 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004455
4456 return false;
4457}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004458
Jim Grosbach4b905842013-09-20 23:08:21 +00004459/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004460/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004461bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004462 // Allow the strings to have escaped octal character sequence.
4463 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004464 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004465
Nirav Davea645433c2016-07-18 15:24:03 +00004466 if (check(getTok().isNot(AsmToken::String),
4467 "expected string in '.include' directive") ||
4468 parseEscapedString(Filename) ||
4469 check(getTok().isNot(AsmToken::EndOfStatement),
4470 "unexpected token in '.include' directive") ||
4471 // Attempt to switch the lexer to the included file before consuming the
4472 // end of statement to avoid losing it when we switch.
4473 check(enterIncludeFile(Filename), IncludeLoc,
4474 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004475 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004476
4477 return false;
4478}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004479
Jim Grosbach4b905842013-09-20 23:08:21 +00004480/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004481/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004482bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004483 // Allow the strings to have escaped octal character sequence.
4484 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004485 SMLoc IncbinLoc = getTok().getLoc();
4486 if (check(getTok().isNot(AsmToken::String),
4487 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004488 parseEscapedString(Filename))
4489 return true;
4490
4491 int64_t Skip = 0;
4492 const MCExpr *Count = nullptr;
4493 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004494 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004495 // The skip expression can be omitted while specifying the count, e.g:
4496 // .incbin "filename",,4
4497 if (getTok().isNot(AsmToken::Comma)) {
4498 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4499 return true;
4500 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004501 if (parseOptionalToken(AsmToken::Comma)) {
4502 CountLoc = getTok().getLoc();
4503 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004504 return true;
4505 }
4506 }
4507
4508 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004509 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004510 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004511
Petr Hosek2f4ac442016-09-23 00:41:06 +00004512 if (check(Skip < 0, SkipLoc, "skip is negative"))
4513 return true;
4514
Nirav Dave1ab71992016-07-18 19:35:21 +00004515 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004516 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004517 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004518 return false;
4519}
4520
Jim Grosbach4b905842013-09-20 23:08:21 +00004521/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004522/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4523bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004524 TheCondStack.push_back(TheCondState);
4525 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004526 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004527 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004528 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004529 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004530 if (parseAbsoluteExpression(ExprValue) ||
4531 parseToken(AsmToken::EndOfStatement,
4532 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004533 return true;
4534
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004535 switch (DirKind) {
4536 default:
4537 llvm_unreachable("unsupported directive");
4538 case DK_IF:
4539 case DK_IFNE:
4540 break;
4541 case DK_IFEQ:
4542 ExprValue = ExprValue == 0;
4543 break;
4544 case DK_IFGE:
4545 ExprValue = ExprValue >= 0;
4546 break;
4547 case DK_IFGT:
4548 ExprValue = ExprValue > 0;
4549 break;
4550 case DK_IFLE:
4551 ExprValue = ExprValue <= 0;
4552 break;
4553 case DK_IFLT:
4554 ExprValue = ExprValue < 0;
4555 break;
4556 }
4557
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004558 TheCondState.CondMet = ExprValue;
4559 TheCondState.Ignore = !TheCondState.CondMet;
4560 }
4561
4562 return false;
4563}
4564
Jim Grosbach4b905842013-09-20 23:08:21 +00004565/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004566/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004567bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004568 TheCondStack.push_back(TheCondState);
4569 TheCondState.TheCond = AsmCond::IfCond;
4570
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004571 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004572 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004573 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004574 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004575
Nirav Davea645433c2016-07-18 15:24:03 +00004576 if (parseToken(AsmToken::EndOfStatement,
4577 "unexpected token in '.ifb' directive"))
4578 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004579
4580 TheCondState.CondMet = ExpectBlank == Str.empty();
4581 TheCondState.Ignore = !TheCondState.CondMet;
4582 }
4583
4584 return false;
4585}
4586
Jim Grosbach4b905842013-09-20 23:08:21 +00004587/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004588/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004589/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004590bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004591 TheCondStack.push_back(TheCondState);
4592 TheCondState.TheCond = AsmCond::IfCond;
4593
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004594 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004595 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004596 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004597 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004598
Nirav Davea645433c2016-07-18 15:24:03 +00004599 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4600 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004601
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004602 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004603
Nirav Davea645433c2016-07-18 15:24:03 +00004604 if (parseToken(AsmToken::EndOfStatement,
4605 "unexpected token in '.ifc' directive"))
4606 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004607
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004608 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004609 TheCondState.Ignore = !TheCondState.CondMet;
4610 }
4611
4612 return false;
4613}
4614
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004615/// parseDirectiveIfeqs
4616/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004617bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004618 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004619 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004620 return TokError("expected string parameter for '.ifeqs' directive");
4621 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004622 }
4623
4624 StringRef String1 = getTok().getStringContents();
4625 Lex();
4626
4627 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004628 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004629 return TokError(
4630 "expected comma after first string for '.ifeqs' directive");
4631 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004632 }
4633
4634 Lex();
4635
4636 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004637 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004638 return TokError("expected string parameter for '.ifeqs' directive");
4639 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004640 }
4641
4642 StringRef String2 = getTok().getStringContents();
4643 Lex();
4644
4645 TheCondStack.push_back(TheCondState);
4646 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004647 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004648 TheCondState.Ignore = !TheCondState.CondMet;
4649
4650 return false;
4651}
4652
Jim Grosbach4b905842013-09-20 23:08:21 +00004653/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004654/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004655bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004656 StringRef Name;
4657 TheCondStack.push_back(TheCondState);
4658 TheCondState.TheCond = AsmCond::IfCond;
4659
4660 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004661 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004662 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004663 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4664 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4665 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004666
Jim Grosbach6f482002015-05-18 18:43:14 +00004667 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004668
4669 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004670 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004671 else
Craig Topper353eda42014-04-24 06:44:33 +00004672 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004673 TheCondState.Ignore = !TheCondState.CondMet;
4674 }
4675
4676 return false;
4677}
4678
Jim Grosbach4b905842013-09-20 23:08:21 +00004679/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004680/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004681bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004682 if (TheCondState.TheCond != AsmCond::IfCond &&
4683 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004684 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4685 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004686 TheCondState.TheCond = AsmCond::ElseIfCond;
4687
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004688 bool LastIgnoreState = false;
4689 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004690 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004691 if (LastIgnoreState || TheCondState.CondMet) {
4692 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004693 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004694 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004695 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004696 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004697 return true;
4698
Nirav Dave1a9044b2016-10-24 14:35:29 +00004699 if (parseToken(AsmToken::EndOfStatement,
4700 "unexpected token in '.elseif' directive"))
4701 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004702
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004703 TheCondState.CondMet = ExprValue;
4704 TheCondState.Ignore = !TheCondState.CondMet;
4705 }
4706
4707 return false;
4708}
4709
Jim Grosbach4b905842013-09-20 23:08:21 +00004710/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004711/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004712bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004713 if (parseToken(AsmToken::EndOfStatement,
4714 "unexpected token in '.else' directive"))
4715 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004716
4717 if (TheCondState.TheCond != AsmCond::IfCond &&
4718 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004719 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4720 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004721 TheCondState.TheCond = AsmCond::ElseCond;
4722 bool LastIgnoreState = false;
4723 if (!TheCondStack.empty())
4724 LastIgnoreState = TheCondStack.back().Ignore;
4725 if (LastIgnoreState || TheCondState.CondMet)
4726 TheCondState.Ignore = true;
4727 else
4728 TheCondState.Ignore = false;
4729
4730 return false;
4731}
4732
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004733/// parseDirectiveEnd
4734/// ::= .end
4735bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004736 if (parseToken(AsmToken::EndOfStatement,
4737 "unexpected token in '.end' directive"))
4738 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004739
4740 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004741 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004742
4743 return false;
4744}
4745
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004746/// parseDirectiveError
4747/// ::= .err
4748/// ::= .error [string]
4749bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4750 if (!TheCondStack.empty()) {
4751 if (TheCondStack.back().Ignore) {
4752 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004753 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004754 }
4755 }
4756
4757 if (!WithMessage)
4758 return Error(L, ".err encountered");
4759
4760 StringRef Message = ".error directive invoked in source file";
4761 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004762 if (Lexer.isNot(AsmToken::String))
4763 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004764
4765 Message = getTok().getStringContents();
4766 Lex();
4767 }
4768
Nirav Dave2364748a2016-09-16 18:30:20 +00004769 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004770}
4771
Nico Weber404012b2014-07-24 16:26:06 +00004772/// parseDirectiveWarning
4773/// ::= .warning [string]
4774bool AsmParser::parseDirectiveWarning(SMLoc L) {
4775 if (!TheCondStack.empty()) {
4776 if (TheCondStack.back().Ignore) {
4777 eatToEndOfStatement();
4778 return false;
4779 }
4780 }
4781
4782 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00004783
4784 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004785 if (Lexer.isNot(AsmToken::String))
4786 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004787
4788 Message = getTok().getStringContents();
4789 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00004790 if (parseToken(AsmToken::EndOfStatement,
4791 "expected end of statement in '.warning' directive"))
4792 return true;
Nico Weber404012b2014-07-24 16:26:06 +00004793 }
4794
Nirav Dave2364748a2016-09-16 18:30:20 +00004795 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004796}
4797
Jim Grosbach4b905842013-09-20 23:08:21 +00004798/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004799/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004800bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004801 if (parseToken(AsmToken::EndOfStatement,
4802 "unexpected token in '.endif' directive"))
4803 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004804
Jim Grosbach4b905842013-09-20 23:08:21 +00004805 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004806 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4807 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004808 if (!TheCondStack.empty()) {
4809 TheCondState = TheCondStack.back();
4810 TheCondStack.pop_back();
4811 }
4812
4813 return false;
4814}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004815
Eli Bendersky17233942013-01-15 22:59:42 +00004816void AsmParser::initializeDirectiveKindMap() {
4817 DirectiveKindMap[".set"] = DK_SET;
4818 DirectiveKindMap[".equ"] = DK_EQU;
4819 DirectiveKindMap[".equiv"] = DK_EQUIV;
4820 DirectiveKindMap[".ascii"] = DK_ASCII;
4821 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4822 DirectiveKindMap[".string"] = DK_STRING;
4823 DirectiveKindMap[".byte"] = DK_BYTE;
4824 DirectiveKindMap[".short"] = DK_SHORT;
4825 DirectiveKindMap[".value"] = DK_VALUE;
4826 DirectiveKindMap[".2byte"] = DK_2BYTE;
4827 DirectiveKindMap[".long"] = DK_LONG;
4828 DirectiveKindMap[".int"] = DK_INT;
4829 DirectiveKindMap[".4byte"] = DK_4BYTE;
4830 DirectiveKindMap[".quad"] = DK_QUAD;
4831 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004832 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004833 DirectiveKindMap[".single"] = DK_SINGLE;
4834 DirectiveKindMap[".float"] = DK_FLOAT;
4835 DirectiveKindMap[".double"] = DK_DOUBLE;
4836 DirectiveKindMap[".align"] = DK_ALIGN;
4837 DirectiveKindMap[".align32"] = DK_ALIGN32;
4838 DirectiveKindMap[".balign"] = DK_BALIGN;
4839 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4840 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4841 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4842 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4843 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4844 DirectiveKindMap[".org"] = DK_ORG;
4845 DirectiveKindMap[".fill"] = DK_FILL;
4846 DirectiveKindMap[".zero"] = DK_ZERO;
4847 DirectiveKindMap[".extern"] = DK_EXTERN;
4848 DirectiveKindMap[".globl"] = DK_GLOBL;
4849 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004850 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4851 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4852 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4853 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4854 DirectiveKindMap[".reference"] = DK_REFERENCE;
4855 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4856 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4857 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4858 DirectiveKindMap[".comm"] = DK_COMM;
4859 DirectiveKindMap[".common"] = DK_COMMON;
4860 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4861 DirectiveKindMap[".abort"] = DK_ABORT;
4862 DirectiveKindMap[".include"] = DK_INCLUDE;
4863 DirectiveKindMap[".incbin"] = DK_INCBIN;
4864 DirectiveKindMap[".code16"] = DK_CODE16;
4865 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4866 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004867 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004868 DirectiveKindMap[".irp"] = DK_IRP;
4869 DirectiveKindMap[".irpc"] = DK_IRPC;
4870 DirectiveKindMap[".endr"] = DK_ENDR;
4871 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4872 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4873 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4874 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004875 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4876 DirectiveKindMap[".ifge"] = DK_IFGE;
4877 DirectiveKindMap[".ifgt"] = DK_IFGT;
4878 DirectiveKindMap[".ifle"] = DK_IFLE;
4879 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004880 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004881 DirectiveKindMap[".ifb"] = DK_IFB;
4882 DirectiveKindMap[".ifnb"] = DK_IFNB;
4883 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004884 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004885 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004886 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004887 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4888 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4889 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4890 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4891 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004892 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004893 DirectiveKindMap[".endif"] = DK_ENDIF;
4894 DirectiveKindMap[".skip"] = DK_SKIP;
4895 DirectiveKindMap[".space"] = DK_SPACE;
4896 DirectiveKindMap[".file"] = DK_FILE;
4897 DirectiveKindMap[".line"] = DK_LINE;
4898 DirectiveKindMap[".loc"] = DK_LOC;
4899 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004900 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004901 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004902 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4903 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004904 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004905 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00004906 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004907 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4908 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004909 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4910 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4911 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4912 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4913 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4914 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4915 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4916 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4917 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4918 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4919 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4920 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4921 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4922 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4923 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4924 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4925 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4926 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4927 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4928 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4929 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004930 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004931 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4932 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4933 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004934 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004935 DirectiveKindMap[".endm"] = DK_ENDM;
4936 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4937 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004938 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004939 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004940 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004941 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00004942 DirectiveKindMap[".dc"] = DK_DC;
4943 DirectiveKindMap[".dc.a"] = DK_DC_A;
4944 DirectiveKindMap[".dc.b"] = DK_DC_B;
4945 DirectiveKindMap[".dc.d"] = DK_DC_D;
4946 DirectiveKindMap[".dc.l"] = DK_DC_L;
4947 DirectiveKindMap[".dc.s"] = DK_DC_S;
4948 DirectiveKindMap[".dc.w"] = DK_DC_W;
4949 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004950 DirectiveKindMap[".dcb"] = DK_DCB;
4951 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4952 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4953 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4954 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4955 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4956 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00004957 DirectiveKindMap[".ds"] = DK_DS;
4958 DirectiveKindMap[".ds.b"] = DK_DS_B;
4959 DirectiveKindMap[".ds.d"] = DK_DS_D;
4960 DirectiveKindMap[".ds.l"] = DK_DS_L;
4961 DirectiveKindMap[".ds.p"] = DK_DS_P;
4962 DirectiveKindMap[".ds.s"] = DK_DS_S;
4963 DirectiveKindMap[".ds.w"] = DK_DS_W;
4964 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004965}
4966
Jim Grosbach4b905842013-09-20 23:08:21 +00004967MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004968 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004969
Rafael Espindola34b9c512012-06-03 23:57:14 +00004970 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004971 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004972 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004973 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004974 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004975 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004976 }
4977
Rafael Espindola34b9c512012-06-03 23:57:14 +00004978 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004979 (getTok().getIdentifier() == ".rept" ||
4980 getTok().getIdentifier() == ".irp" ||
4981 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004982 ++NestLevel;
4983 }
4984
4985 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004986 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004987 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004988 EndToken = getTok();
4989 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004990 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004991 printError(getTok().getLoc(),
4992 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004993 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004994 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004995 break;
4996 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004997 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004998 }
4999
Rafael Espindola34b9c512012-06-03 23:57:14 +00005000 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005001 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005002 }
5003
5004 const char *BodyStart = StartToken.getLoc().getPointer();
5005 const char *BodyEnd = EndToken.getLoc().getPointer();
5006 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5007
Rafael Espindola34b9c512012-06-03 23:57:14 +00005008 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005009 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005010 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005011}
5012
Jim Grosbach4b905842013-09-20 23:08:21 +00005013void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005014 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005015 OS << ".endr\n";
5016
Rafael Espindola3560ff22014-08-27 20:03:13 +00005017 std::unique_ptr<MemoryBuffer> Instantiation =
5018 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005019
Rafael Espindola34b9c512012-06-03 23:57:14 +00005020 // Create the macro instantiation object and add to the current macro
5021 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005022 MacroInstantiation *MI = new MacroInstantiation(
5023 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005024 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005025
Rafael Espindola34b9c512012-06-03 23:57:14 +00005026 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005027 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005028 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005029 Lex();
5030}
5031
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005032/// parseDirectiveRept
5033/// ::= .rep | .rept count
5034bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005035 const MCExpr *CountExpr;
5036 SMLoc CountLoc = getTok().getLoc();
5037 if (parseExpression(CountExpr))
5038 return true;
5039
Rafael Espindola34b9c512012-06-03 23:57:14 +00005040 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005041 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005042 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5043 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005044
Nirav Davea645433c2016-07-18 15:24:03 +00005045 if (check(Count < 0, CountLoc, "Count is negative") ||
5046 parseToken(AsmToken::EndOfStatement,
5047 "unexpected token in '" + Dir + "' directive"))
5048 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005049
5050 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005051 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005052 if (!M)
5053 return true;
5054
5055 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5056 // to hold the macro body with substitutions.
5057 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005058 raw_svector_ostream OS(Buf);
5059 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005060 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5061 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005062 return true;
5063 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005064 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005065
5066 return false;
5067}
5068
Jim Grosbach4b905842013-09-20 23:08:21 +00005069/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005070/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005071bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005072 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005073 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005074 if (check(parseIdentifier(Parameter.Name),
5075 "expected identifier in '.irp' directive") ||
5076 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5077 parseMacroArguments(nullptr, A) ||
5078 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005079 return true;
5080
Rafael Espindola768b41c2012-06-15 14:02:34 +00005081 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005082 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005083 if (!M)
5084 return true;
5085
5086 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5087 // to hold the macro body with substitutions.
5088 SmallString<256> Buf;
5089 raw_svector_ostream OS(Buf);
5090
Craig Topper84008482015-10-10 05:38:14 +00005091 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005092 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5093 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005094 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005095 return true;
5096 }
5097
Jim Grosbach4b905842013-09-20 23:08:21 +00005098 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005099
5100 return false;
5101}
5102
Jim Grosbach4b905842013-09-20 23:08:21 +00005103/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005104/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005105bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005106 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005107 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005108
5109 if (check(parseIdentifier(Parameter.Name),
5110 "expected identifier in '.irpc' directive") ||
5111 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5112 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005113 return true;
5114
5115 if (A.size() != 1 || A.front().size() != 1)
5116 return TokError("unexpected token in '.irpc' directive");
5117
5118 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005119 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5120 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005121
5122 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005123 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005124 if (!M)
5125 return true;
5126
5127 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5128 // to hold the macro body with substitutions.
5129 SmallString<256> Buf;
5130 raw_svector_ostream OS(Buf);
5131
5132 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005133 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005134 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005135 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005136
Toma Tabacu217116e2015-04-27 10:50:29 +00005137 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5138 // This is undocumented, but GAS seems to support it.
5139 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005140 return true;
5141 }
5142
Jim Grosbach4b905842013-09-20 23:08:21 +00005143 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005144
5145 return false;
5146}
5147
Jim Grosbach4b905842013-09-20 23:08:21 +00005148bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005149 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005150 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005151
5152 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005153 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005154 assert(getLexer().is(AsmToken::EndOfStatement));
5155
Jim Grosbach4b905842013-09-20 23:08:21 +00005156 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005157 return false;
5158}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005159
Jim Grosbach4b905842013-09-20 23:08:21 +00005160bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005161 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005162 const MCExpr *Value;
5163 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005164 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005165 return true;
5166 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5167 if (!MCE)
5168 return Error(ExprLoc, "unexpected expression in _emit");
5169 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005170 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005171 return Error(ExprLoc, "literal value out of range for directive");
5172
Craig Topper7d5b2312015-10-10 05:25:02 +00005173 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005174 return false;
5175}
5176
Jim Grosbach4b905842013-09-20 23:08:21 +00005177bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005178 const MCExpr *Value;
5179 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005180 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005181 return true;
5182 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5183 if (!MCE)
5184 return Error(ExprLoc, "unexpected expression in align");
5185 uint64_t IntValue = MCE->getValue();
5186 if (!isPowerOf2_64(IntValue))
5187 return Error(ExprLoc, "literal value not a power of two greater then zero");
5188
Craig Topper7d5b2312015-10-10 05:25:02 +00005189 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005190 return false;
5191}
5192
Chad Rosierf43fcf52013-02-13 21:27:17 +00005193// We are comparing pointers, but the pointers are relative to a single string.
5194// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005195static int rewritesSort(const AsmRewrite *AsmRewriteA,
5196 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005197 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5198 return -1;
5199 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5200 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005201
Chad Rosierfce4fab2013-04-08 17:43:47 +00005202 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5203 // rewrite to the same location. Make sure the SizeDirective rewrite is
5204 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5205 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005206 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5207 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005208 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005209
Jim Grosbach4b905842013-09-20 23:08:21 +00005210 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5211 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005212 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005213 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005214}
5215
Jim Grosbach4b905842013-09-20 23:08:21 +00005216bool AsmParser::parseMSInlineAsm(
5217 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005218 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005219 SmallVectorImpl<std::string> &Constraints,
5220 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5221 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005222 SmallVector<void *, 4> InputDecls;
5223 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005224 SmallVector<bool, 4> InputDeclsAddressOf;
5225 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005226 SmallVector<std::string, 4> InputConstraints;
5227 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005228 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005229
Benjamin Kramer1a136112013-02-15 20:37:21 +00005230 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005231
5232 // Prime the lexer.
5233 Lex();
5234
5235 // While we have input, parse each statement.
5236 unsigned InputIdx = 0;
5237 unsigned OutputIdx = 0;
5238 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005239 // Parse curly braces marking block start/end
5240 if (parseCurlyBlockScope(AsmStrRewrites))
5241 continue;
5242
Eli Friedman0f4871d2012-10-22 23:58:19 +00005243 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005244 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005245
Nirav Dave2364748a2016-09-16 18:30:20 +00005246 if (StatementErr || Info.ParseError) {
5247 // Emit pending errors if any exist.
5248 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005249 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005250 }
5251
5252 // No pending error should exist here.
5253 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005254
Benjamin Kramer1a136112013-02-15 20:37:21 +00005255 if (Info.Opcode == ~0U)
5256 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005257
Benjamin Kramer1a136112013-02-15 20:37:21 +00005258 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005259
Benjamin Kramer1a136112013-02-15 20:37:21 +00005260 // Build the list of clobbers, outputs and inputs.
5261 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005262 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005263
Benjamin Kramer1a136112013-02-15 20:37:21 +00005264 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005265 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005266 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005267
Benjamin Kramer1a136112013-02-15 20:37:21 +00005268 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005269 if (Operand.isReg() && !Operand.needAddressOf() &&
5270 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005271 unsigned NumDefs = Desc.getNumDefs();
5272 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005273 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5274 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005275 continue;
5276 }
5277
5278 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005279 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005280 if (SymName.empty())
5281 continue;
5282
David Blaikie960ea3f2014-06-08 16:18:35 +00005283 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005284 if (!OpDecl)
5285 continue;
5286
5287 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005288 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005289 if (isOutput) {
5290 ++InputIdx;
5291 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005292 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005293 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005294 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005295 } else {
5296 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005297 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5298 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005299 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005300 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005301 }
Reid Kleckneree088972013-12-10 18:27:32 +00005302
5303 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005304 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5305 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005306 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005307 }
5308
5309 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005310 NumOutputs = OutputDecls.size();
5311 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005312
5313 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005314 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5315 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5316 ClobberRegs.end());
5317 Clobbers.assign(ClobberRegs.size(), std::string());
5318 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5319 raw_string_ostream OS(Clobbers[I]);
5320 IP->printRegName(OS, ClobberRegs[I]);
5321 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005322
5323 // Merge the various outputs and inputs. Output are expected first.
5324 if (NumOutputs || NumInputs) {
5325 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005326 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005327 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005328 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005329 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005330 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005331 }
5332 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005333 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005334 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005335 }
5336 }
5337
5338 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005339 std::string AsmStringIR;
5340 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005341 StringRef ASMString =
5342 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5343 const char *AsmStart = ASMString.begin();
5344 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005345 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005346 for (const AsmRewrite &AR : AsmStrRewrites) {
5347 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005348 if (Kind == AOK_Delete)
5349 continue;
5350
David Majnemer8114c1a2014-06-23 02:17:16 +00005351 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005352 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005353
Chad Rosier120eefd2013-03-19 17:32:17 +00005354 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005355 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005356 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005357
Chad Rosier37e755c2012-10-23 17:43:43 +00005358 // Skip the original expression.
5359 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005360 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005361 continue;
5362 }
5363
Chad Rosierff10ed12013-04-12 16:26:42 +00005364 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005365 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005366 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005367 default:
5368 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005369 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005370 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005371 break;
5372 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005373 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005374 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005375 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005376 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005377 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005378 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005379 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005380 break;
5381 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005382 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005383 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005384 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005385 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005386 default: break;
5387 case 8: OS << "byte ptr "; break;
5388 case 16: OS << "word ptr "; break;
5389 case 32: OS << "dword ptr "; break;
5390 case 64: OS << "qword ptr "; break;
5391 case 80: OS << "xword ptr "; break;
5392 case 128: OS << "xmmword ptr "; break;
5393 case 256: OS << "ymmword ptr "; break;
5394 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005395 break;
5396 case AOK_Emit:
5397 OS << ".byte";
5398 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005399 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005400 // MS alignment directives are measured in bytes. If the native assembler
5401 // measures alignment in bytes, we can pass it straight through.
5402 OS << ".align";
5403 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5404 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005405
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005406 // Alignment is in log2 form, so print that instead and skip the original
5407 // immediate.
5408 unsigned Val = AR.Val;
5409 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005410 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005411 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5412 break;
5413 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005414 case AOK_EVEN:
5415 OS << ".even";
5416 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005417 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005418 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005419 OS.flush();
5420 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005421 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005422 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005423 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005424 case AOK_EndOfStatement:
5425 OS << "\n\t";
5426 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005427 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005428
Chad Rosier8bce6642012-10-18 15:49:34 +00005429 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005430 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005431 }
5432
5433 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005434 if (AsmStart != AsmEnd)
5435 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005436
5437 AsmString = OS.str();
5438 return false;
5439}
5440
Pete Cooper80d21cb2015-06-22 19:35:57 +00005441namespace llvm {
5442namespace MCParserUtils {
5443
5444/// Returns whether the given symbol is used anywhere in the given expression,
5445/// or subexpressions.
5446static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5447 switch (Value->getKind()) {
5448 case MCExpr::Binary: {
5449 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5450 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5451 isSymbolUsedInExpression(Sym, BE->getRHS());
5452 }
5453 case MCExpr::Target:
5454 case MCExpr::Constant:
5455 return false;
5456 case MCExpr::SymbolRef: {
5457 const MCSymbol &S =
5458 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5459 if (S.isVariable())
5460 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5461 return &S == Sym;
5462 }
5463 case MCExpr::Unary:
5464 return isSymbolUsedInExpression(
5465 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5466 }
5467
5468 llvm_unreachable("Unknown expr kind!");
5469}
5470
5471bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5472 MCAsmParser &Parser, MCSymbol *&Sym,
5473 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005474
5475 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005476 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005477
5478 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005479 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005480 }
5481
5482 // Note: we don't count b as used in "a = b". This is to allow
5483 // a = b
5484 // b = c
5485
Nirav Dave1a9044b2016-10-24 14:35:29 +00005486 if (Parser.parseToken(AsmToken::EndOfStatement))
5487 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005488
5489 // Validate that the LHS is allowed to be a variable (either it has not been
5490 // used as a symbol, or it is an absolute symbol).
5491 Sym = Parser.getContext().lookupSymbol(Name);
5492 if (Sym) {
5493 // Diagnose assignment to a label.
5494 //
5495 // FIXME: Diagnostics. Note the location of the definition as a label.
5496 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5497 if (isSymbolUsedInExpression(Sym, Value))
5498 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005499 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5500 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005501 ; // Allow redefinitions of undefined symbols only used in directives.
5502 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5503 ; // Allow redefinitions of variables that haven't yet been used.
5504 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5505 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5506 else if (!Sym->isVariable())
5507 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5508 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5509 return Parser.Error(EqualLoc,
5510 "invalid reassignment of non-absolute variable '" +
5511 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005512 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005513 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005514 return false;
5515 } else
5516 Sym = Parser.getContext().getOrCreateSymbol(Name);
5517
5518 Sym->setRedefinable(allow_redef);
5519
5520 return false;
5521}
5522
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005523} // end namespace MCParserUtils
5524} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005525
Daniel Dunbar01e36072010-07-17 02:26:10 +00005526/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005527MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005528 MCStreamer &Out, const MCAsmInfo &MAI,
5529 unsigned CB) {
5530 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005531}