blob: 33843d7cbed7522c61e8ea6851a2f48981753efa [file] [log] [blame]
Chris Lattnerb0133452009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar2af16532010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/STLExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000021#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000023#include "llvm/ADT/Twine.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000024#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000025#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000026#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000027#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000028#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000029#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000030#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000031#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000033#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000034#include "llvm/MC/MCParser/AsmCond.h"
35#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000036#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000037#include "llvm/MC/MCParser/MCAsmParser.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000038#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000039#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000040#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000041#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000042#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000043#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000044#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000045#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000046#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000047#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000048#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000049#include "llvm/Support/CommandLine.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000050#include "llvm/Support/Dwarf.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000051#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000052#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000053#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000054#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000055#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000056#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000057#include <algorithm>
58#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000059#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000060#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000061#include <cstddef>
62#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000063#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000064#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000065#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000066#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000067#include <tuple>
68#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000069#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000070
Chris Lattnerb0133452009-06-21 20:16:42 +000071using namespace llvm;
72
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000073MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000074
Davide Italiano7c9fc732016-07-27 05:51:56 +000075static cl::opt<unsigned> AsmMacroMaxNestingDepth(
76 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
77 cl::desc("The maximum nesting depth allowed for assembly macros."));
78
Daniel Dunbar86033402010-07-12 17:54:38 +000079namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000080
Eli Benderskya313ae62013-01-16 18:56:50 +000081/// \brief Helper types for tracking macro definitions.
82typedef std::vector<AsmToken> MCAsmMacroArgument;
83typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000084
85struct MCAsmMacroParameter {
86 StringRef Name;
87 MCAsmMacroArgument Value;
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000088 bool Required = false;
89 bool Vararg = false;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000090
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000091 MCAsmMacroParameter() = default;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000092};
93
Eli Benderskya313ae62013-01-16 18:56:50 +000094typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
95
96struct MCAsmMacro {
97 StringRef Name;
98 StringRef Body;
99 MCAsmMacroParameters Parameters;
100
101public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000102 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
103 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +0000104};
105
Daniel Dunbar43235712010-07-18 18:54:11 +0000106/// \brief Helper class for storing information about an active macro
107/// instantiation.
108struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +0000109 /// The location of the instantiation.
110 SMLoc InstantiationLoc;
111
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000112 /// The buffer where parsing should resume upon instantiation completion.
113 int ExitBuffer;
114
Daniel Dunbar43235712010-07-18 18:54:11 +0000115 /// The location where parsing should resume upon instantiation completion.
116 SMLoc ExitLoc;
117
Nico Weber155dccd12014-07-24 17:08:39 +0000118 /// The depth of TheCondStack at the start of the instantiation.
119 size_t CondStackDepth;
120
Daniel Dunbar43235712010-07-18 18:54:11 +0000121public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000122 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000123};
124
Eli Friedman0f4871d2012-10-22 23:58:19 +0000125struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000126 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000127 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000128
Jim Grosbach4b905842013-09-20 23:08:21 +0000129 /// \brief The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000130 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000131
Jim Grosbach4b905842013-09-20 23:08:21 +0000132 /// \brief Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000133 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000134
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000135 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000136
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000137 ParseStatementInfo() = default;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000138 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000139 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000140};
141
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000142/// \brief The concrete assembly parser instance.
143class AsmParser : public MCAsmParser {
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000144private:
145 AsmLexer Lexer;
146 MCContext &Ctx;
147 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000148 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000149 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000150 SourceMgr::DiagHandlerTy SavedDiagHandler;
151 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000152 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000153
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000154 /// This is the current buffer index we're lexing from as managed by the
155 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000156 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000157
158 AsmCond TheCondState;
159 std::vector<AsmCond> TheCondStack;
160
Jim Grosbach4b905842013-09-20 23:08:21 +0000161 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000162 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000163 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000164 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000165
Jim Grosbach4b905842013-09-20 23:08:21 +0000166 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000167 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000168
Jim Grosbach4b905842013-09-20 23:08:21 +0000169 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000170 std::vector<MacroInstantiation*> ActiveMacros;
171
Jim Grosbach4b905842013-09-20 23:08:21 +0000172 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000173 std::deque<MCAsmMacro> MacroLikeBodies;
174
Daniel Dunbar828984f2010-07-18 18:38:02 +0000175 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000176 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000177
Toma Tabacu217116e2015-04-27 10:50:29 +0000178 /// \brief Keeps track of how many .macro's have been instantiated.
179 unsigned NumOfMacroInstantiations;
180
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000181 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000182 struct CppHashInfoTy {
183 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000184 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000185 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000186 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000187 };
188 CppHashInfoTy CppHashInfo;
189
190 /// \brief List of forward directional labels for diagnosis at the end.
191 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
192
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000193 /// When generating dwarf for assembly source files we need to calculate the
194 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000195 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000196 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
197 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000198 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000199 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000200
Devang Patela173ee52012-01-31 18:14:05 +0000201 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000202 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000203
Jim Grosbach4b905842013-09-20 23:08:21 +0000204 /// \brief is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000205 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000206
Jim Grosbach4b905842013-09-20 23:08:21 +0000207 /// \brief Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000208 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000209
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000210public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000211 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000212 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000213 AsmParser(const AsmParser &) = delete;
214 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000215 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000216
Craig Topper59be68f2014-03-08 07:14:16 +0000217 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000218
Craig Topper59be68f2014-03-08 07:14:16 +0000219 void addDirectiveHandler(StringRef Directive,
220 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000221 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000222 }
223
Toma Tabacu11e14a92015-04-21 11:50:52 +0000224 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
225 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
226 }
227
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000228 /// @name MCAsmParser Interface
229 /// {
230
Craig Topper59be68f2014-03-08 07:14:16 +0000231 SourceMgr &getSourceManager() override { return SrcMgr; }
232 MCAsmLexer &getLexer() override { return Lexer; }
233 MCContext &getContext() override { return Ctx; }
234 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000235
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000236 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
237
Craig Topper59be68f2014-03-08 07:14:16 +0000238 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000239 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000240 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000241 else
242 return AssemblerDialect;
243 }
Craig Topper59be68f2014-03-08 07:14:16 +0000244 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000245 AssemblerDialect = i;
246 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000247
Nirav Dave2364748a2016-09-16 18:30:20 +0000248 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
249 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
250 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000251
Craig Topper59be68f2014-03-08 07:14:16 +0000252 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000254 void setParsingInlineAsm(bool V) override {
255 ParsingInlineAsm = V;
256 Lexer.setParsingMSInlineAsm(V);
257 }
Craig Topper59be68f2014-03-08 07:14:16 +0000258 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000259
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000260 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000261 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000262 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000263 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000264 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000265 const MCInstrInfo *MII, const MCInstPrinter *IP,
266 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000267
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000268 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000269 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
270 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
271 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000272 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
273 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000274 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000275
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000276 /// \brief Parse a floating point expression using the float \p Semantics
277 /// and set \p Res to the value.
278 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
279
Jim Grosbach4b905842013-09-20 23:08:21 +0000280 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000281 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000282 bool parseIdentifier(StringRef &Res) override;
283 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000284
Nirav Davef43cc9f2016-10-10 15:24:54 +0000285 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000286
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000287 /// }
288
289private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000290 bool parseStatement(ParseStatementInfo &Info,
291 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000292 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000293 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000294
Jim Grosbach4b905842013-09-20 23:08:21 +0000295 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000296 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000297 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000298 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000299 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000300 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000301
Eli Benderskya313ae62013-01-16 18:56:50 +0000302 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000303 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000304
305 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000306 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000307
308 /// \brief Lookup a previously defined macro.
309 /// \param Name Macro name.
310 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000311 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000312
313 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000314 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000315
316 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000317 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000318
319 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000320 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000321
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000322 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000323 ///
324 /// \param M The macro.
325 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000326 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000327
328 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000329 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000330
David Majnemer91fc4c22014-01-29 18:57:46 +0000331 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000332 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000333
334 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000335 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000336
Jim Grosbach4b905842013-09-20 23:08:21 +0000337 void printMacroInstantiations();
338 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000339 SMRange Range = None) const {
340 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000341 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000342 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000343 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000344
Jim Grosbach4b905842013-09-20 23:08:21 +0000345 /// \brief Enter the specified file. This returns true on failure.
346 bool enterIncludeFile(const std::string &Filename);
347
348 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000349 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000350 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
351 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000352
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000353 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000354 /// current token is not set; clients should ensure Lex() is called
355 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000356 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000357 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000358 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000359 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000360
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000361 /// \brief Parse up to the end of statement and a return the contents from the
362 /// current token until the end of the statement; the current token on exit
363 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000364 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000365
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000366 /// \brief Parse until the end of a statement or a comma is encountered,
367 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000368 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000369
Jim Grosbach4b905842013-09-20 23:08:21 +0000370 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000371 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000372
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000373 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
374 MCBinaryExpr::Opcode &Kind);
375
Jim Grosbach4b905842013-09-20 23:08:21 +0000376 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
377 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
378 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000379
Jim Grosbach4b905842013-09-20 23:08:21 +0000380 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000381
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000382 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
383 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
384
Eli Bendersky17233942013-01-15 22:59:42 +0000385 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000386 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000387 DK_NO_DIRECTIVE, // Placeholder
388 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000389 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000390 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
Petr Hosek731bb9c2016-08-23 21:34:53 +0000391 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000392 DK_DCB, DK_DCB_B, DK_DCB_D, DK_DCB_L, DK_DCB_S, DK_DCB_W, DK_DCB_X,
Petr Hosek85b2f672016-09-23 21:53:36 +0000393 DK_DS, DK_DS_B, DK_DS_D, DK_DS_L, DK_DS_P, DK_DS_S, DK_DS_W, DK_DS_X,
David Woodhoused6de0d92014-02-01 16:20:59 +0000394 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000395 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000396 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000397 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000398 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000399 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000400 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
401 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000402 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000403 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
404 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000405 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000406 DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE,
407 DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE,
408 DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000409 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
410 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
411 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
412 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
413 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000414 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000415 DK_MACROS_ON, DK_MACROS_OFF,
416 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000417 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000418 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000419 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000420 };
421
Jim Grosbach4b905842013-09-20 23:08:21 +0000422 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000423 /// directives parsed by this class.
424 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000425
426 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000427 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000428 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000429 bool parseDirectiveValue(StringRef IDVal,
430 unsigned Size); // ".byte", ".long", ...
431 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
432 bool parseDirectiveRealValue(StringRef IDVal,
433 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000434 bool parseDirectiveFill(); // ".fill"
435 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000436 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000437 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
438 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000439 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000440 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000441
Eli Bendersky17233942013-01-15 22:59:42 +0000442 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000443 bool parseDirectiveFile(SMLoc DirectiveLoc);
444 bool parseDirectiveLine();
445 bool parseDirectiveLoc();
446 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000447
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000448 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
449 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000450 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000451 bool parseDirectiveCVFuncId();
452 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000453 bool parseDirectiveCVLoc();
454 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000455 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000456 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000457 bool parseDirectiveCVStringTable();
458 bool parseDirectiveCVFileChecksums();
459
Eli Bendersky17233942013-01-15 22:59:42 +0000460 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000461 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000462 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000463 bool parseDirectiveCFISections();
464 bool parseDirectiveCFIStartProc();
465 bool parseDirectiveCFIEndProc();
466 bool parseDirectiveCFIDefCfaOffset();
467 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
468 bool parseDirectiveCFIAdjustCfaOffset();
469 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
470 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
471 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
472 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
473 bool parseDirectiveCFIRememberState();
474 bool parseDirectiveCFIRestoreState();
475 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
476 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
477 bool parseDirectiveCFIEscape();
478 bool parseDirectiveCFISignalFrame();
479 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000480
481 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000482 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000483 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000484 bool parseDirectiveEndMacro(StringRef Directive);
485 bool parseDirectiveMacro(SMLoc DirectiveLoc);
486 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000487
Eli Benderskyf483ff92012-12-20 19:05:53 +0000488 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000489 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000490 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000491 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000492 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000493 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000494
Eli Bendersky17233942013-01-15 22:59:42 +0000495 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000496 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000497
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000498 // ".dcb"
499 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
500 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000501 // ".ds"
502 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000503
Eli Bendersky17233942013-01-15 22:59:42 +0000504 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000505 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000506
Jim Grosbach4b905842013-09-20 23:08:21 +0000507 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000508 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000509 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000510
Jim Grosbach4b905842013-09-20 23:08:21 +0000511 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000512
Jim Grosbach4b905842013-09-20 23:08:21 +0000513 bool parseDirectiveAbort(); // ".abort"
514 bool parseDirectiveInclude(); // ".include"
515 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000516
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000517 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
518 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000519 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000520 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000521 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000522 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000523 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
524 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000525 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000526 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
527 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
528 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
529 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000530 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000531
Jim Grosbach4b905842013-09-20 23:08:21 +0000532 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000533 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000534
Rafael Espindola34b9c512012-06-03 23:57:14 +0000535 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000536 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
537 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000538 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000539 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000540 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
541 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
542 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000543
Chad Rosierc7f552c2013-02-12 21:33:51 +0000544 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000545 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000546 size_t Len);
547
548 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000549 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000550
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000551 // "end"
552 bool parseDirectiveEnd(SMLoc DirectiveLoc);
553
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000554 // ".err" or ".error"
555 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000556
Nico Weber404012b2014-07-24 16:26:06 +0000557 // ".warning"
558 bool parseDirectiveWarning(SMLoc DirectiveLoc);
559
Eli Bendersky17233942013-01-15 22:59:42 +0000560 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000561};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000562
563} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000564
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000565namespace llvm {
566
567extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000568extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000569extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000570
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000571} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000572
Chris Lattnerc35681b2010-01-19 19:46:13 +0000573enum { DEFAULT_ADDRSPACE = 0 };
574
David Blaikie9f380a32015-03-16 18:06:57 +0000575AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000576 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000577 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000578 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000579 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000580 // Save the old handler.
581 SavedDiagHandler = SrcMgr.getDiagHandler();
582 SavedDiagContext = SrcMgr.getDiagContext();
583 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000584 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000585 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000586
Daniel Dunbarc5011082010-07-12 18:12:02 +0000587 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000588 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
589 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000590 PlatformParser.reset(createCOFFAsmParser());
591 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000592 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000593 PlatformParser.reset(createDarwinAsmParser());
594 IsDarwin = true;
595 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000596 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000597 PlatformParser.reset(createELFAsmParser());
598 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000599 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000600
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000601 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000602 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000603
604 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000605}
606
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000607AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000608 assert((HadError || ActiveMacros.empty()) &&
609 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000610
611 // Restore the saved diagnostics handler and context for use during
612 // finalization.
613 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000614}
615
Jim Grosbach4b905842013-09-20 23:08:21 +0000616void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000617 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000618 for (std::vector<MacroInstantiation *>::const_reverse_iterator
619 it = ActiveMacros.rbegin(),
620 ie = ActiveMacros.rend();
621 it != ie; ++it)
622 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000623 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000624}
625
Nirav Dave2364748a2016-09-16 18:30:20 +0000626void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
627 printPendingErrors();
628 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000629 printMacroInstantiations();
630}
631
Nirav Dave2364748a2016-09-16 18:30:20 +0000632bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000633 if(getTargetParser().getTargetOptions().MCNoWarn)
634 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000635 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000636 return Error(L, Msg, Range);
637 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000638 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000639 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000640}
641
Nirav Dave2364748a2016-09-16 18:30:20 +0000642bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000643 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000644 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000645 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000646 return true;
647}
648
Jim Grosbach4b905842013-09-20 23:08:21 +0000649bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000650 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000651 unsigned NewBuf =
652 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
653 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000654 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000655
Sean Callanan7a77eae2010-01-21 00:19:58 +0000656 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000657 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000658 return false;
659}
Daniel Dunbar43235712010-07-18 18:54:11 +0000660
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000661/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000662/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000663/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000664bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
665 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000666 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000667 unsigned NewBuf =
668 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
669 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000670 return true;
671
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000672 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000673 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
674 Bytes = Bytes.drop_front(Skip);
675 if (Count) {
676 int64_t Res;
677 if (!Count->evaluateAsAbsolute(Res))
678 return Error(Loc, "expected absolute expression");
679 if (Res < 0)
680 return Warning(Loc, "negative count has no effect");
681 Bytes = Bytes.take_front(Res);
682 }
683 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000684 return false;
685}
686
Alp Tokera55b95b2014-07-06 10:33:31 +0000687void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
688 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000689 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
690 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000691}
692
Sean Callanan7a77eae2010-01-21 00:19:58 +0000693const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000694 if (Lexer.getTok().is(AsmToken::Error))
695 Error(Lexer.getErrLoc(), Lexer.getErr());
696
Nirav Dave53a72f42016-07-11 12:42:14 +0000697 // if it's a end of statement with a comment in it
698 if (getTok().is(AsmToken::EndOfStatement)) {
699 // if this is a line comment output it.
700 if (getTok().getString().front() != '\n' &&
701 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
702 Out.addExplicitComment(Twine(getTok().getString()));
703 }
704
Sean Callanan7a77eae2010-01-21 00:19:58 +0000705 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000706
707 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000708 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000709 if (MAI.preserveAsmComments())
710 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000711 tok = &Lexer.Lex();
712 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000713
Sean Callanan7a77eae2010-01-21 00:19:58 +0000714 if (tok->is(AsmToken::Eof)) {
715 // If this is the end of an included file, pop the parent file off the
716 // include stack.
717 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
718 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000719 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000720 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000721 }
722 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000723
Sean Callanan7a77eae2010-01-21 00:19:58 +0000724 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000725}
726
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000727bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000728 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000729 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000730 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000731
Chris Lattner36e02122009-06-21 20:54:55 +0000732 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000733 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000734
735 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000736 AsmCond StartingCondState = TheCondState;
737
Kevin Enderby6469fc22011-11-01 22:27:22 +0000738 // If we are generating dwarf for assembly source files save the initial text
739 // section and generate a .file directive.
740 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000741 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000742 if (!Sec->getBeginSymbol()) {
743 MCSymbol *SectionStartSym = getContext().createTempSymbol();
744 getStreamer().EmitLabel(SectionStartSym);
745 Sec->setBeginSymbol(SectionStartSym);
746 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000747 bool InsertResult = getContext().addGenDwarfSection(Sec);
748 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000749 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000750 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
751 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000752 }
753
Chris Lattner73f36112009-07-02 21:53:43 +0000754 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000755 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000756 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000757 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000758 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000759
Nirav Dave2364748a2016-09-16 18:30:20 +0000760 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
761 // for printing ErrMsg via Lex() only if no (presumably better) parser error
762 // exists.
763 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000764 Lex();
765 }
766
Nirav Dave2364748a2016-09-16 18:30:20 +0000767 // parseStatement returned true so may need to emit an error.
768 printPendingErrors();
769
770 // Skipping to the next line if needed.
771 if (!getLexer().isAtStartOfStatement())
772 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000773 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000774
Nirav Dave2364748a2016-09-16 18:30:20 +0000775 // All errors should have been emitted.
776 assert(!hasPendingError() && "unexpected error from parseStatement");
777
Oliver Stannard21718282016-07-26 14:19:47 +0000778 getTargetParser().flushPendingInstructions(getStreamer());
779
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000780 if (TheCondState.TheCond != StartingCondState.TheCond ||
781 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000782 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000783 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000784 const auto &LineTables = getContext().getMCDwarfLineTables();
785 if (!LineTables.empty()) {
786 unsigned Index = 0;
787 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
788 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000789 printError(getTok().getLoc(), "unassigned file number: " +
790 Twine(Index) +
791 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000792 ++Index;
793 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000794 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000795
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000796 // Check to see that all assembler local symbols were actually defined.
797 // Targets that don't do subsections via symbols may not want this, though,
798 // so conservatively exclude them. Only do this if we're finalizing, though,
799 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000800 if (!NoFinalize) {
801 if (MAI.hasSubsectionsViaSymbols()) {
802 for (const auto &TableEntry : getContext().getSymbols()) {
803 MCSymbol *Sym = TableEntry.getValue();
804 // Variable symbols may not be marked as defined, so check those
805 // explicitly. If we know it's a variable, we have a definition for
806 // the purposes of this check.
807 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
808 // FIXME: We would really like to refer back to where the symbol was
809 // first referenced for a source location. We need to add something
810 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000811 printError(getTok().getLoc(), "assembler local symbol '" +
812 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000813 }
814 }
815
816 // Temporary symbols like the ones for directional jumps don't go in the
817 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000818 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
819 if (std::get<2>(LocSym)->isUndefined()) {
820 // Reset the state of any "# line file" directives we've seen to the
821 // context as it was at the diagnostic site.
822 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000823 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000824 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000825 }
826 }
827
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000828 // Finalize the output stream if there are no errors and if the client wants
829 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000830 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000831 Out.Finish();
832
Oliver Stannard07b43d32015-11-17 09:58:07 +0000833 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000834}
835
Nirav Davef43cc9f2016-10-10 15:24:54 +0000836bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000837 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000838 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000839 return Error(getTok().getLoc(),
840 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000841 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000842 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000843}
844
Jim Grosbach4b905842013-09-20 23:08:21 +0000845/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000846void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000847 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000848 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000849
Chris Lattnere5074c42009-06-22 01:29:09 +0000850 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000851 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000852 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000853}
854
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000855StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000856 const char *Start = getTok().getLoc().getPointer();
857
Jim Grosbach4b905842013-09-20 23:08:21 +0000858 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000859 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000860
861 const char *End = getTok().getLoc().getPointer();
862 return StringRef(Start, End - Start);
863}
Chris Lattner78db3622009-06-22 05:51:26 +0000864
Jim Grosbach4b905842013-09-20 23:08:21 +0000865StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000866 const char *Start = getTok().getLoc().getPointer();
867
868 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000869 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000870 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000871
872 const char *End = getTok().getLoc().getPointer();
873 return StringRef(Start, End - Start);
874}
875
Jim Grosbach4b905842013-09-20 23:08:21 +0000876/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000877/// NOTE: This assumes the leading '(' has already been consumed.
878///
879/// parenexpr ::= expr)
880///
Jim Grosbach4b905842013-09-20 23:08:21 +0000881bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
882 if (parseExpression(Res))
883 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000884 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000885 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000886 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000887 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000888 return false;
889}
Chris Lattner78db3622009-06-22 05:51:26 +0000890
Jim Grosbach4b905842013-09-20 23:08:21 +0000891/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000892/// NOTE: This assumes the leading '[' has already been consumed.
893///
894/// bracketexpr ::= expr]
895///
Jim Grosbach4b905842013-09-20 23:08:21 +0000896bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
897 if (parseExpression(Res))
898 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000899 EndLoc = getTok().getEndLoc();
900 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
901 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000902 return false;
903}
904
Jim Grosbach4b905842013-09-20 23:08:21 +0000905/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000906/// primaryexpr ::= (parenexpr
907/// primaryexpr ::= symbol
908/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000909/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000910/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000911bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000912 SMLoc FirstTokenLoc = getLexer().getLoc();
913 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
914 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000915 default:
916 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000917 // If we have an error assume that we've already handled it.
918 case AsmToken::Error:
919 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000920 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000921 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000922 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000923 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000924 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000925 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000926 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000927 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000928 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000929 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000930 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000931 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +0000932 // We may have failed but $ may be a valid token.
933 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000934 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +0000935 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +0000936 // This is a '$' reference, which references the current PC. Emit a
937 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000938 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000939 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000940 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000941 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000942 EndLoc = FirstTokenLoc;
943 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000944 }
945 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000946 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000947 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000948 // Parse symbol variant
949 std::pair<StringRef, StringRef> Split;
950 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000951 if (FirstTokenKind == AsmToken::String) {
952 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000953 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000954 SMLoc AtLoc = getLexer().getLoc();
955 StringRef VName;
956 if (parseIdentifier(VName))
957 return Error(AtLoc, "expected symbol variant after '@'");
958
959 Split = std::make_pair(Identifier, VName);
960 }
961 } else {
962 Split = Identifier.split('@');
963 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000964 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000965 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000966 StringRef VName;
967 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000968 // eat ')'.
969 if (parseToken(AsmToken::RParen,
970 "unexpected token in variant, expected ')'"))
971 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000972 Split = std::make_pair(Identifier, VName);
973 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000974
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000975 EndLoc = SMLoc::getFromPointer(Identifier.end());
976
Daniel Dunbard20cda02009-10-16 01:34:54 +0000977 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000978 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +0000979 if (SymbolName.empty())
980 return true;
981
Hans Wennborgce69d772013-10-18 20:46:28 +0000982 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000983
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000984 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000985 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000986 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000987 if (Variant != MCSymbolRefExpr::VK_Invalid) {
988 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000989 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000990 Variant = MCSymbolRefExpr::VK_None;
991 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000992 return Error(SMLoc::getFromPointer(Split.second.begin()),
993 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000994 }
995 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000996
Jim Grosbach6f482002015-05-18 18:43:14 +0000997 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000998
Daniel Dunbard20cda02009-10-16 01:34:54 +0000999 // If this is an absolute variable reference, substitute it now to preserve
1000 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001001 if (Sym->isVariable() &&
1002 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001003 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001004 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001005
Vedant Kumar86dbd922015-08-31 17:44:53 +00001006 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001007 return false;
1008 }
1009
1010 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001011 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001012 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001013 }
David Woodhousef42a6662014-02-01 16:20:54 +00001014 case AsmToken::BigNum:
1015 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001016 case AsmToken::Integer: {
1017 SMLoc Loc = getTok().getLoc();
1018 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001019 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001020 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001021 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001022 // Look for 'b' or 'f' following an Integer as a directional label
1023 if (Lexer.getKind() == AsmToken::Identifier) {
1024 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001025 // Lookup the symbol variant if used.
1026 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1027 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1028 if (Split.first.size() != IDVal.size()) {
1029 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001030 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001031 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001032 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001033 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001034 if (IDVal == "f" || IDVal == "b") {
1035 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001036 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001037 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001038 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001039 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001040 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001041 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001042 Lex(); // Eat identifier.
1043 }
1044 }
Chris Lattner78db3622009-06-22 05:51:26 +00001045 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001046 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001047 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001048 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001049 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001050 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001051 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001052 Lex(); // Eat token.
1053 return false;
1054 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001055 case AsmToken::Dot: {
1056 // This is a '.' reference, which references the current PC. Emit a
1057 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001058 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001059 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001060 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001061 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001062 Lex(); // Eat identifier.
1063 return false;
1064 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001065 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001066 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001067 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001068 case AsmToken::LBrac:
1069 if (!PlatformParser->HasBracketExpressions())
1070 return TokError("brackets expression not supported on this target");
1071 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001072 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001073 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001074 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001075 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001076 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001077 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001078 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001079 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001080 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001081 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001082 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001083 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001084 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001085 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001086 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001087 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001088 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001089 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001090 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001091 // MIPS unary expression operators. The lexer won't generate these tokens if
1092 // MCAsmInfo::HasMipsExpressions is false for the target.
1093 case AsmToken::PercentCall16:
1094 case AsmToken::PercentCall_Hi:
1095 case AsmToken::PercentCall_Lo:
1096 case AsmToken::PercentDtprel_Hi:
1097 case AsmToken::PercentDtprel_Lo:
1098 case AsmToken::PercentGot:
1099 case AsmToken::PercentGot_Disp:
1100 case AsmToken::PercentGot_Hi:
1101 case AsmToken::PercentGot_Lo:
1102 case AsmToken::PercentGot_Ofst:
1103 case AsmToken::PercentGot_Page:
1104 case AsmToken::PercentGottprel:
1105 case AsmToken::PercentGp_Rel:
1106 case AsmToken::PercentHi:
1107 case AsmToken::PercentHigher:
1108 case AsmToken::PercentHighest:
1109 case AsmToken::PercentLo:
1110 case AsmToken::PercentNeg:
1111 case AsmToken::PercentPcrel_Hi:
1112 case AsmToken::PercentPcrel_Lo:
1113 case AsmToken::PercentTlsgd:
1114 case AsmToken::PercentTlsldm:
1115 case AsmToken::PercentTprel_Hi:
1116 case AsmToken::PercentTprel_Lo:
1117 Lex(); // Eat the operator.
1118 if (Lexer.isNot(AsmToken::LParen))
1119 return TokError("expected '(' after operator");
1120 Lex(); // Eat the operator.
1121 if (parseExpression(Res, EndLoc))
1122 return true;
1123 if (Lexer.isNot(AsmToken::RParen))
1124 return TokError("expected ')'");
1125 Lex(); // Eat the operator.
1126 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1127 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001128 }
1129}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001130
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001131bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001132 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001133 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001134}
1135
Daniel Dunbar55f16672010-09-17 02:47:07 +00001136const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001137AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001138 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001139 // Ask the target implementation about this expression first.
1140 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1141 if (NewE)
1142 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001143 // Recurse over the given expression, rebuilding it to apply the given variant
1144 // if there is exactly one symbol.
1145 switch (E->getKind()) {
1146 case MCExpr::Target:
1147 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001148 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001149
1150 case MCExpr::SymbolRef: {
1151 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1152
1153 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001154 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1155 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001156 return E;
1157 }
1158
Jim Grosbach13760bd2015-05-30 01:25:56 +00001159 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001160 }
1161
1162 case MCExpr::Unary: {
1163 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001164 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001165 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001166 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001167 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001168 }
1169
1170 case MCExpr::Binary: {
1171 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001172 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1173 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001174
1175 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001176 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001177
Jim Grosbach4b905842013-09-20 23:08:21 +00001178 if (!LHS)
1179 LHS = BE->getLHS();
1180 if (!RHS)
1181 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001182
Jim Grosbach13760bd2015-05-30 01:25:56 +00001183 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001184 }
1185 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001186
Craig Toppera2886c22012-02-07 05:05:23 +00001187 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001188}
1189
Jim Grosbach4b905842013-09-20 23:08:21 +00001190/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001191///
Jim Grosbachbd164242011-08-20 16:24:13 +00001192/// expr ::= expr &&,|| expr -> lowest.
1193/// expr ::= expr |,^,&,! expr
1194/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1195/// expr ::= expr <<,>> expr
1196/// expr ::= expr +,- expr
1197/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001198/// expr ::= primaryexpr
1199///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001200bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001201 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001202 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001203 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001204 return true;
1205
Daniel Dunbar55f16672010-09-17 02:47:07 +00001206 // As a special case, we support 'a op b @ modifier' by rewriting the
1207 // expression to include the modifier. This is inefficient, but in general we
1208 // expect users to use 'a@modifier op b'.
1209 if (Lexer.getKind() == AsmToken::At) {
1210 Lex();
1211
1212 if (Lexer.isNot(AsmToken::Identifier))
1213 return TokError("unexpected symbol modifier following '@'");
1214
1215 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001216 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001217 if (Variant == MCSymbolRefExpr::VK_Invalid)
1218 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1219
Jim Grosbach4b905842013-09-20 23:08:21 +00001220 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001221 if (!ModifiedRes) {
1222 return TokError("invalid modifier '" + getTok().getIdentifier() +
1223 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001224 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001225
Daniel Dunbar55f16672010-09-17 02:47:07 +00001226 Res = ModifiedRes;
1227 Lex();
1228 }
1229
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001230 // Try to constant fold it up front, if possible.
1231 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001232 if (Res->evaluateAsAbsolute(Value))
1233 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001234
1235 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001236}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001237
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001238bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001239 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001240 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001241}
1242
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001243bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1244 SMLoc &EndLoc) {
1245 if (parseParenExpr(Res, EndLoc))
1246 return true;
1247
1248 for (; ParenDepth > 0; --ParenDepth) {
1249 if (parseBinOpRHS(1, Res, EndLoc))
1250 return true;
1251
1252 // We don't Lex() the last RParen.
1253 // This is the same behavior as parseParenExpression().
1254 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001255 EndLoc = getTok().getEndLoc();
1256 if (parseToken(AsmToken::RParen,
1257 "expected ')' in parentheses expression"))
1258 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001259 }
1260 }
1261 return false;
1262}
1263
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001264bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001265 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001266
Daniel Dunbar75630b32009-06-30 02:10:03 +00001267 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001268 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001269 return true;
1270
Jim Grosbach13760bd2015-05-30 01:25:56 +00001271 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001272 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001273
1274 return false;
1275}
1276
David Majnemer0993e0b2015-10-26 03:15:34 +00001277static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1278 MCBinaryExpr::Opcode &Kind,
1279 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001280 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001281 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001282 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001283
Jim Grosbach4b905842013-09-20 23:08:21 +00001284 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001285 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001286 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001287 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001288 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001289 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001290 return 1;
1291
Jim Grosbach4b905842013-09-20 23:08:21 +00001292 // Low Precedence: |, &, ^
1293 //
1294 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001295 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001296 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001297 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001298 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001299 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001300 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001301 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001302 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001303 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001304
Jim Grosbach4b905842013-09-20 23:08:21 +00001305 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001306 case AsmToken::EqualEqual:
1307 Kind = MCBinaryExpr::EQ;
1308 return 3;
1309 case AsmToken::ExclaimEqual:
1310 case AsmToken::LessGreater:
1311 Kind = MCBinaryExpr::NE;
1312 return 3;
1313 case AsmToken::Less:
1314 Kind = MCBinaryExpr::LT;
1315 return 3;
1316 case AsmToken::LessEqual:
1317 Kind = MCBinaryExpr::LTE;
1318 return 3;
1319 case AsmToken::Greater:
1320 Kind = MCBinaryExpr::GT;
1321 return 3;
1322 case AsmToken::GreaterEqual:
1323 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001324 return 3;
1325
Jim Grosbach4b905842013-09-20 23:08:21 +00001326 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001327 case AsmToken::LessLess:
1328 Kind = MCBinaryExpr::Shl;
1329 return 4;
1330 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001331 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001332 return 4;
1333
Jim Grosbach4b905842013-09-20 23:08:21 +00001334 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001335 case AsmToken::Plus:
1336 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001337 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001338 case AsmToken::Minus:
1339 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001340 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001341
Jim Grosbach4b905842013-09-20 23:08:21 +00001342 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001343 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001344 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001345 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001346 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001347 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001348 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001349 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001350 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001351 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001352 }
1353}
1354
David Majnemer0993e0b2015-10-26 03:15:34 +00001355static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1356 MCBinaryExpr::Opcode &Kind,
1357 bool ShouldUseLogicalShr) {
1358 switch (K) {
1359 default:
1360 return 0; // not a binop.
1361
1362 // Lowest Precedence: &&, ||
1363 case AsmToken::AmpAmp:
1364 Kind = MCBinaryExpr::LAnd;
1365 return 2;
1366 case AsmToken::PipePipe:
1367 Kind = MCBinaryExpr::LOr;
1368 return 1;
1369
1370 // Low Precedence: ==, !=, <>, <, <=, >, >=
1371 case AsmToken::EqualEqual:
1372 Kind = MCBinaryExpr::EQ;
1373 return 3;
1374 case AsmToken::ExclaimEqual:
1375 case AsmToken::LessGreater:
1376 Kind = MCBinaryExpr::NE;
1377 return 3;
1378 case AsmToken::Less:
1379 Kind = MCBinaryExpr::LT;
1380 return 3;
1381 case AsmToken::LessEqual:
1382 Kind = MCBinaryExpr::LTE;
1383 return 3;
1384 case AsmToken::Greater:
1385 Kind = MCBinaryExpr::GT;
1386 return 3;
1387 case AsmToken::GreaterEqual:
1388 Kind = MCBinaryExpr::GTE;
1389 return 3;
1390
1391 // Low Intermediate Precedence: +, -
1392 case AsmToken::Plus:
1393 Kind = MCBinaryExpr::Add;
1394 return 4;
1395 case AsmToken::Minus:
1396 Kind = MCBinaryExpr::Sub;
1397 return 4;
1398
1399 // High Intermediate Precedence: |, &, ^
1400 //
1401 // FIXME: gas seems to support '!' as an infix operator?
1402 case AsmToken::Pipe:
1403 Kind = MCBinaryExpr::Or;
1404 return 5;
1405 case AsmToken::Caret:
1406 Kind = MCBinaryExpr::Xor;
1407 return 5;
1408 case AsmToken::Amp:
1409 Kind = MCBinaryExpr::And;
1410 return 5;
1411
1412 // Highest Precedence: *, /, %, <<, >>
1413 case AsmToken::Star:
1414 Kind = MCBinaryExpr::Mul;
1415 return 6;
1416 case AsmToken::Slash:
1417 Kind = MCBinaryExpr::Div;
1418 return 6;
1419 case AsmToken::Percent:
1420 Kind = MCBinaryExpr::Mod;
1421 return 6;
1422 case AsmToken::LessLess:
1423 Kind = MCBinaryExpr::Shl;
1424 return 6;
1425 case AsmToken::GreaterGreater:
1426 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1427 return 6;
1428 }
1429}
1430
1431unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1432 MCBinaryExpr::Opcode &Kind) {
1433 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1434 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1435 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1436}
1437
Jim Grosbach4b905842013-09-20 23:08:21 +00001438/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001439/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001440bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001441 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001442 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001443 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001444 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001445 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001446
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001447 // If the next token is lower precedence than we are allowed to eat, return
1448 // successfully with what we ate already.
1449 if (TokPrec < Precedence)
1450 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001451
Sean Callanan686ed8d2010-01-19 20:22:31 +00001452 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001453
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001454 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001455 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001456 if (parsePrimaryExpr(RHS, EndLoc))
1457 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001458
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001459 // If BinOp binds less tightly with RHS than the operator after RHS, let
1460 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001461 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001462 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001463 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1464 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001465
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001466 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001467 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001468 }
1469}
1470
Chris Lattner36e02122009-06-21 20:54:55 +00001471/// ParseStatement:
1472/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001473/// ::= Label* Directive ...Operands... EndOfStatement
1474/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001475bool AsmParser::parseStatement(ParseStatementInfo &Info,
1476 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001477 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001478 // Eat initial spaces and comments
1479 while (Lexer.is(AsmToken::Space))
1480 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001481 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001482 // if this is a line comment we can drop it safely
1483 if (getTok().getString().front() == '\r' ||
1484 getTok().getString().front() == '\n')
1485 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001486 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001487 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001488 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001489 if (Lexer.is(AsmToken::Hash)) {
1490 // Seeing a hash here means that it was an end-of-line comment in
1491 // an asm syntax where hash's are not comment and the previous
1492 // statement parser did not check the end of statement. Relex as
1493 // EndOfStatement.
1494 StringRef CommentStr = parseStringToEndOfStatement();
1495 Lexer.Lex();
1496 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1497 return false;
1498 }
Nirav Davefd910412016-06-17 16:06:17 +00001499 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001500 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001501 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001502 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001503 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001504 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001505 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001506 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001507 if (Lexer.is(AsmToken::Integer)) {
1508 LocalLabelVal = getTok().getIntVal();
1509 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001510 if (!TheCondState.Ignore) {
1511 Lex(); // always eat a token
1512 return Error(IDLoc, "unexpected token at start of statement");
1513 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001514 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001515 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001516 IDVal = getTok().getString();
1517 Lex(); // Consume the integer token to be used as an identifier token.
1518 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001519 if (!TheCondState.Ignore) {
1520 Lex(); // always eat a token
1521 return Error(IDLoc, "unexpected token at start of statement");
1522 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001523 }
1524 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001525 } else if (Lexer.is(AsmToken::Dot)) {
1526 // Treat '.' as a valid identifier in this context.
1527 Lex();
1528 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001529 } else if (Lexer.is(AsmToken::LCurly)) {
1530 // Treat '{' as a valid identifier in this context.
1531 Lex();
1532 IDVal = "{";
1533
1534 } else if (Lexer.is(AsmToken::RCurly)) {
1535 // Treat '}' as a valid identifier in this context.
1536 Lex();
1537 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001538 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001539 if (!TheCondState.Ignore) {
1540 Lex(); // always eat a token
1541 return Error(IDLoc, "unexpected token at start of statement");
1542 }
Chris Lattner926885c2010-04-17 18:14:27 +00001543 IDVal = "";
1544 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001545
Chris Lattner926885c2010-04-17 18:14:27 +00001546 // Handle conditional assembly here before checking for skipping. We
1547 // have to do this so that .endif isn't skipped in a ".if 0" block for
1548 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001549 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001550 DirectiveKindMap.find(IDVal);
1551 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1552 ? DK_NO_DIRECTIVE
1553 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001554 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001555 default:
1556 break;
1557 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001558 case DK_IFEQ:
1559 case DK_IFGE:
1560 case DK_IFGT:
1561 case DK_IFLE:
1562 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001563 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001564 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001565 case DK_IFB:
1566 return parseDirectiveIfb(IDLoc, true);
1567 case DK_IFNB:
1568 return parseDirectiveIfb(IDLoc, false);
1569 case DK_IFC:
1570 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001571 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001572 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001573 case DK_IFNC:
1574 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001575 case DK_IFNES:
1576 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001577 case DK_IFDEF:
1578 return parseDirectiveIfdef(IDLoc, true);
1579 case DK_IFNDEF:
1580 case DK_IFNOTDEF:
1581 return parseDirectiveIfdef(IDLoc, false);
1582 case DK_ELSEIF:
1583 return parseDirectiveElseIf(IDLoc);
1584 case DK_ELSE:
1585 return parseDirectiveElse(IDLoc);
1586 case DK_ENDIF:
1587 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001588 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001589
Eli Bendersky88024712013-01-16 19:32:36 +00001590 // Ignore the statement if in the middle of inactive conditional
1591 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001592 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001593 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001594 return false;
1595 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001596
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001597 // FIXME: Recurse on local labels?
1598
1599 // See what kind of statement we have.
1600 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001601 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001602 if (!getTargetParser().isLabel(ID))
1603 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001604 if (checkForValidSection())
1605 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001606
Chris Lattner36e02122009-06-21 20:54:55 +00001607 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001608 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001609
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001610 // Diagnose attempt to use '.' as a label.
1611 if (IDVal == ".")
1612 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1613
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001614 // Diagnose attempt to use a variable as a label.
1615 //
1616 // FIXME: Diagnostics. Note the location of the definition as a label.
1617 // FIXME: This doesn't diagnose assignment to a symbol which has been
1618 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001619 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001620 if (LocalLabelVal == -1) {
1621 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001622 StringRef RewrittenLabel =
1623 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001624 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001625 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001626 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1627 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001628 IDVal = RewrittenLabel;
1629 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001630 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001631 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001632 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001633 // End of Labels should be treated as end of line for lexing
1634 // purposes but that information is not available to the Lexer who
1635 // does not understand Labels. This may cause us to see a Hash
1636 // here instead of a preprocessor line comment.
1637 if (getTok().is(AsmToken::Hash)) {
1638 StringRef CommentStr = parseStringToEndOfStatement();
1639 Lexer.Lex();
1640 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1641 }
1642
Nirav Dave8ea792d2016-07-13 14:03:12 +00001643 // Consume any end of statement token, if present, to avoid spurious
1644 // AddBlankLine calls().
1645 if (getTok().is(AsmToken::EndOfStatement)) {
1646 Lex();
1647 }
1648
Daniel Dunbare73b2672009-08-26 22:13:22 +00001649 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001650 if (!ParsingInlineAsm)
Rafael Espindolabe991572017-02-10 15:13:12 +00001651 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001652
Kevin Enderbye7739d42011-12-09 18:09:40 +00001653 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001654 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001655 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001656 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1657 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001658
Tim Northover1744d0a2013-10-25 12:49:50 +00001659 getTargetParser().onLabelParsed(Sym);
1660
Eli Friedman0f4871d2012-10-22 23:58:19 +00001661 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001662 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001663
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001664 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001665 if (!getTargetParser().equalIsAsmAssignment())
1666 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001667 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001668 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001669
Jim Grosbach4b905842013-09-20 23:08:21 +00001670 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001671
1672 default: // Normal instruction or directive.
1673 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001674 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001675
1676 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001677 if (areMacrosEnabled())
1678 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1679 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001680 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001681
Michael J. Spencer530ce852010-10-09 11:00:50 +00001682 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001683
Eli Bendersky17233942013-01-15 22:59:42 +00001684 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001685 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001686 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001687 //
Eli Bendersky17233942013-01-15 22:59:42 +00001688 // 1. The target-specific assembly parser. Some directives are target
1689 // specific or may potentially behave differently on certain targets.
1690 // 2. Asm parser extensions. For example, platform-specific parsers
1691 // (like the ELF parser) register themselves as extensions.
1692 // 3. The generic directive parser implemented by this class. These are
1693 // all the directives that behave in a target and platform independent
1694 // manner, or at least have a default behavior that's shared between
1695 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001696
Oliver Stannard21718282016-07-26 14:19:47 +00001697 getTargetParser().flushPendingInstructions(getStreamer());
1698
Nirav Dave2364748a2016-09-16 18:30:20 +00001699 SMLoc StartTokLoc = getTok().getLoc();
1700 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1701
1702 if (hasPendingError())
1703 return true;
1704 // Currently the return value should be true if we are
1705 // uninterested but as this is at odds with the standard parsing
1706 // convention (return true = error) we have instances of a parsed
1707 // directive that fails returning true as an error. Catch these
1708 // cases as best as possible errors here.
1709 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1710 return true;
1711 // Return if we did some parsing or believe we succeeded.
1712 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001713 return false;
1714
Alp Tokercb402912014-01-24 17:20:08 +00001715 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001716 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001717 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1718 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001719 if (Handler.first)
1720 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1721
1722 // Finally, if no one else is interested in this directive, it must be
1723 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001724 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001725 default:
1726 break;
1727 case DK_SET:
1728 case DK_EQU:
1729 return parseDirectiveSet(IDVal, true);
1730 case DK_EQUIV:
1731 return parseDirectiveSet(IDVal, false);
1732 case DK_ASCII:
1733 return parseDirectiveAscii(IDVal, false);
1734 case DK_ASCIZ:
1735 case DK_STRING:
1736 return parseDirectiveAscii(IDVal, true);
1737 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001738 case DK_DC_B:
1739 return parseDirectiveValue(IDVal, 1);
1740 case DK_DC:
1741 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001742 case DK_SHORT:
1743 case DK_VALUE:
1744 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001745 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001746 case DK_LONG:
1747 case DK_INT:
1748 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001749 case DK_DC_L:
1750 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001751 case DK_QUAD:
1752 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001753 return parseDirectiveValue(IDVal, 8);
1754 case DK_DC_A:
1755 return parseDirectiveValue(IDVal,
1756 getContext().getAsmInfo()->getPointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001757 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001758 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001759 case DK_SINGLE:
1760 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001761 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001762 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001763 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001764 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001765 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001766 case DK_ALIGN: {
1767 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1768 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1769 }
1770 case DK_ALIGN32: {
1771 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1772 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1773 }
1774 case DK_BALIGN:
1775 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1776 case DK_BALIGNW:
1777 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1778 case DK_BALIGNL:
1779 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1780 case DK_P2ALIGN:
1781 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1782 case DK_P2ALIGNW:
1783 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1784 case DK_P2ALIGNL:
1785 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1786 case DK_ORG:
1787 return parseDirectiveOrg();
1788 case DK_FILL:
1789 return parseDirectiveFill();
1790 case DK_ZERO:
1791 return parseDirectiveZero();
1792 case DK_EXTERN:
1793 eatToEndOfStatement(); // .extern is the default, ignore it.
1794 return false;
1795 case DK_GLOBL:
1796 case DK_GLOBAL:
1797 return parseDirectiveSymbolAttribute(MCSA_Global);
1798 case DK_LAZY_REFERENCE:
1799 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1800 case DK_NO_DEAD_STRIP:
1801 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1802 case DK_SYMBOL_RESOLVER:
1803 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1804 case DK_PRIVATE_EXTERN:
1805 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1806 case DK_REFERENCE:
1807 return parseDirectiveSymbolAttribute(MCSA_Reference);
1808 case DK_WEAK_DEFINITION:
1809 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1810 case DK_WEAK_REFERENCE:
1811 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1812 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1813 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1814 case DK_COMM:
1815 case DK_COMMON:
1816 return parseDirectiveComm(/*IsLocal=*/false);
1817 case DK_LCOMM:
1818 return parseDirectiveComm(/*IsLocal=*/true);
1819 case DK_ABORT:
1820 return parseDirectiveAbort();
1821 case DK_INCLUDE:
1822 return parseDirectiveInclude();
1823 case DK_INCBIN:
1824 return parseDirectiveIncbin();
1825 case DK_CODE16:
1826 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001827 return TokError(Twine(IDVal) +
1828 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001829 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001830 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001831 case DK_IRP:
1832 return parseDirectiveIrp(IDLoc);
1833 case DK_IRPC:
1834 return parseDirectiveIrpc(IDLoc);
1835 case DK_ENDR:
1836 return parseDirectiveEndr(IDLoc);
1837 case DK_BUNDLE_ALIGN_MODE:
1838 return parseDirectiveBundleAlignMode();
1839 case DK_BUNDLE_LOCK:
1840 return parseDirectiveBundleLock();
1841 case DK_BUNDLE_UNLOCK:
1842 return parseDirectiveBundleUnlock();
1843 case DK_SLEB128:
1844 return parseDirectiveLEB128(true);
1845 case DK_ULEB128:
1846 return parseDirectiveLEB128(false);
1847 case DK_SPACE:
1848 case DK_SKIP:
1849 return parseDirectiveSpace(IDVal);
1850 case DK_FILE:
1851 return parseDirectiveFile(IDLoc);
1852 case DK_LINE:
1853 return parseDirectiveLine();
1854 case DK_LOC:
1855 return parseDirectiveLoc();
1856 case DK_STABS:
1857 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001858 case DK_CV_FILE:
1859 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001860 case DK_CV_FUNC_ID:
1861 return parseDirectiveCVFuncId();
1862 case DK_CV_INLINE_SITE_ID:
1863 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001864 case DK_CV_LOC:
1865 return parseDirectiveCVLoc();
1866 case DK_CV_LINETABLE:
1867 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001868 case DK_CV_INLINE_LINETABLE:
1869 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001870 case DK_CV_DEF_RANGE:
1871 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001872 case DK_CV_STRINGTABLE:
1873 return parseDirectiveCVStringTable();
1874 case DK_CV_FILECHECKSUMS:
1875 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001876 case DK_CFI_SECTIONS:
1877 return parseDirectiveCFISections();
1878 case DK_CFI_STARTPROC:
1879 return parseDirectiveCFIStartProc();
1880 case DK_CFI_ENDPROC:
1881 return parseDirectiveCFIEndProc();
1882 case DK_CFI_DEF_CFA:
1883 return parseDirectiveCFIDefCfa(IDLoc);
1884 case DK_CFI_DEF_CFA_OFFSET:
1885 return parseDirectiveCFIDefCfaOffset();
1886 case DK_CFI_ADJUST_CFA_OFFSET:
1887 return parseDirectiveCFIAdjustCfaOffset();
1888 case DK_CFI_DEF_CFA_REGISTER:
1889 return parseDirectiveCFIDefCfaRegister(IDLoc);
1890 case DK_CFI_OFFSET:
1891 return parseDirectiveCFIOffset(IDLoc);
1892 case DK_CFI_REL_OFFSET:
1893 return parseDirectiveCFIRelOffset(IDLoc);
1894 case DK_CFI_PERSONALITY:
1895 return parseDirectiveCFIPersonalityOrLsda(true);
1896 case DK_CFI_LSDA:
1897 return parseDirectiveCFIPersonalityOrLsda(false);
1898 case DK_CFI_REMEMBER_STATE:
1899 return parseDirectiveCFIRememberState();
1900 case DK_CFI_RESTORE_STATE:
1901 return parseDirectiveCFIRestoreState();
1902 case DK_CFI_SAME_VALUE:
1903 return parseDirectiveCFISameValue(IDLoc);
1904 case DK_CFI_RESTORE:
1905 return parseDirectiveCFIRestore(IDLoc);
1906 case DK_CFI_ESCAPE:
1907 return parseDirectiveCFIEscape();
1908 case DK_CFI_SIGNAL_FRAME:
1909 return parseDirectiveCFISignalFrame();
1910 case DK_CFI_UNDEFINED:
1911 return parseDirectiveCFIUndefined(IDLoc);
1912 case DK_CFI_REGISTER:
1913 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001914 case DK_CFI_WINDOW_SAVE:
1915 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001916 case DK_MACROS_ON:
1917 case DK_MACROS_OFF:
1918 return parseDirectiveMacrosOnOff(IDVal);
1919 case DK_MACRO:
1920 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001921 case DK_EXITM:
1922 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001923 case DK_ENDM:
1924 case DK_ENDMACRO:
1925 return parseDirectiveEndMacro(IDVal);
1926 case DK_PURGEM:
1927 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001928 case DK_END:
1929 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001930 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001931 return parseDirectiveError(IDLoc, false);
1932 case DK_ERROR:
1933 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001934 case DK_WARNING:
1935 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001936 case DK_RELOC:
1937 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001938 case DK_DCB:
1939 case DK_DCB_W:
1940 return parseDirectiveDCB(IDVal, 2);
1941 case DK_DCB_B:
1942 return parseDirectiveDCB(IDVal, 1);
1943 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001944 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001945 case DK_DCB_L:
1946 return parseDirectiveDCB(IDVal, 4);
1947 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001948 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00001949 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001950 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00001951 return TokError(Twine(IDVal) +
1952 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00001953 case DK_DS:
1954 case DK_DS_W:
1955 return parseDirectiveDS(IDVal, 2);
1956 case DK_DS_B:
1957 return parseDirectiveDS(IDVal, 1);
1958 case DK_DS_D:
1959 return parseDirectiveDS(IDVal, 8);
1960 case DK_DS_L:
1961 case DK_DS_S:
1962 return parseDirectiveDS(IDVal, 4);
1963 case DK_DS_P:
1964 case DK_DS_X:
1965 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00001966 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001967
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001968 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001969 }
Chris Lattner36e02122009-06-21 20:54:55 +00001970
Chad Rosierc7f552c2013-02-12 21:33:51 +00001971 // __asm _emit or __asm __emit
1972 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1973 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001974 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001975
1976 // __asm align
1977 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001978 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001979
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001980 if (ParsingInlineAsm && (IDVal == "even"))
1981 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00001982 if (checkForValidSection())
1983 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001984
Chris Lattner7cbfa442010-05-19 23:34:33 +00001985 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001986 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001987 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00001988 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1989 Info.ParsedOperands);
1990 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001991
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001992 // Dump the parsed representation, if requested.
1993 if (getShowParsedOperands()) {
1994 SmallString<256> Str;
1995 raw_svector_ostream OS(Str);
1996 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001997 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001998 if (i != 0)
1999 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002000 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002001 }
2002 OS << "]";
2003
Jim Grosbach4b905842013-09-20 23:08:21 +00002004 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002005 }
2006
Nirav Dave2364748a2016-09-16 18:30:20 +00002007 // Fail even if ParseInstruction erroneously returns false.
2008 if (hasPendingError() || ParseHadError)
2009 return true;
2010
Oliver Stannard8b273082014-06-19 15:52:37 +00002011 // If we are generating dwarf for the current section then generate a .loc
2012 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002013 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002014 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002015 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002016 unsigned Line;
2017 if (ActiveMacros.empty())
2018 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2019 else
Frederic Riss16238d92015-06-25 21:57:33 +00002020 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2021 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002022
Eli Bendersky88024712013-01-16 19:32:36 +00002023 // If we previously parsed a cpp hash file line comment then make sure the
2024 // current Dwarf File is for the CppHashFilename if not then emit the
2025 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002026 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002027 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002028 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002029 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002030
Jim Grosbach4b905842013-09-20 23:08:21 +00002031 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2032 // cache with the different Loc from the call above we save the last
2033 // info we queried here with SrcMgr.FindLineNumber().
2034 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002035 if (LastQueryIDLoc == CppHashInfo.Loc &&
2036 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002037 CppHashLocLineNo = LastQueryLine;
2038 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002039 CppHashLocLineNo =
2040 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002041 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002042 LastQueryIDLoc = CppHashInfo.Loc;
2043 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002044 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002045 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002046 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002047
Jim Grosbach4b905842013-09-20 23:08:21 +00002048 getStreamer().EmitDwarfLocDirective(
2049 getContext().getGenDwarfFileNumber(), Line, 0,
2050 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2051 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002052 }
2053
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002054 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002055 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002056 uint64_t ErrorInfo;
Nirav Dave2364748a2016-09-16 18:30:20 +00002057 if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2058 Info.ParsedOperands, Out,
2059 ErrorInfo, ParsingInlineAsm))
2060 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002061 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002062 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002063}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002064
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002065// Parse and erase curly braces marking block start/end
2066bool
2067AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2068 // Identify curly brace marking block start/end
2069 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2070 return false;
2071
2072 SMLoc StartLoc = Lexer.getLoc();
2073 Lex(); // Eat the brace
2074 if (Lexer.is(AsmToken::EndOfStatement))
2075 Lex(); // Eat EndOfStatement following the brace
2076
2077 // Erase the block start/end brace from the output asm string
2078 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2079 StartLoc.getPointer());
2080 return true;
2081}
2082
Jim Grosbach4b905842013-09-20 23:08:21 +00002083/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002084/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002085bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002086 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002087 // Lexer only ever emits HashDirective if it fully formed if it's
2088 // done the checking already so this is an internal error.
2089 assert(getTok().is(AsmToken::Integer) &&
2090 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002091 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002092 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002093 assert(getTok().is(AsmToken::String) &&
2094 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002095 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002096 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002097
Kevin Enderby72553612011-09-13 23:45:18 +00002098 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002099 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002100
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002101 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002102 CppHashInfo.Loc = L;
2103 CppHashInfo.Filename = Filename;
2104 CppHashInfo.LineNumber = LineNumber;
2105 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002106 return false;
2107}
2108
Jim Grosbach4b905842013-09-20 23:08:21 +00002109/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002110/// for the Filename and LineNo if any in the diagnostic.
2111void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002112 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002113 raw_ostream &OS = errs();
2114
2115 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002116 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002117 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2118 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002119 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002120
Jim Grosbach4b905842013-09-20 23:08:21 +00002121 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002122 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002123 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2124 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2125 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002126 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2127 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002128 }
2129
Eric Christophera7c32732012-12-18 00:30:54 +00002130 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002131 // manager changed or buffer changed (like in a nested include) then just
2132 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002133 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002134 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002135 if (Parser->SavedDiagHandler)
2136 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2137 else
Craig Topper353eda42014-04-24 06:44:33 +00002138 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002139 return;
2140 }
2141
Eric Christophera7c32732012-12-18 00:30:54 +00002142 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002143 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2144 // for the diagnostic.
2145 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002146
2147 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2148 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002149 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002150 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002151 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002152
Jim Grosbach4b905842013-09-20 23:08:21 +00002153 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2154 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002155 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002156
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002157 if (Parser->SavedDiagHandler)
2158 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2159 else
Craig Topper353eda42014-04-24 06:44:33 +00002160 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002161}
2162
Rafael Espindola2c064482012-08-21 18:29:30 +00002163// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2164// difference being that that function accepts '@' as part of identifiers and
2165// we can't do that. AsmLexer.cpp should probably be changed to handle
2166// '@' as a special case when needed.
2167static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002168 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2169 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002170}
2171
Rafael Espindola34b9c512012-06-03 23:57:14 +00002172bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002173 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002174 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002175 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002176 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002177 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002178 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002179 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002180
Preston Gurd05500642012-09-19 20:36:12 +00002181 // A macro without parameters is handled differently on Darwin:
2182 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002183 while (!Body.empty()) {
2184 // Scan for the next substitution.
2185 std::size_t End = Body.size(), Pos = 0;
2186 for (; Pos != End; ++Pos) {
2187 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002188 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002189 // This macro has no parameters, look for $0, $1, etc.
2190 if (Body[Pos] != '$' || Pos + 1 == End)
2191 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002192
Rafael Espindola1134ab232011-06-05 02:43:45 +00002193 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002194 if (Next == '$' || Next == 'n' ||
2195 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002196 break;
2197 } else {
2198 // This macro has parameters, look for \foo, \bar, etc.
2199 if (Body[Pos] == '\\' && Pos + 1 != End)
2200 break;
2201 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002202 }
2203
2204 // Add the prefix.
2205 OS << Body.slice(0, Pos);
2206
2207 // Check if we reached the end.
2208 if (Pos == End)
2209 break;
2210
Benjamin Kramer513e7442014-02-20 13:36:32 +00002211 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002212 switch (Body[Pos + 1]) {
2213 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002214 case '$':
2215 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002216 break;
2217
Jim Grosbach4b905842013-09-20 23:08:21 +00002218 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002219 case 'n':
2220 OS << A.size();
2221 break;
2222
Jim Grosbach4b905842013-09-20 23:08:21 +00002223 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002224 default: {
2225 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002226 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002227 if (Index >= A.size())
2228 break;
2229
2230 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002231 for (const AsmToken &Token : A[Index])
2232 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002233 break;
2234 }
2235 }
2236 Pos += 2;
2237 } else {
2238 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002239
2240 // Check for the \@ pseudo-variable.
2241 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002242 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002243 else
2244 while (isIdentifierChar(Body[I]) && I + 1 != End)
2245 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002246
Jim Grosbach4b905842013-09-20 23:08:21 +00002247 const char *Begin = Body.data() + Pos + 1;
2248 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002249 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002250
Toma Tabacu217116e2015-04-27 10:50:29 +00002251 if (Argument == "@") {
2252 OS << NumOfMacroInstantiations;
2253 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002254 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002255 for (; Index < NParameters; ++Index)
2256 if (Parameters[Index].Name == Argument)
2257 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002258
Toma Tabacu217116e2015-04-27 10:50:29 +00002259 if (Index == NParameters) {
2260 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2261 Pos += 3;
2262 else {
2263 OS << '\\' << Argument;
2264 Pos = I;
2265 }
2266 } else {
2267 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002268 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002269 // We expect no quotes around the string's contents when
2270 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002271 if (Token.getKind() != AsmToken::String || VarargParameter)
2272 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002273 else
Craig Topper84008482015-10-10 05:38:14 +00002274 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002275
2276 Pos += 1 + Argument.size();
2277 }
Preston Gurd05500642012-09-19 20:36:12 +00002278 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002279 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002280 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002281 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002282 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002283
Rafael Espindola1134ab232011-06-05 02:43:45 +00002284 return false;
2285}
Daniel Dunbar43235712010-07-18 18:54:11 +00002286
Nico Weber2a8f9222014-07-24 16:29:04 +00002287MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002288 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002289 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002290 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002291
Jim Grosbach4b905842013-09-20 23:08:21 +00002292static bool isOperator(AsmToken::TokenKind kind) {
2293 switch (kind) {
2294 default:
2295 return false;
2296 case AsmToken::Plus:
2297 case AsmToken::Minus:
2298 case AsmToken::Tilde:
2299 case AsmToken::Slash:
2300 case AsmToken::Star:
2301 case AsmToken::Dot:
2302 case AsmToken::Equal:
2303 case AsmToken::EqualEqual:
2304 case AsmToken::Pipe:
2305 case AsmToken::PipePipe:
2306 case AsmToken::Caret:
2307 case AsmToken::Amp:
2308 case AsmToken::AmpAmp:
2309 case AsmToken::Exclaim:
2310 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002311 case AsmToken::Less:
2312 case AsmToken::LessEqual:
2313 case AsmToken::LessLess:
2314 case AsmToken::LessGreater:
2315 case AsmToken::Greater:
2316 case AsmToken::GreaterEqual:
2317 case AsmToken::GreaterGreater:
2318 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002319 }
2320}
2321
David Majnemer16252452014-01-29 00:07:39 +00002322namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002323
David Majnemer16252452014-01-29 00:07:39 +00002324class AsmLexerSkipSpaceRAII {
2325public:
2326 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2327 Lexer.setSkipSpace(SkipSpace);
2328 }
2329
2330 ~AsmLexerSkipSpaceRAII() {
2331 Lexer.setSkipSpace(true);
2332 }
2333
2334private:
2335 AsmLexer &Lexer;
2336};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002337
2338} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002339
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002340bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2341
2342 if (Vararg) {
2343 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2344 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002345 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002346 }
2347 return false;
2348 }
2349
Rafael Espindola768b41c2012-06-15 14:02:34 +00002350 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002351
David Majnemer16252452014-01-29 00:07:39 +00002352 // Darwin doesn't use spaces to delmit arguments.
2353 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002354
Scott Egertona1fa68a2016-02-11 13:48:49 +00002355 bool SpaceEaten;
2356
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002357 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002358 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002359 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002360 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002361
Scott Egertona1fa68a2016-02-11 13:48:49 +00002362 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002363
Scott Egertona1fa68a2016-02-11 13:48:49 +00002364 if (Lexer.is(AsmToken::Comma))
2365 break;
2366
2367 if (Lexer.is(AsmToken::Space)) {
2368 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002369 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002370 }
Preston Gurd05500642012-09-19 20:36:12 +00002371
2372 // Spaces can delimit parameters, but could also be part an expression.
2373 // If the token after a space is an operator, add the token and the next
2374 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002375 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002376 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002377 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002378 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002379
Scott Egertona1fa68a2016-02-11 13:48:49 +00002380 // Whitespace after an operator can be ignored.
2381 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002382 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002383
2384 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002385 }
2386 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002387 if (SpaceEaten)
2388 break;
Preston Gurd05500642012-09-19 20:36:12 +00002389 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002390
Jim Grosbach4b905842013-09-20 23:08:21 +00002391 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002392 // to be able to fill in the remaining default parameter values
2393 if (Lexer.is(AsmToken::EndOfStatement))
2394 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002395
2396 // Adjust the current parentheses level.
2397 if (Lexer.is(AsmToken::LParen))
2398 ++ParenLevel;
2399 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2400 --ParenLevel;
2401
2402 // Append the token to the current argument list.
2403 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002404 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002405 }
Preston Gurd05500642012-09-19 20:36:12 +00002406
Rafael Espindola768b41c2012-06-15 14:02:34 +00002407 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002408 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002409 return false;
2410}
2411
2412// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002413bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002414 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002415 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002416 bool NamedParametersFound = false;
2417 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002418
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002419 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002420 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002421
Rafael Espindola768b41c2012-06-15 14:02:34 +00002422 // Parse two kinds of macro invocations:
2423 // - macros defined without any parameters accept an arbitrary number of them
2424 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002425 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002426 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2427 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002428 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002429 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002430
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002431 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002432 if (parseIdentifier(FA.Name))
2433 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002434
Nirav Dave2364748a2016-09-16 18:30:20 +00002435 if (Lexer.isNot(AsmToken::Equal))
2436 return TokError("expected '=' after formal parameter identifier");
2437
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002438 Lex();
2439
2440 NamedParametersFound = true;
2441 }
2442
Nirav Dave2364748a2016-09-16 18:30:20 +00002443 if (NamedParametersFound && FA.Name.empty())
2444 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002445
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002446 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2447 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002448 return true;
2449
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002450 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002451 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002452 unsigned FAI = 0;
2453 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002454 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002455 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002456
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002457 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002458 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002459 return Error(IDLoc, "parameter named '" + FA.Name +
2460 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002461 }
2462 PI = FAI;
2463 }
2464
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002465 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002466 if (A.size() <= PI)
2467 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002468 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002469
2470 if (FALocs.size() <= PI)
2471 FALocs.resize(PI + 1);
2472
2473 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002474 }
Jim Grosbach206661622012-07-30 22:44:17 +00002475
Preston Gurd242ed3152012-09-19 20:29:04 +00002476 // At the end of the statement, fill in remaining arguments that have
2477 // default values. If there aren't any, then the next argument is
2478 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002479 if (Lexer.is(AsmToken::EndOfStatement)) {
2480 bool Failure = false;
2481 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2482 if (A[FAI].empty()) {
2483 if (M->Parameters[FAI].Required) {
2484 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2485 "missing value for required parameter "
2486 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2487 Failure = true;
2488 }
2489
2490 if (!M->Parameters[FAI].Value.empty())
2491 A[FAI] = M->Parameters[FAI].Value;
2492 }
2493 }
2494 return Failure;
2495 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002496
2497 if (Lexer.is(AsmToken::Comma))
2498 Lex();
2499 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002500
2501 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002502}
2503
Jim Grosbach4b905842013-09-20 23:08:21 +00002504const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002505 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2506 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002507}
2508
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002509void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2510 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002511}
2512
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002513void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002514
Jim Grosbach4b905842013-09-20 23:08:21 +00002515bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002516 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2517 // eliminate this, although we should protect against infinite loops.
2518 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2519 if (ActiveMacros.size() == MaxNestingDepth) {
2520 std::ostringstream MaxNestingDepthError;
2521 MaxNestingDepthError << "macros cannot be nested more than "
2522 << MaxNestingDepth << " levels deep."
2523 << " Use -asm-macro-max-nesting-depth to increase "
2524 "this limit.";
2525 return TokError(MaxNestingDepthError.str());
2526 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002527
Eli Bendersky38274122013-01-14 23:22:36 +00002528 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002529 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002530 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002531
Rafael Espindola1134ab232011-06-05 02:43:45 +00002532 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2533 // to hold the macro body with substitutions.
2534 SmallString<256> Buf;
2535 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002536 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002537
Toma Tabacu217116e2015-04-27 10:50:29 +00002538 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002539 return true;
2540
Eli Bendersky38274122013-01-14 23:22:36 +00002541 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002542 // instantiation.
2543 OS << ".endmacro\n";
2544
Rafael Espindola3560ff22014-08-27 20:03:13 +00002545 std::unique_ptr<MemoryBuffer> Instantiation =
2546 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002547
Daniel Dunbar43235712010-07-18 18:54:11 +00002548 // Create the macro instantiation object and add to the current macro
2549 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002550 MacroInstantiation *MI = new MacroInstantiation(
2551 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002552 ActiveMacros.push_back(MI);
2553
Toma Tabacu217116e2015-04-27 10:50:29 +00002554 ++NumOfMacroInstantiations;
2555
Daniel Dunbar43235712010-07-18 18:54:11 +00002556 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002557 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002558 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002559 Lex();
2560
2561 return false;
2562}
2563
Jim Grosbach4b905842013-09-20 23:08:21 +00002564void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002565 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002566 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002567 Lex();
2568
2569 // Pop the instantiation entry.
2570 delete ActiveMacros.back();
2571 ActiveMacros.pop_back();
2572}
2573
Jim Grosbach4b905842013-09-20 23:08:21 +00002574bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002575 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002576 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002577 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002578 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2579 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002580 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002581
Pete Cooper80d21cb2015-06-22 19:35:57 +00002582 if (!Sym) {
2583 // In the case where we parse an expression starting with a '.', we will
2584 // not generate an error, nor will we create a symbol. In this case we
2585 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002586 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002587 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002588
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002589 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002590 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002591 if (NoDeadStrip)
2592 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2593
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002594 return false;
2595}
2596
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002597/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002598/// ::= identifier
2599/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002600bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002601 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002602 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2603 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002604 // handle this as a context dependent token, instead we detect adjacent tokens
2605 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002606 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2607 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002608
Hans Wennborgce69d772013-10-18 20:46:28 +00002609 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002610
2611 AsmToken Buf[1];
2612 Lexer.peekTokens(Buf, false);
2613
2614 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002615 return true;
2616
Hans Wennborgce69d772013-10-18 20:46:28 +00002617 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002618 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002619 return true;
2620
Nirav Daved0463322016-10-12 13:58:07 +00002621 // eat $ or @
2622 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002623 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002624 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002625 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002626 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002627 return false;
2628 }
2629
Jim Grosbach4b905842013-09-20 23:08:21 +00002630 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002631 return true;
2632
Sean Callanan936b0d32010-01-19 21:44:56 +00002633 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002634
Sean Callanan686ed8d2010-01-19 20:22:31 +00002635 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002636
2637 return false;
2638}
2639
Jim Grosbach4b905842013-09-20 23:08:21 +00002640/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002641/// ::= .equ identifier ',' expression
2642/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002643/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002644bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002645 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002646 if (check(parseIdentifier(Name), "expected identifier") ||
2647 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2648 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2649 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002650}
2651
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002652bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002653 if (check(getTok().isNot(AsmToken::String), "expected string"))
2654 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002655
2656 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002657 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002658 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2659 if (Str[i] != '\\') {
2660 Data += Str[i];
2661 continue;
2662 }
2663
2664 // Recognize escaped characters. Note that this escape semantics currently
2665 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2666 ++i;
2667 if (i == e)
2668 return TokError("unexpected backslash at end of string");
2669
2670 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002671 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002672 // Consume up to three octal characters.
2673 unsigned Value = Str[i] - '0';
2674
Jim Grosbach4b905842013-09-20 23:08:21 +00002675 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002676 ++i;
2677 Value = Value * 8 + (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 }
2683 }
2684
2685 if (Value > 255)
2686 return TokError("invalid octal escape sequence (out of range)");
2687
Jim Grosbach4b905842013-09-20 23:08:21 +00002688 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002689 continue;
2690 }
2691
2692 // Otherwise recognize individual escapes.
2693 switch (Str[i]) {
2694 default:
2695 // Just reject invalid escape sequences for now.
2696 return TokError("invalid escape sequence (unrecognized character)");
2697
2698 case 'b': Data += '\b'; break;
2699 case 'f': Data += '\f'; break;
2700 case 'n': Data += '\n'; break;
2701 case 'r': Data += '\r'; break;
2702 case 't': Data += '\t'; break;
2703 case '"': Data += '"'; break;
2704 case '\\': Data += '\\'; break;
2705 }
2706 }
2707
Nirav Davea645433c2016-07-18 15:24:03 +00002708 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002709 return false;
2710}
2711
Jim Grosbach4b905842013-09-20 23:08:21 +00002712/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002713/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002714bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002715 auto parseOp = [&]() -> bool {
2716 std::string Data;
2717 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002718 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002719 getStreamer().EmitBytes(Data);
2720 if (ZeroTerminated)
2721 getStreamer().EmitBytes(StringRef("\0", 1));
2722 return false;
2723 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002724
Nirav Dave1a9044b2016-10-24 14:35:29 +00002725 if (parseMany(parseOp))
2726 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002727 return false;
2728}
2729
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002730/// parseDirectiveReloc
2731/// ::= .reloc expression , identifier [ , expression ]
2732bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2733 const MCExpr *Offset;
2734 const MCExpr *Expr = nullptr;
2735
2736 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002737 int64_t OffsetValue;
2738 // We can only deal with constant expressions at the moment.
2739
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002740 if (parseExpression(Offset))
2741 return true;
2742
Nirav Davea645433c2016-07-18 15:24:03 +00002743 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2744 "expression is not a constant value") ||
2745 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2746 parseToken(AsmToken::Comma, "expected comma") ||
2747 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2748 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002749
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002750 SMLoc NameLoc = Lexer.getTok().getLoc();
2751 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002752 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002753
2754 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002755 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002756 SMLoc ExprLoc = Lexer.getLoc();
2757 if (parseExpression(Expr))
2758 return true;
2759
2760 MCValue Value;
2761 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2762 return Error(ExprLoc, "expression must be relocatable");
2763 }
2764
Nirav Davea645433c2016-07-18 15:24:03 +00002765 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002766 "unexpected token in .reloc directive"))
2767 return true;
2768
2769 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2770 return Error(NameLoc, "unknown relocation name");
2771
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002772 return false;
2773}
2774
Jim Grosbach4b905842013-09-20 23:08:21 +00002775/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002776/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002777bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2778 auto parseOp = [&]() -> bool {
2779 const MCExpr *Value;
2780 SMLoc ExprLoc = getLexer().getLoc();
2781 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002782 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002783 // Special case constant expressions to match code generator.
2784 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2785 assert(Size <= 8 && "Invalid size");
2786 uint64_t IntValue = MCE->getValue();
2787 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2788 return Error(ExprLoc, "out of range literal value");
2789 getStreamer().EmitIntValue(IntValue, Size);
2790 } else
2791 getStreamer().EmitValue(Value, Size, ExprLoc);
2792 return false;
2793 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002794
Nirav Dave1a9044b2016-10-24 14:35:29 +00002795 if (parseMany(parseOp))
2796 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002797 return false;
2798}
2799
David Woodhoused6de0d92014-02-01 16:20:59 +00002800/// ParseDirectiveOctaValue
2801/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002802
2803bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2804 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002805 if (checkForValidSection())
2806 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002807 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2808 return TokError("unknown token in expression");
2809 SMLoc ExprLoc = getTok().getLoc();
2810 APInt IntValue = getTok().getAPIntVal();
2811 uint64_t hi, lo;
2812 Lex();
2813 if (!IntValue.isIntN(128))
2814 return Error(ExprLoc, "out of range literal value");
2815 if (!IntValue.isIntN(64)) {
2816 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2817 lo = IntValue.getLoBits(64).getZExtValue();
2818 } else {
2819 hi = 0;
2820 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002821 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002822 if (MAI.isLittleEndian()) {
2823 getStreamer().EmitIntValue(lo, 8);
2824 getStreamer().EmitIntValue(hi, 8);
2825 } else {
2826 getStreamer().EmitIntValue(hi, 8);
2827 getStreamer().EmitIntValue(lo, 8);
2828 }
2829 return false;
2830 };
David Woodhoused6de0d92014-02-01 16:20:59 +00002831
Nirav Dave1a9044b2016-10-24 14:35:29 +00002832 if (parseMany(parseOp))
2833 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00002834 return false;
2835}
2836
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002837bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2838 // We don't truly support arithmetic on floating point expressions, so we
2839 // have to manually parse unary prefixes.
2840 bool IsNeg = false;
2841 if (getLexer().is(AsmToken::Minus)) {
2842 Lexer.Lex();
2843 IsNeg = true;
2844 } else if (getLexer().is(AsmToken::Plus))
2845 Lexer.Lex();
2846
2847 if (Lexer.is(AsmToken::Error))
2848 return TokError(Lexer.getErr());
2849 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2850 Lexer.isNot(AsmToken::Identifier))
2851 return TokError("unexpected token in directive");
2852
2853 // Convert to an APFloat.
2854 APFloat Value(Semantics);
2855 StringRef IDVal = getTok().getString();
2856 if (getLexer().is(AsmToken::Identifier)) {
2857 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2858 Value = APFloat::getInf(Semantics);
2859 else if (!IDVal.compare_lower("nan"))
2860 Value = APFloat::getNaN(Semantics, false, ~0);
2861 else
2862 return TokError("invalid floating point literal");
2863 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2864 APFloat::opInvalidOp)
2865 return TokError("invalid floating point literal");
2866 if (IsNeg)
2867 Value.changeSign();
2868
2869 // Consume the numeric token.
2870 Lex();
2871
2872 Res = Value.bitcastToAPInt();
2873
2874 return false;
2875}
2876
Jim Grosbach4b905842013-09-20 23:08:21 +00002877/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002878/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002879bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2880 const fltSemantics &Semantics) {
2881 auto parseOp = [&]() -> bool {
2882 APInt AsInt;
2883 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002884 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002885 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2886 AsInt.getBitWidth() / 8);
2887 return false;
2888 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00002889
Nirav Dave1a9044b2016-10-24 14:35:29 +00002890 if (parseMany(parseOp))
2891 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00002892 return false;
2893}
2894
Jim Grosbach4b905842013-09-20 23:08:21 +00002895/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002896/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002897bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002898 SMLoc NumBytesLoc = Lexer.getLoc();
2899 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002900 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002901 return true;
2902
Rafael Espindolab91bac62010-10-05 19:42:57 +00002903 int64_t Val = 0;
2904 if (getLexer().is(AsmToken::Comma)) {
2905 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002906 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002907 return true;
2908 }
2909
Nirav Davea645433c2016-07-18 15:24:03 +00002910 if (parseToken(AsmToken::EndOfStatement,
2911 "unexpected token in '.zero' directive"))
2912 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002913 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002914
2915 return false;
2916}
2917
Jim Grosbach4b905842013-09-20 23:08:21 +00002918/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002919/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002920bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002921 SMLoc NumValuesLoc = Lexer.getLoc();
2922 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002923 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002924 return true;
2925
Roman Divackye33098f2013-09-24 17:44:41 +00002926 int64_t FillSize = 1;
2927 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002928
David Majnemer522d3db2014-02-01 07:19:38 +00002929 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002930
Nirav Dave1a9044b2016-10-24 14:35:29 +00002931 if (parseOptionalToken(AsmToken::Comma)) {
2932 SizeLoc = getTok().getLoc();
2933 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002934 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002935 if (parseOptionalToken(AsmToken::Comma)) {
2936 ExprLoc = getTok().getLoc();
2937 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00002938 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002939 }
2940 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002941 if (parseToken(AsmToken::EndOfStatement,
2942 "unexpected token in '.fill' directive"))
2943 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002944
David Majnemer522d3db2014-02-01 07:19:38 +00002945 if (FillSize < 0) {
2946 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002947 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002948 }
2949 if (FillSize > 8) {
2950 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2951 FillSize = 8;
2952 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002953
David Majnemer522d3db2014-02-01 07:19:38 +00002954 if (!isUInt<32>(FillExpr) && FillSize > 4)
2955 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2956
Petr Hosek67a94a72016-05-28 05:57:48 +00002957 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002958
2959 return false;
2960}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002961
Jim Grosbach4b905842013-09-20 23:08:21 +00002962/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002963/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002964bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002965 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00002966 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00002967 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002968 return true;
2969
2970 // Parse optional fill expression.
2971 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002972 if (parseOptionalToken(AsmToken::Comma))
2973 if (parseAbsoluteExpression(FillExpr))
2974 return addErrorSuffix(" in '.org' directive");
2975 if (parseToken(AsmToken::EndOfStatement))
2976 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00002977
Oliver Stannard268f42f2016-12-14 10:43:58 +00002978 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002979 return false;
2980}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002981
Jim Grosbach4b905842013-09-20 23:08:21 +00002982/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002983/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002984bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002985 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002986 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002987 SMLoc MaxBytesLoc;
2988 bool HasFillExpr = false;
2989 int64_t FillExpr = 0;
2990 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002991
2992 auto parseAlign = [&]() -> bool {
2993 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00002994 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002995 if (parseOptionalToken(AsmToken::Comma)) {
2996 // The fill expression can be omitted while specifying a maximum number of
2997 // alignment bytes, e.g:
2998 // .align 3,,4
2999 if (getTok().isNot(AsmToken::Comma)) {
3000 HasFillExpr = true;
3001 if (parseAbsoluteExpression(FillExpr))
3002 return true;
3003 }
3004 if (parseOptionalToken(AsmToken::Comma))
3005 if (parseTokenLoc(MaxBytesLoc) ||
3006 parseAbsoluteExpression(MaxBytesToFill))
3007 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003008 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003009 return parseToken(AsmToken::EndOfStatement);
3010 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003011
Nirav Dave1a9044b2016-10-24 14:35:29 +00003012 if (parseAlign())
3013 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003014
Nirav Dave2364748a2016-09-16 18:30:20 +00003015 // Always emit an alignment here even if we thrown an error.
3016 bool ReturnVal = false;
3017
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003018 // Compute alignment in bytes.
3019 if (IsPow2) {
3020 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003021 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003022 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003023 Alignment = 31;
3024 }
3025
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003026 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003027 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003028 // Reject alignments that aren't either a power of two or zero,
3029 // for gas compatibility. Alignment of zero is silently rounded
3030 // up to one.
3031 if (Alignment == 0)
3032 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003033 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003034 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003035 }
3036
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003037 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003038 if (MaxBytesLoc.isValid()) {
3039 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003040 ReturnVal |= Error(MaxBytesLoc,
3041 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003042 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003043 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003044 }
3045
3046 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003047 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003048 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003049 MaxBytesToFill = 0;
3050 }
3051 }
3052
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003053 // Check whether we should use optimal code alignment for this .align
3054 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003055 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003056 assert(Section && "must have section to emit alignment");
3057 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003058 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3059 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003060 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003061 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003062 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003063 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3064 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003065 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003066
Nirav Dave2364748a2016-09-16 18:30:20 +00003067 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003068}
3069
Jim Grosbach4b905842013-09-20 23:08:21 +00003070/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003071/// ::= .file [number] filename
3072/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003073bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003074 // FIXME: I'm not sure what this is.
3075 int64_t FileNumber = -1;
3076 SMLoc FileNumberLoc = getLexer().getLoc();
3077 if (getLexer().is(AsmToken::Integer)) {
3078 FileNumber = getTok().getIntVal();
3079 Lex();
3080
3081 if (FileNumber < 1)
3082 return TokError("file number less than one");
3083 }
3084
Nirav Davea645433c2016-07-18 15:24:03 +00003085 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003086
3087 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003088 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003089 if (check(getTok().isNot(AsmToken::String),
3090 "unexpected token in '.file' directive") ||
3091 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003092 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003093
3094 StringRef Directory;
3095 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003096 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003097 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003098 if (check(FileNumber == -1,
3099 "explicit path specified, but no file number") ||
3100 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003101 return true;
3102 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003103 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003104 } else {
3105 Filename = Path;
3106 }
3107
Nirav Davea645433c2016-07-18 15:24:03 +00003108 if (parseToken(AsmToken::EndOfStatement,
3109 "unexpected token in '.file' directive"))
3110 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003111
3112 if (FileNumber == -1)
3113 getStreamer().EmitFileDirective(Filename);
3114 else {
David Blaikie22748082016-05-26 00:22:26 +00003115 // If there is -g option as well as debug info from directive file,
3116 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003117 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003118 getContext().setGenDwarfForAssembly(false);
3119 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003120 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003121 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003122 }
3123
3124 return false;
3125}
3126
Jim Grosbach4b905842013-09-20 23:08:21 +00003127/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003128/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003129bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003130 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003131 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003132 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3133 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003134 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003135 // FIXME: Do something with the .line.
3136 }
Nirav Davea645433c2016-07-18 15:24:03 +00003137 if (parseToken(AsmToken::EndOfStatement,
3138 "unexpected token in '.line' directive"))
3139 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003140
3141 return false;
3142}
3143
Jim Grosbach4b905842013-09-20 23:08:21 +00003144/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003145/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3146/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3147/// The first number is a file number, must have been previously assigned with
3148/// a .file directive, the second number is the line number and optionally the
3149/// third number is a column position (zero if not specified). The remaining
3150/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003151bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003152 int64_t FileNumber = 0, LineNumber = 0;
3153 SMLoc Loc = getTok().getLoc();
3154 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3155 check(FileNumber < 1, Loc,
3156 "file number less than one in '.loc' directive") ||
3157 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3158 "unassigned file number in '.loc' directive"))
3159 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003160
Nirav Davea645433c2016-07-18 15:24:03 +00003161 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003162 if (getLexer().is(AsmToken::Integer)) {
3163 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003164 if (LineNumber < 0)
3165 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003166 Lex();
3167 }
3168
3169 int64_t ColumnPos = 0;
3170 if (getLexer().is(AsmToken::Integer)) {
3171 ColumnPos = getTok().getIntVal();
3172 if (ColumnPos < 0)
3173 return TokError("column position less than zero in '.loc' directive");
3174 Lex();
3175 }
3176
3177 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3178 unsigned Isa = 0;
3179 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003180
Nirav Dave1a9044b2016-10-24 14:35:29 +00003181 auto parseLocOp = [&]() -> bool {
3182 StringRef Name;
3183 SMLoc Loc = getTok().getLoc();
3184 if (parseIdentifier(Name))
3185 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003186
Nirav Dave1a9044b2016-10-24 14:35:29 +00003187 if (Name == "basic_block")
3188 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3189 else if (Name == "prologue_end")
3190 Flags |= DWARF2_FLAG_PROLOGUE_END;
3191 else if (Name == "epilogue_begin")
3192 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3193 else if (Name == "is_stmt") {
3194 Loc = getTok().getLoc();
3195 const MCExpr *Value;
3196 if (parseExpression(Value))
3197 return true;
3198 // The expression must be the constant 0 or 1.
3199 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3200 int Value = MCE->getValue();
3201 if (Value == 0)
3202 Flags &= ~DWARF2_FLAG_IS_STMT;
3203 else if (Value == 1)
3204 Flags |= DWARF2_FLAG_IS_STMT;
3205 else
3206 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003207 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003208 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003209 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003210 } else if (Name == "isa") {
3211 Loc = getTok().getLoc();
3212 const MCExpr *Value;
3213 if (parseExpression(Value))
3214 return true;
3215 // The expression must be a constant greater or equal to 0.
3216 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3217 int Value = MCE->getValue();
3218 if (Value < 0)
3219 return Error(Loc, "isa number less than zero");
3220 Isa = Value;
3221 } else {
3222 return Error(Loc, "isa number not a constant value");
3223 }
3224 } else if (Name == "discriminator") {
3225 if (parseAbsoluteExpression(Discriminator))
3226 return true;
3227 } else {
3228 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003229 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003230 return false;
3231 };
3232
Nirav Davee2369aa2016-10-26 17:28:58 +00003233 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003234 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003235
3236 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3237 Isa, Discriminator, StringRef());
3238
3239 return false;
3240}
3241
Jim Grosbach4b905842013-09-20 23:08:21 +00003242/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003243/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003244bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003245 return TokError("unsupported directive '.stabs'");
3246}
3247
Reid Kleckner2214ed82016-01-29 00:49:42 +00003248/// parseDirectiveCVFile
3249/// ::= .cv_file number filename
3250bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003251 SMLoc FileNumberLoc = getTok().getLoc();
3252 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003253 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003254
3255 if (parseIntToken(FileNumber,
3256 "expected file number in '.cv_file' directive") ||
3257 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3258 check(getTok().isNot(AsmToken::String),
3259 "unexpected token in '.cv_file' directive") ||
3260 // Usually directory and filename are together, otherwise just
3261 // directory. Allow the strings to have escaped octal character sequence.
3262 parseEscapedString(Filename) ||
3263 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003264 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003265 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003266
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003267 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003268 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003269
3270 return false;
3271}
3272
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003273bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3274 StringRef DirectiveName) {
3275 SMLoc Loc;
3276 return parseTokenLoc(Loc) ||
3277 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3278 "' directive") ||
3279 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3280 "expected function id within range [0, UINT_MAX)");
3281}
3282
3283bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3284 SMLoc Loc;
3285 return parseTokenLoc(Loc) ||
3286 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3287 "' directive") ||
3288 check(FileNumber < 1, Loc, "file number less than one in '" +
3289 DirectiveName + "' directive") ||
3290 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3291 "unassigned file number in '" + DirectiveName + "' directive");
3292}
3293
3294/// parseDirectiveCVFuncId
3295/// ::= .cv_func_id FunctionId
3296///
3297/// Introduces a function ID that can be used with .cv_loc.
3298bool AsmParser::parseDirectiveCVFuncId() {
3299 SMLoc FunctionIdLoc = getTok().getLoc();
3300 int64_t FunctionId;
3301
3302 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3303 parseToken(AsmToken::EndOfStatement,
3304 "unexpected token in '.cv_func_id' directive"))
3305 return true;
3306
3307 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003308 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003309
3310 return false;
3311}
3312
3313/// parseDirectiveCVInlineSiteId
3314/// ::= .cv_inline_site_id FunctionId
3315/// "within" IAFunc
3316/// "inlined_at" IAFile IALine [IACol]
3317///
3318/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3319/// at" source location information for use in the line table of the caller,
3320/// whether the caller is a real function or another inlined call site.
3321bool AsmParser::parseDirectiveCVInlineSiteId() {
3322 SMLoc FunctionIdLoc = getTok().getLoc();
3323 int64_t FunctionId;
3324 int64_t IAFunc;
3325 int64_t IAFile;
3326 int64_t IALine;
3327 int64_t IACol = 0;
3328
3329 // FunctionId
3330 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3331 return true;
3332
3333 // "within"
3334 if (check((getLexer().isNot(AsmToken::Identifier) ||
3335 getTok().getIdentifier() != "within"),
3336 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3337 return true;
3338 Lex();
3339
3340 // IAFunc
3341 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3342 return true;
3343
3344 // "inlined_at"
3345 if (check((getLexer().isNot(AsmToken::Identifier) ||
3346 getTok().getIdentifier() != "inlined_at"),
3347 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3348 "directive") )
3349 return true;
3350 Lex();
3351
3352 // IAFile IALine
3353 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3354 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3355 return true;
3356
3357 // [IACol]
3358 if (getLexer().is(AsmToken::Integer)) {
3359 IACol = getTok().getIntVal();
3360 Lex();
3361 }
3362
3363 if (parseToken(AsmToken::EndOfStatement,
3364 "unexpected token in '.cv_inline_site_id' directive"))
3365 return true;
3366
3367 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3368 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003369 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003370
3371 return false;
3372}
3373
Reid Kleckner2214ed82016-01-29 00:49:42 +00003374/// parseDirectiveCVLoc
3375/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3376/// [is_stmt VALUE]
3377/// The first number is a file number, must have been previously assigned with
3378/// a .file directive, the second number is the line number and optionally the
3379/// third number is a column position (zero if not specified). The remaining
3380/// optional items are .loc sub-directives.
3381bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003382 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003383 SMLoc Loc;
3384 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003385 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3386 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003387 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003388
3389 int64_t LineNumber = 0;
3390 if (getLexer().is(AsmToken::Integer)) {
3391 LineNumber = getTok().getIntVal();
3392 if (LineNumber < 0)
3393 return TokError("line number less than zero in '.cv_loc' directive");
3394 Lex();
3395 }
3396
3397 int64_t ColumnPos = 0;
3398 if (getLexer().is(AsmToken::Integer)) {
3399 ColumnPos = getTok().getIntVal();
3400 if (ColumnPos < 0)
3401 return TokError("column position less than zero in '.cv_loc' directive");
3402 Lex();
3403 }
3404
3405 bool PrologueEnd = false;
3406 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003407
3408 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003409 StringRef Name;
3410 SMLoc Loc = getTok().getLoc();
3411 if (parseIdentifier(Name))
3412 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003413 if (Name == "prologue_end")
3414 PrologueEnd = true;
3415 else if (Name == "is_stmt") {
3416 Loc = getTok().getLoc();
3417 const MCExpr *Value;
3418 if (parseExpression(Value))
3419 return true;
3420 // The expression must be the constant 0 or 1.
3421 IsStmt = ~0ULL;
3422 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3423 IsStmt = MCE->getValue();
3424
3425 if (IsStmt > 1)
3426 return Error(Loc, "is_stmt value not 0 or 1");
3427 } else {
3428 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3429 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003430 return false;
3431 };
3432
3433 if (parseMany(parseOp, false /*hasComma*/))
3434 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003435
3436 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003437 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3438 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003439 return false;
3440}
3441
3442/// parseDirectiveCVLinetable
3443/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3444bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003445 int64_t FunctionId;
3446 StringRef FnStartName, FnEndName;
3447 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003448 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003449 parseToken(AsmToken::Comma,
3450 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003451 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3452 "expected identifier in directive") ||
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(FnEndName), Loc,
3456 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003457 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003458
3459 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3460 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3461
3462 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3463 return false;
3464}
3465
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003466/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003467/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003468bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003469 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3470 StringRef FnStartName, FnEndName;
3471 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003472 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003473 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003474 parseIntToken(
3475 SourceFileId,
3476 "expected SourceField in '.cv_inline_linetable' directive") ||
3477 check(SourceFileId <= 0, Loc,
3478 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003479 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003480 parseIntToken(
3481 SourceLineNum,
3482 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3483 check(SourceLineNum < 0, Loc,
3484 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003485 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3486 "expected identifier in directive") ||
3487 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3488 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003489 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003490
Nirav Davea645433c2016-07-18 15:24:03 +00003491 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3492 return true;
3493
3494 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3495 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003496 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3497 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003498 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003499 return false;
3500}
3501
David Majnemer408b5e62016-02-05 01:55:49 +00003502/// parseDirectiveCVDefRange
3503/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3504bool AsmParser::parseDirectiveCVDefRange() {
3505 SMLoc Loc;
3506 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3507 while (getLexer().is(AsmToken::Identifier)) {
3508 Loc = getLexer().getLoc();
3509 StringRef GapStartName;
3510 if (parseIdentifier(GapStartName))
3511 return Error(Loc, "expected identifier in directive");
3512 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3513
3514 Loc = getLexer().getLoc();
3515 StringRef GapEndName;
3516 if (parseIdentifier(GapEndName))
3517 return Error(Loc, "expected identifier in directive");
3518 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3519
3520 Ranges.push_back({GapStartSym, GapEndSym});
3521 }
3522
David Majnemer408b5e62016-02-05 01:55:49 +00003523 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003524 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3525 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003526 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003527
3528 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3529 return false;
3530}
3531
Reid Kleckner2214ed82016-01-29 00:49:42 +00003532/// parseDirectiveCVStringTable
3533/// ::= .cv_stringtable
3534bool AsmParser::parseDirectiveCVStringTable() {
3535 getStreamer().EmitCVStringTableDirective();
3536 return false;
3537}
3538
3539/// parseDirectiveCVFileChecksums
3540/// ::= .cv_filechecksums
3541bool AsmParser::parseDirectiveCVFileChecksums() {
3542 getStreamer().EmitCVFileChecksumsDirective();
3543 return false;
3544}
3545
Jim Grosbach4b905842013-09-20 23:08:21 +00003546/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003547/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003548bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003549 StringRef Name;
3550 bool EH = false;
3551 bool Debug = false;
3552
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003553 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003554 return TokError("Expected an identifier");
3555
3556 if (Name == ".eh_frame")
3557 EH = true;
3558 else if (Name == ".debug_frame")
3559 Debug = true;
3560
3561 if (getLexer().is(AsmToken::Comma)) {
3562 Lex();
3563
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003564 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003565 return TokError("Expected an identifier");
3566
3567 if (Name == ".eh_frame")
3568 EH = true;
3569 else if (Name == ".debug_frame")
3570 Debug = true;
3571 }
3572
3573 getStreamer().EmitCFISections(EH, Debug);
3574 return false;
3575}
3576
Jim Grosbach4b905842013-09-20 23:08:21 +00003577/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003578/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003579bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003580 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003581 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3582 if (check(parseIdentifier(Simple) || Simple != "simple",
3583 "unexpected token") ||
3584 parseToken(AsmToken::EndOfStatement))
3585 return addErrorSuffix(" in '.cfi_startproc' directive");
3586 }
Nirav Davea645433c2016-07-18 15:24:03 +00003587
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003588 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003589 return false;
3590}
3591
Jim Grosbach4b905842013-09-20 23:08:21 +00003592/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003593/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003594bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003595 getStreamer().EmitCFIEndProc();
3596 return false;
3597}
3598
Jim Grosbach4b905842013-09-20 23:08:21 +00003599/// \brief parse register name or number.
3600bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003601 SMLoc DirectiveLoc) {
3602 unsigned RegNo;
3603
3604 if (getLexer().isNot(AsmToken::Integer)) {
3605 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3606 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003607 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003608 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003609 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003610
3611 return false;
3612}
3613
Jim Grosbach4b905842013-09-20 23:08:21 +00003614/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003615/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003616bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003617 int64_t Register = 0, Offset = 0;
3618 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3619 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3620 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003621 return true;
3622
3623 getStreamer().EmitCFIDefCfa(Register, Offset);
3624 return false;
3625}
3626
Jim Grosbach4b905842013-09-20 23:08:21 +00003627/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003628/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003629bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003630 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003631 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003632 return true;
3633
3634 getStreamer().EmitCFIDefCfaOffset(Offset);
3635 return false;
3636}
3637
Jim Grosbach4b905842013-09-20 23:08:21 +00003638/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003639/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003640bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003641 int64_t Register1 = 0, Register2 = 0;
3642 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3643 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3644 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003645 return true;
3646
3647 getStreamer().EmitCFIRegister(Register1, Register2);
3648 return false;
3649}
3650
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003651/// parseDirectiveCFIWindowSave
3652/// ::= .cfi_window_save
3653bool AsmParser::parseDirectiveCFIWindowSave() {
3654 getStreamer().EmitCFIWindowSave();
3655 return false;
3656}
3657
Jim Grosbach4b905842013-09-20 23:08:21 +00003658/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003659/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003660bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003661 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003662 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003663 return true;
3664
3665 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3666 return false;
3667}
3668
Jim Grosbach4b905842013-09-20 23:08:21 +00003669/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003670/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003671bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003672 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003673 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003674 return true;
3675
3676 getStreamer().EmitCFIDefCfaRegister(Register);
3677 return false;
3678}
3679
Jim Grosbach4b905842013-09-20 23:08:21 +00003680/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003681/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003682bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003683 int64_t Register = 0;
3684 int64_t Offset = 0;
3685
Nirav Davea645433c2016-07-18 15:24:03 +00003686 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3687 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3688 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003689 return true;
3690
3691 getStreamer().EmitCFIOffset(Register, Offset);
3692 return false;
3693}
3694
Jim Grosbach4b905842013-09-20 23:08:21 +00003695/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003696/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003697bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003698 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003699
Nirav Davea645433c2016-07-18 15:24:03 +00003700 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3701 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3702 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003703 return true;
3704
3705 getStreamer().EmitCFIRelOffset(Register, Offset);
3706 return false;
3707}
3708
3709static bool isValidEncoding(int64_t Encoding) {
3710 if (Encoding & ~0xff)
3711 return false;
3712
3713 if (Encoding == dwarf::DW_EH_PE_omit)
3714 return true;
3715
3716 const unsigned Format = Encoding & 0xf;
3717 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3718 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3719 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3720 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3721 return false;
3722
3723 const unsigned Application = Encoding & 0x70;
3724 if (Application != dwarf::DW_EH_PE_absptr &&
3725 Application != dwarf::DW_EH_PE_pcrel)
3726 return false;
3727
3728 return true;
3729}
3730
Jim Grosbach4b905842013-09-20 23:08:21 +00003731/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003732/// IsPersonality true for cfi_personality, false for cfi_lsda
3733/// ::= .cfi_personality encoding, [symbol_name]
3734/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003735bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003736 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003737 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003738 return true;
3739 if (Encoding == dwarf::DW_EH_PE_omit)
3740 return false;
3741
Eli Bendersky17233942013-01-15 22:59:42 +00003742 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003743 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3744 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3745 check(parseIdentifier(Name), "expected identifier in directive"))
3746 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003747
Jim Grosbach6f482002015-05-18 18:43:14 +00003748 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003749
3750 if (IsPersonality)
3751 getStreamer().EmitCFIPersonality(Sym, Encoding);
3752 else
3753 getStreamer().EmitCFILsda(Sym, Encoding);
3754 return false;
3755}
3756
Jim Grosbach4b905842013-09-20 23:08:21 +00003757/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003758/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003759bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003760 getStreamer().EmitCFIRememberState();
3761 return false;
3762}
3763
Jim Grosbach4b905842013-09-20 23:08:21 +00003764/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003765/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003766bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003767 getStreamer().EmitCFIRestoreState();
3768 return false;
3769}
3770
Jim Grosbach4b905842013-09-20 23:08:21 +00003771/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003772/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003773bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003774 int64_t Register = 0;
3775
Jim Grosbach4b905842013-09-20 23:08:21 +00003776 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003777 return true;
3778
3779 getStreamer().EmitCFISameValue(Register);
3780 return false;
3781}
3782
Jim Grosbach4b905842013-09-20 23:08:21 +00003783/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003784/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003785bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003786 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003787 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003788 return true;
3789
3790 getStreamer().EmitCFIRestore(Register);
3791 return false;
3792}
3793
Jim Grosbach4b905842013-09-20 23:08:21 +00003794/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003795/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003796bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003797 std::string Values;
3798 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003799 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003800 return true;
3801
3802 Values.push_back((uint8_t)CurrValue);
3803
3804 while (getLexer().is(AsmToken::Comma)) {
3805 Lex();
3806
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003807 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003808 return true;
3809
3810 Values.push_back((uint8_t)CurrValue);
3811 }
3812
3813 getStreamer().EmitCFIEscape(Values);
3814 return false;
3815}
3816
Jim Grosbach4b905842013-09-20 23:08:21 +00003817/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003818/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003819bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003820 if (parseToken(AsmToken::EndOfStatement,
3821 "unexpected token in '.cfi_signal_frame'"))
3822 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003823
3824 getStreamer().EmitCFISignalFrame();
3825 return false;
3826}
3827
Jim Grosbach4b905842013-09-20 23:08:21 +00003828/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003829/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003830bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003831 int64_t Register = 0;
3832
Jim Grosbach4b905842013-09-20 23:08:21 +00003833 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003834 return true;
3835
3836 getStreamer().EmitCFIUndefined(Register);
3837 return false;
3838}
3839
Jim Grosbach4b905842013-09-20 23:08:21 +00003840/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003841/// ::= .macros_on
3842/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003843bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003844 if (parseToken(AsmToken::EndOfStatement,
3845 "unexpected token in '" + Directive + "' directive"))
3846 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003847
Jim Grosbach4b905842013-09-20 23:08:21 +00003848 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003849 return false;
3850}
3851
Jim Grosbach4b905842013-09-20 23:08:21 +00003852/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003853/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003854bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003855 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003856 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003857 return TokError("expected identifier in '.macro' directive");
3858
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003859 if (getLexer().is(AsmToken::Comma))
3860 Lex();
3861
Eli Bendersky17233942013-01-15 22:59:42 +00003862 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003863 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003864
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003865 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003866 return Error(Lexer.getLoc(),
3867 "Vararg parameter '" + Parameters.back().Name +
3868 "' should be last one in the list of parameters.");
3869
David Majnemer91fc4c22014-01-29 18:57:46 +00003870 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003871 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003872 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003873
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003874 if (Lexer.is(AsmToken::Colon)) {
3875 Lex(); // consume ':'
3876
3877 SMLoc QualLoc;
3878 StringRef Qualifier;
3879
3880 QualLoc = Lexer.getLoc();
3881 if (parseIdentifier(Qualifier))
3882 return Error(QualLoc, "missing parameter qualifier for "
3883 "'" + Parameter.Name + "' in macro '" + Name + "'");
3884
3885 if (Qualifier == "req")
3886 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003887 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003888 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003889 else
3890 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3891 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3892 }
3893
David Majnemer91fc4c22014-01-29 18:57:46 +00003894 if (getLexer().is(AsmToken::Equal)) {
3895 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003896
3897 SMLoc ParamLoc;
3898
3899 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003900 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003901 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003902
3903 if (Parameter.Required)
3904 Warning(ParamLoc, "pointless default value for required parameter "
3905 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003906 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003907
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003908 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003909
3910 if (getLexer().is(AsmToken::Comma))
3911 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003912 }
3913
Nirav Dave1180e6892016-06-02 17:15:05 +00003914 // Eat just the end of statement.
3915 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003916
Nirav Dave1180e6892016-06-02 17:15:05 +00003917 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003918 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003919 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003920 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003921 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003922 // Ignore Lexing errors in macros.
3923 while (Lexer.is(AsmToken::Error)) {
3924 Lexer.Lex();
3925 }
3926
Eli Bendersky17233942013-01-15 22:59:42 +00003927 // Check whether we have reached the end of the file.
3928 if (getLexer().is(AsmToken::Eof))
3929 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3930
3931 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003932 if (getLexer().is(AsmToken::Identifier)) {
3933 if (getTok().getIdentifier() == ".endm" ||
3934 getTok().getIdentifier() == ".endmacro") {
3935 if (MacroDepth == 0) { // Outermost macro.
3936 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003937 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003938 if (getLexer().isNot(AsmToken::EndOfStatement))
3939 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3940 "' directive");
3941 break;
3942 } else {
3943 // Otherwise we just found the end of an inner macro.
3944 --MacroDepth;
3945 }
3946 } else if (getTok().getIdentifier() == ".macro") {
3947 // We allow nested macros. Those aren't instantiated until the outermost
3948 // macro is expanded so just ignore them for now.
3949 ++MacroDepth;
3950 }
Eli Bendersky17233942013-01-15 22:59:42 +00003951 }
3952
3953 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003954 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003955 }
3956
Jim Grosbach4b905842013-09-20 23:08:21 +00003957 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003958 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3959 }
3960
3961 const char *BodyStart = StartToken.getLoc().getPointer();
3962 const char *BodyEnd = EndToken.getLoc().getPointer();
3963 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003964 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003965 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003966 return false;
3967}
3968
Jim Grosbach4b905842013-09-20 23:08:21 +00003969/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003970///
3971/// With the support added for named parameters there may be code out there that
3972/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003973/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003974/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003975/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003976/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3977/// warning that the positional parameter found in body which have no effect.
3978/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003979/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003980/// intended or change the macro to use the named parameters. It is possible
3981/// this warning will trigger when the none of the named parameters are used
3982/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003983void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003984 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003985 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003986 // If this macro is not defined with named parameters the warning we are
3987 // checking for here doesn't apply.
3988 unsigned NParameters = Parameters.size();
3989 if (NParameters == 0)
3990 return;
3991
3992 bool NamedParametersFound = false;
3993 bool PositionalParametersFound = false;
3994
3995 // Look at the body of the macro for use of both the named parameters and what
3996 // are likely to be positional parameters. This is what expandMacro() is
3997 // doing when it finds the parameters in the body.
3998 while (!Body.empty()) {
3999 // Scan for the next possible parameter.
4000 std::size_t End = Body.size(), Pos = 0;
4001 for (; Pos != End; ++Pos) {
4002 // Check for a substitution or escape.
4003 // This macro is defined with parameters, look for \foo, \bar, etc.
4004 if (Body[Pos] == '\\' && Pos + 1 != End)
4005 break;
4006
4007 // This macro should have parameters, but look for $0, $1, ..., $n too.
4008 if (Body[Pos] != '$' || Pos + 1 == End)
4009 continue;
4010 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004011 if (Next == '$' || Next == 'n' ||
4012 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004013 break;
4014 }
4015
4016 // Check if we reached the end.
4017 if (Pos == End)
4018 break;
4019
4020 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004021 switch (Body[Pos + 1]) {
4022 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004023 case '$':
4024 break;
4025
Jim Grosbach4b905842013-09-20 23:08:21 +00004026 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004027 case 'n':
4028 PositionalParametersFound = true;
4029 break;
4030
Jim Grosbach4b905842013-09-20 23:08:21 +00004031 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004032 default: {
4033 PositionalParametersFound = true;
4034 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004035 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004036 }
4037 Pos += 2;
4038 } else {
4039 unsigned I = Pos + 1;
4040 while (isIdentifierChar(Body[I]) && I + 1 != End)
4041 ++I;
4042
Jim Grosbach4b905842013-09-20 23:08:21 +00004043 const char *Begin = Body.data() + Pos + 1;
4044 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004045 unsigned Index = 0;
4046 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004047 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004048 break;
4049
4050 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004051 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4052 Pos += 3;
4053 else {
4054 Pos = I;
4055 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004056 } else {
4057 NamedParametersFound = true;
4058 Pos += 1 + Argument.size();
4059 }
4060 }
4061 // Update the scan point.
4062 Body = Body.substr(Pos);
4063 }
4064
4065 if (!NamedParametersFound && PositionalParametersFound)
4066 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4067 "used in macro body, possible positional parameter "
4068 "found in body which will have no effect");
4069}
4070
Nico Weber155dccd12014-07-24 17:08:39 +00004071/// parseDirectiveExitMacro
4072/// ::= .exitm
4073bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004074 if (parseToken(AsmToken::EndOfStatement,
4075 "unexpected token in '" + Directive + "' directive"))
4076 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004077
4078 if (!isInsideMacroInstantiation())
4079 return TokError("unexpected '" + Directive + "' in file, "
4080 "no current macro definition");
4081
4082 // Exit all conditionals that are active in the current macro.
4083 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4084 TheCondState = TheCondStack.back();
4085 TheCondStack.pop_back();
4086 }
4087
4088 handleMacroExit();
4089 return false;
4090}
4091
Jim Grosbach4b905842013-09-20 23:08:21 +00004092/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004093/// ::= .endm
4094/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004095bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004096 if (getLexer().isNot(AsmToken::EndOfStatement))
4097 return TokError("unexpected token in '" + Directive + "' directive");
4098
4099 // If we are inside a macro instantiation, terminate the current
4100 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004101 if (isInsideMacroInstantiation()) {
4102 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004103 return false;
4104 }
4105
4106 // Otherwise, this .endmacro is a stray entry in the file; well formed
4107 // .endmacro directives are handled during the macro definition parsing.
4108 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004109 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004110}
4111
Jim Grosbach4b905842013-09-20 23:08:21 +00004112/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004113/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004114bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004115 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004116 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004117 if (parseTokenLoc(Loc) ||
4118 check(parseIdentifier(Name), Loc,
4119 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004120 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004121 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004122 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004123
Nirav Dave1ab71992016-07-18 19:35:21 +00004124 if (!lookupMacro(Name))
4125 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4126
Jim Grosbach4b905842013-09-20 23:08:21 +00004127 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004128 return false;
4129}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004130
Jim Grosbach4b905842013-09-20 23:08:21 +00004131/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004132/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004133bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004134 // Expect a single argument: an expression that evaluates to a constant
4135 // in the inclusive range 0-30.
4136 SMLoc ExprLoc = getLexer().getLoc();
4137 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004138 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004139 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4140 "in '.bundle_align_mode' "
4141 "directive") ||
4142 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4143 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004144 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004145
4146 // Because of AlignSizePow2's verified range we can safely truncate it to
4147 // unsigned.
4148 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4149 return false;
4150}
4151
Jim Grosbach4b905842013-09-20 23:08:21 +00004152/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004153/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004154bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004155 if (checkForValidSection())
4156 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004157 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004158
Nirav Dave1a9044b2016-10-24 14:35:29 +00004159 StringRef Option;
4160 SMLoc Loc = getTok().getLoc();
4161 const char *kInvalidOptionError =
4162 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004163
Nirav Dave1a9044b2016-10-24 14:35:29 +00004164 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004165 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4166 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004167 parseToken(AsmToken::EndOfStatement,
4168 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004169 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004170 AlignToEnd = true;
4171 }
4172
Eli Bendersky802b6282013-01-07 21:51:08 +00004173 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004174 return false;
4175}
4176
Jim Grosbach4b905842013-09-20 23:08:21 +00004177/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004178/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004179bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004180 if (checkForValidSection() ||
4181 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004182 "unexpected token in '.bundle_unlock' directive"))
4183 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004184
4185 getStreamer().EmitBundleUnlock();
4186 return false;
4187}
4188
Jim Grosbach4b905842013-09-20 23:08:21 +00004189/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004190/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004191bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004192 SMLoc NumBytesLoc = Lexer.getLoc();
4193 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004194 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004195 return true;
4196
4197 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004198 if (parseOptionalToken(AsmToken::Comma))
4199 if (parseAbsoluteExpression(FillExpr))
4200 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4201 if (parseToken(AsmToken::EndOfStatement))
4202 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004203
Eli Bendersky17233942013-01-15 22:59:42 +00004204 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004205 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004206
4207 return false;
4208}
4209
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004210/// parseDirectiveDCB
4211/// ::= .dcb.{b, l, w} expression, expression
4212bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004213 SMLoc NumValuesLoc = Lexer.getLoc();
4214 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004215 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004216 return true;
4217
4218 if (NumValues < 0) {
4219 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4220 return false;
4221 }
4222
4223 if (parseToken(AsmToken::Comma,
4224 "unexpected token in '" + Twine(IDVal) + "' directive"))
4225 return true;
4226
4227 const MCExpr *Value;
4228 SMLoc ExprLoc = getLexer().getLoc();
4229 if (parseExpression(Value))
4230 return true;
4231
4232 // Special case constant expressions to match code generator.
4233 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4234 assert(Size <= 8 && "Invalid size");
4235 uint64_t IntValue = MCE->getValue();
4236 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4237 return Error(ExprLoc, "literal value out of range for directive");
4238 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4239 getStreamer().EmitIntValue(IntValue, Size);
4240 } else {
4241 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4242 getStreamer().EmitValue(Value, Size, ExprLoc);
4243 }
4244
4245 if (parseToken(AsmToken::EndOfStatement,
4246 "unexpected token in '" + Twine(IDVal) + "' directive"))
4247 return true;
4248
4249 return false;
4250}
4251
4252/// parseDirectiveRealDCB
4253/// ::= .dcb.{d, s} expression, expression
4254bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004255 SMLoc NumValuesLoc = Lexer.getLoc();
4256 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004257 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004258 return true;
4259
4260 if (NumValues < 0) {
4261 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4262 return false;
4263 }
4264
4265 if (parseToken(AsmToken::Comma,
4266 "unexpected token in '" + Twine(IDVal) + "' directive"))
4267 return true;
4268
4269 APInt AsInt;
4270 if (parseRealValue(Semantics, AsInt))
4271 return true;
4272
4273 if (parseToken(AsmToken::EndOfStatement,
4274 "unexpected token in '" + Twine(IDVal) + "' directive"))
4275 return true;
4276
4277 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4278 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4279 AsInt.getBitWidth() / 8);
4280
4281 return false;
4282}
4283
Petr Hosek85b2f672016-09-23 21:53:36 +00004284/// parseDirectiveDS
4285/// ::= .ds.{b, d, l, p, s, w, x} expression
4286bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004287 SMLoc NumValuesLoc = Lexer.getLoc();
4288 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004289 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004290 return true;
4291
4292 if (NumValues < 0) {
4293 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4294 return false;
4295 }
4296
4297 if (parseToken(AsmToken::EndOfStatement,
4298 "unexpected token in '" + Twine(IDVal) + "' directive"))
4299 return true;
4300
4301 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4302 getStreamer().emitFill(Size, 0);
4303
4304 return false;
4305}
4306
Jim Grosbach4b905842013-09-20 23:08:21 +00004307/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004308/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004309bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004310 if (checkForValidSection())
4311 return true;
4312
Nirav Dave1a9044b2016-10-24 14:35:29 +00004313 auto parseOp = [&]() -> bool {
4314 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004315 if (parseExpression(Value))
4316 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004317 if (Signed)
4318 getStreamer().EmitSLEB128Value(Value);
4319 else
4320 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004321 return false;
4322 };
Eli Bendersky17233942013-01-15 22:59:42 +00004323
Nirav Dave1a9044b2016-10-24 14:35:29 +00004324 if (parseMany(parseOp))
4325 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004326
4327 return false;
4328}
4329
Jim Grosbach4b905842013-09-20 23:08:21 +00004330/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004331/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004332bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004333 auto parseOp = [&]() -> bool {
4334 StringRef Name;
4335 SMLoc Loc = getTok().getLoc();
4336 if (parseIdentifier(Name))
4337 return Error(Loc, "expected identifier");
4338 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004339
Nirav Dave1a9044b2016-10-24 14:35:29 +00004340 // Assembler local symbols don't make any sense here. Complain loudly.
4341 if (Sym->isTemporary())
4342 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004343
Nirav Dave1a9044b2016-10-24 14:35:29 +00004344 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4345 return Error(Loc, "unable to emit symbol attribute");
4346 return false;
4347 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004348
Nirav Dave1a9044b2016-10-24 14:35:29 +00004349 if (parseMany(parseOp))
4350 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004351 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004352}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004353
Jim Grosbach4b905842013-09-20 23:08:21 +00004354/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004355/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004356bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004357 if (checkForValidSection())
4358 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004359
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004360 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004361 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004362 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004363 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004364
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004365 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004366 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004367
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004368 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004369 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004370 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004371
4372 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004373 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004374 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004375 return true;
4376
4377 int64_t Pow2Alignment = 0;
4378 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004379 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004380 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004381 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004382 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004383 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004384
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004385 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4386 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004387 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4388
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004389 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004390 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4391 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004392 if (!isPowerOf2_64(Pow2Alignment))
4393 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4394 Pow2Alignment = Log2_64(Pow2Alignment);
4395 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004396 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004397
Nirav Dave1a9044b2016-10-24 14:35:29 +00004398 if (parseToken(AsmToken::EndOfStatement,
4399 "unexpected token in '.comm' or '.lcomm' directive"))
4400 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004401
Chris Lattner28ad7542009-07-09 17:25:12 +00004402 // NOTE: a size of zero for a .comm should create a undefined symbol
4403 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004404 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004405 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004406 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004407
Eric Christopherbc818852010-05-14 01:38:54 +00004408 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004409 // may internally end up wanting an alignment in bytes.
4410 // FIXME: Diagnose overflow.
4411 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004412 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004413 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004414
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004415 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004416 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004417 return Error(IDLoc, "invalid symbol redefinition");
4418
Chris Lattner28ad7542009-07-09 17:25:12 +00004419 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004420 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004421 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004422 return false;
4423 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004424
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004425 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004426 return false;
4427}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004428
Jim Grosbach4b905842013-09-20 23:08:21 +00004429/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004430/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004431bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004432 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004433 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004434
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004435 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004436 if (parseToken(AsmToken::EndOfStatement,
4437 "unexpected token in '.abort' directive"))
4438 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004439
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004440 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004441 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004442 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004443 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004444 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004445
4446 return false;
4447}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004448
Jim Grosbach4b905842013-09-20 23:08:21 +00004449/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004450/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004451bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004452 // Allow the strings to have escaped octal character sequence.
4453 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004454 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004455
Nirav Davea645433c2016-07-18 15:24:03 +00004456 if (check(getTok().isNot(AsmToken::String),
4457 "expected string in '.include' directive") ||
4458 parseEscapedString(Filename) ||
4459 check(getTok().isNot(AsmToken::EndOfStatement),
4460 "unexpected token in '.include' directive") ||
4461 // Attempt to switch the lexer to the included file before consuming the
4462 // end of statement to avoid losing it when we switch.
4463 check(enterIncludeFile(Filename), IncludeLoc,
4464 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004465 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004466
4467 return false;
4468}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004469
Jim Grosbach4b905842013-09-20 23:08:21 +00004470/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004471/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004472bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004473 // Allow the strings to have escaped octal character sequence.
4474 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004475 SMLoc IncbinLoc = getTok().getLoc();
4476 if (check(getTok().isNot(AsmToken::String),
4477 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004478 parseEscapedString(Filename))
4479 return true;
4480
4481 int64_t Skip = 0;
4482 const MCExpr *Count = nullptr;
4483 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004484 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004485 // The skip expression can be omitted while specifying the count, e.g:
4486 // .incbin "filename",,4
4487 if (getTok().isNot(AsmToken::Comma)) {
4488 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4489 return true;
4490 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004491 if (parseOptionalToken(AsmToken::Comma)) {
4492 CountLoc = getTok().getLoc();
4493 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004494 return true;
4495 }
4496 }
4497
4498 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004499 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004500 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004501
Petr Hosek2f4ac442016-09-23 00:41:06 +00004502 if (check(Skip < 0, SkipLoc, "skip is negative"))
4503 return true;
4504
Nirav Dave1ab71992016-07-18 19:35:21 +00004505 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004506 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004507 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004508 return false;
4509}
4510
Jim Grosbach4b905842013-09-20 23:08:21 +00004511/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004512/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4513bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004514 TheCondStack.push_back(TheCondState);
4515 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004516 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004517 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004518 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004519 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004520 if (parseAbsoluteExpression(ExprValue) ||
4521 parseToken(AsmToken::EndOfStatement,
4522 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004523 return true;
4524
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004525 switch (DirKind) {
4526 default:
4527 llvm_unreachable("unsupported directive");
4528 case DK_IF:
4529 case DK_IFNE:
4530 break;
4531 case DK_IFEQ:
4532 ExprValue = ExprValue == 0;
4533 break;
4534 case DK_IFGE:
4535 ExprValue = ExprValue >= 0;
4536 break;
4537 case DK_IFGT:
4538 ExprValue = ExprValue > 0;
4539 break;
4540 case DK_IFLE:
4541 ExprValue = ExprValue <= 0;
4542 break;
4543 case DK_IFLT:
4544 ExprValue = ExprValue < 0;
4545 break;
4546 }
4547
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004548 TheCondState.CondMet = ExprValue;
4549 TheCondState.Ignore = !TheCondState.CondMet;
4550 }
4551
4552 return false;
4553}
4554
Jim Grosbach4b905842013-09-20 23:08:21 +00004555/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004556/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004557bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004558 TheCondStack.push_back(TheCondState);
4559 TheCondState.TheCond = AsmCond::IfCond;
4560
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004561 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004562 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004563 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004564 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004565
Nirav Davea645433c2016-07-18 15:24:03 +00004566 if (parseToken(AsmToken::EndOfStatement,
4567 "unexpected token in '.ifb' directive"))
4568 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004569
4570 TheCondState.CondMet = ExpectBlank == Str.empty();
4571 TheCondState.Ignore = !TheCondState.CondMet;
4572 }
4573
4574 return false;
4575}
4576
Jim Grosbach4b905842013-09-20 23:08:21 +00004577/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004578/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004579/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004580bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004581 TheCondStack.push_back(TheCondState);
4582 TheCondState.TheCond = AsmCond::IfCond;
4583
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004584 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004585 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004586 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004587 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004588
Nirav Davea645433c2016-07-18 15:24:03 +00004589 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4590 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004591
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004592 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004593
Nirav Davea645433c2016-07-18 15:24:03 +00004594 if (parseToken(AsmToken::EndOfStatement,
4595 "unexpected token in '.ifc' directive"))
4596 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004597
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004598 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004599 TheCondState.Ignore = !TheCondState.CondMet;
4600 }
4601
4602 return false;
4603}
4604
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004605/// parseDirectiveIfeqs
4606/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004607bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004608 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004609 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004610 return TokError("expected string parameter for '.ifeqs' directive");
4611 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004612 }
4613
4614 StringRef String1 = getTok().getStringContents();
4615 Lex();
4616
4617 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004618 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004619 return TokError(
4620 "expected comma after first string for '.ifeqs' directive");
4621 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004622 }
4623
4624 Lex();
4625
4626 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004627 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004628 return TokError("expected string parameter for '.ifeqs' directive");
4629 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004630 }
4631
4632 StringRef String2 = getTok().getStringContents();
4633 Lex();
4634
4635 TheCondStack.push_back(TheCondState);
4636 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004637 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004638 TheCondState.Ignore = !TheCondState.CondMet;
4639
4640 return false;
4641}
4642
Jim Grosbach4b905842013-09-20 23:08:21 +00004643/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004644/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004645bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004646 StringRef Name;
4647 TheCondStack.push_back(TheCondState);
4648 TheCondState.TheCond = AsmCond::IfCond;
4649
4650 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004651 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004652 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004653 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4654 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4655 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004656
Jim Grosbach6f482002015-05-18 18:43:14 +00004657 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004658
4659 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004660 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004661 else
Craig Topper353eda42014-04-24 06:44:33 +00004662 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004663 TheCondState.Ignore = !TheCondState.CondMet;
4664 }
4665
4666 return false;
4667}
4668
Jim Grosbach4b905842013-09-20 23:08:21 +00004669/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004670/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004671bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004672 if (TheCondState.TheCond != AsmCond::IfCond &&
4673 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004674 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4675 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004676 TheCondState.TheCond = AsmCond::ElseIfCond;
4677
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004678 bool LastIgnoreState = false;
4679 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004680 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004681 if (LastIgnoreState || TheCondState.CondMet) {
4682 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004683 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004684 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004685 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004686 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004687 return true;
4688
Nirav Dave1a9044b2016-10-24 14:35:29 +00004689 if (parseToken(AsmToken::EndOfStatement,
4690 "unexpected token in '.elseif' directive"))
4691 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004692
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004693 TheCondState.CondMet = ExprValue;
4694 TheCondState.Ignore = !TheCondState.CondMet;
4695 }
4696
4697 return false;
4698}
4699
Jim Grosbach4b905842013-09-20 23:08:21 +00004700/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004701/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004702bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004703 if (parseToken(AsmToken::EndOfStatement,
4704 "unexpected token in '.else' directive"))
4705 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004706
4707 if (TheCondState.TheCond != AsmCond::IfCond &&
4708 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004709 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4710 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004711 TheCondState.TheCond = AsmCond::ElseCond;
4712 bool LastIgnoreState = false;
4713 if (!TheCondStack.empty())
4714 LastIgnoreState = TheCondStack.back().Ignore;
4715 if (LastIgnoreState || TheCondState.CondMet)
4716 TheCondState.Ignore = true;
4717 else
4718 TheCondState.Ignore = false;
4719
4720 return false;
4721}
4722
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004723/// parseDirectiveEnd
4724/// ::= .end
4725bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004726 if (parseToken(AsmToken::EndOfStatement,
4727 "unexpected token in '.end' directive"))
4728 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004729
4730 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004731 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004732
4733 return false;
4734}
4735
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004736/// parseDirectiveError
4737/// ::= .err
4738/// ::= .error [string]
4739bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4740 if (!TheCondStack.empty()) {
4741 if (TheCondStack.back().Ignore) {
4742 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004743 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004744 }
4745 }
4746
4747 if (!WithMessage)
4748 return Error(L, ".err encountered");
4749
4750 StringRef Message = ".error directive invoked in source file";
4751 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004752 if (Lexer.isNot(AsmToken::String))
4753 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004754
4755 Message = getTok().getStringContents();
4756 Lex();
4757 }
4758
Nirav Dave2364748a2016-09-16 18:30:20 +00004759 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004760}
4761
Nico Weber404012b2014-07-24 16:26:06 +00004762/// parseDirectiveWarning
4763/// ::= .warning [string]
4764bool AsmParser::parseDirectiveWarning(SMLoc L) {
4765 if (!TheCondStack.empty()) {
4766 if (TheCondStack.back().Ignore) {
4767 eatToEndOfStatement();
4768 return false;
4769 }
4770 }
4771
4772 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00004773
4774 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004775 if (Lexer.isNot(AsmToken::String))
4776 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004777
4778 Message = getTok().getStringContents();
4779 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00004780 if (parseToken(AsmToken::EndOfStatement,
4781 "expected end of statement in '.warning' directive"))
4782 return true;
Nico Weber404012b2014-07-24 16:26:06 +00004783 }
4784
Nirav Dave2364748a2016-09-16 18:30:20 +00004785 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004786}
4787
Jim Grosbach4b905842013-09-20 23:08:21 +00004788/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004789/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004790bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004791 if (parseToken(AsmToken::EndOfStatement,
4792 "unexpected token in '.endif' directive"))
4793 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004794
Jim Grosbach4b905842013-09-20 23:08:21 +00004795 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004796 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4797 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004798 if (!TheCondStack.empty()) {
4799 TheCondState = TheCondStack.back();
4800 TheCondStack.pop_back();
4801 }
4802
4803 return false;
4804}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004805
Eli Bendersky17233942013-01-15 22:59:42 +00004806void AsmParser::initializeDirectiveKindMap() {
4807 DirectiveKindMap[".set"] = DK_SET;
4808 DirectiveKindMap[".equ"] = DK_EQU;
4809 DirectiveKindMap[".equiv"] = DK_EQUIV;
4810 DirectiveKindMap[".ascii"] = DK_ASCII;
4811 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4812 DirectiveKindMap[".string"] = DK_STRING;
4813 DirectiveKindMap[".byte"] = DK_BYTE;
4814 DirectiveKindMap[".short"] = DK_SHORT;
4815 DirectiveKindMap[".value"] = DK_VALUE;
4816 DirectiveKindMap[".2byte"] = DK_2BYTE;
4817 DirectiveKindMap[".long"] = DK_LONG;
4818 DirectiveKindMap[".int"] = DK_INT;
4819 DirectiveKindMap[".4byte"] = DK_4BYTE;
4820 DirectiveKindMap[".quad"] = DK_QUAD;
4821 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004822 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004823 DirectiveKindMap[".single"] = DK_SINGLE;
4824 DirectiveKindMap[".float"] = DK_FLOAT;
4825 DirectiveKindMap[".double"] = DK_DOUBLE;
4826 DirectiveKindMap[".align"] = DK_ALIGN;
4827 DirectiveKindMap[".align32"] = DK_ALIGN32;
4828 DirectiveKindMap[".balign"] = DK_BALIGN;
4829 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4830 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4831 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4832 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4833 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4834 DirectiveKindMap[".org"] = DK_ORG;
4835 DirectiveKindMap[".fill"] = DK_FILL;
4836 DirectiveKindMap[".zero"] = DK_ZERO;
4837 DirectiveKindMap[".extern"] = DK_EXTERN;
4838 DirectiveKindMap[".globl"] = DK_GLOBL;
4839 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004840 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4841 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4842 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4843 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4844 DirectiveKindMap[".reference"] = DK_REFERENCE;
4845 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4846 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4847 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4848 DirectiveKindMap[".comm"] = DK_COMM;
4849 DirectiveKindMap[".common"] = DK_COMMON;
4850 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4851 DirectiveKindMap[".abort"] = DK_ABORT;
4852 DirectiveKindMap[".include"] = DK_INCLUDE;
4853 DirectiveKindMap[".incbin"] = DK_INCBIN;
4854 DirectiveKindMap[".code16"] = DK_CODE16;
4855 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4856 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004857 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004858 DirectiveKindMap[".irp"] = DK_IRP;
4859 DirectiveKindMap[".irpc"] = DK_IRPC;
4860 DirectiveKindMap[".endr"] = DK_ENDR;
4861 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4862 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4863 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4864 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004865 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4866 DirectiveKindMap[".ifge"] = DK_IFGE;
4867 DirectiveKindMap[".ifgt"] = DK_IFGT;
4868 DirectiveKindMap[".ifle"] = DK_IFLE;
4869 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004870 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004871 DirectiveKindMap[".ifb"] = DK_IFB;
4872 DirectiveKindMap[".ifnb"] = DK_IFNB;
4873 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004874 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004875 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004876 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004877 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4878 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4879 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4880 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4881 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004882 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004883 DirectiveKindMap[".endif"] = DK_ENDIF;
4884 DirectiveKindMap[".skip"] = DK_SKIP;
4885 DirectiveKindMap[".space"] = DK_SPACE;
4886 DirectiveKindMap[".file"] = DK_FILE;
4887 DirectiveKindMap[".line"] = DK_LINE;
4888 DirectiveKindMap[".loc"] = DK_LOC;
4889 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004890 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004891 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004892 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4893 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004894 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004895 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00004896 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004897 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4898 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004899 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4900 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4901 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4902 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4903 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4904 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4905 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4906 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4907 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4908 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4909 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4910 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4911 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4912 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4913 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4914 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4915 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4916 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4917 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4918 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4919 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004920 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004921 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4922 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4923 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004924 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004925 DirectiveKindMap[".endm"] = DK_ENDM;
4926 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4927 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004928 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004929 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004930 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004931 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00004932 DirectiveKindMap[".dc"] = DK_DC;
4933 DirectiveKindMap[".dc.a"] = DK_DC_A;
4934 DirectiveKindMap[".dc.b"] = DK_DC_B;
4935 DirectiveKindMap[".dc.d"] = DK_DC_D;
4936 DirectiveKindMap[".dc.l"] = DK_DC_L;
4937 DirectiveKindMap[".dc.s"] = DK_DC_S;
4938 DirectiveKindMap[".dc.w"] = DK_DC_W;
4939 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004940 DirectiveKindMap[".dcb"] = DK_DCB;
4941 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4942 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4943 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4944 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4945 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4946 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00004947 DirectiveKindMap[".ds"] = DK_DS;
4948 DirectiveKindMap[".ds.b"] = DK_DS_B;
4949 DirectiveKindMap[".ds.d"] = DK_DS_D;
4950 DirectiveKindMap[".ds.l"] = DK_DS_L;
4951 DirectiveKindMap[".ds.p"] = DK_DS_P;
4952 DirectiveKindMap[".ds.s"] = DK_DS_S;
4953 DirectiveKindMap[".ds.w"] = DK_DS_W;
4954 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004955}
4956
Jim Grosbach4b905842013-09-20 23:08:21 +00004957MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004958 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004959
Rafael Espindola34b9c512012-06-03 23:57:14 +00004960 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004961 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004962 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004963 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004964 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004965 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004966 }
4967
Rafael Espindola34b9c512012-06-03 23:57:14 +00004968 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004969 (getTok().getIdentifier() == ".rept" ||
4970 getTok().getIdentifier() == ".irp" ||
4971 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004972 ++NestLevel;
4973 }
4974
4975 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004976 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004977 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004978 EndToken = getTok();
4979 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004980 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004981 printError(getTok().getLoc(),
4982 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004983 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004984 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004985 break;
4986 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004987 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004988 }
4989
Rafael Espindola34b9c512012-06-03 23:57:14 +00004990 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004991 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004992 }
4993
4994 const char *BodyStart = StartToken.getLoc().getPointer();
4995 const char *BodyEnd = EndToken.getLoc().getPointer();
4996 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4997
Rafael Espindola34b9c512012-06-03 23:57:14 +00004998 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004999 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005000 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005001}
5002
Jim Grosbach4b905842013-09-20 23:08:21 +00005003void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005004 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005005 OS << ".endr\n";
5006
Rafael Espindola3560ff22014-08-27 20:03:13 +00005007 std::unique_ptr<MemoryBuffer> Instantiation =
5008 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005009
Rafael Espindola34b9c512012-06-03 23:57:14 +00005010 // Create the macro instantiation object and add to the current macro
5011 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005012 MacroInstantiation *MI = new MacroInstantiation(
5013 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005014 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005015
Rafael Espindola34b9c512012-06-03 23:57:14 +00005016 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005017 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005018 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005019 Lex();
5020}
5021
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005022/// parseDirectiveRept
5023/// ::= .rep | .rept count
5024bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005025 const MCExpr *CountExpr;
5026 SMLoc CountLoc = getTok().getLoc();
5027 if (parseExpression(CountExpr))
5028 return true;
5029
Rafael Espindola34b9c512012-06-03 23:57:14 +00005030 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005031 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005032 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5033 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005034
Nirav Davea645433c2016-07-18 15:24:03 +00005035 if (check(Count < 0, CountLoc, "Count is negative") ||
5036 parseToken(AsmToken::EndOfStatement,
5037 "unexpected token in '" + Dir + "' directive"))
5038 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005039
5040 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005041 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005042 if (!M)
5043 return true;
5044
5045 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5046 // to hold the macro body with substitutions.
5047 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005048 raw_svector_ostream OS(Buf);
5049 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005050 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5051 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005052 return true;
5053 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005054 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005055
5056 return false;
5057}
5058
Jim Grosbach4b905842013-09-20 23:08:21 +00005059/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005060/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005061bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005062 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005063 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005064 if (check(parseIdentifier(Parameter.Name),
5065 "expected identifier in '.irp' directive") ||
5066 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5067 parseMacroArguments(nullptr, A) ||
5068 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005069 return true;
5070
Rafael Espindola768b41c2012-06-15 14:02:34 +00005071 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005072 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005073 if (!M)
5074 return true;
5075
5076 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5077 // to hold the macro body with substitutions.
5078 SmallString<256> Buf;
5079 raw_svector_ostream OS(Buf);
5080
Craig Topper84008482015-10-10 05:38:14 +00005081 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005082 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5083 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005084 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005085 return true;
5086 }
5087
Jim Grosbach4b905842013-09-20 23:08:21 +00005088 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005089
5090 return false;
5091}
5092
Jim Grosbach4b905842013-09-20 23:08:21 +00005093/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005094/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005095bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005096 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005097 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005098
5099 if (check(parseIdentifier(Parameter.Name),
5100 "expected identifier in '.irpc' directive") ||
5101 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5102 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005103 return true;
5104
5105 if (A.size() != 1 || A.front().size() != 1)
5106 return TokError("unexpected token in '.irpc' directive");
5107
5108 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005109 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5110 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005111
5112 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005113 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005114 if (!M)
5115 return true;
5116
5117 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5118 // to hold the macro body with substitutions.
5119 SmallString<256> Buf;
5120 raw_svector_ostream OS(Buf);
5121
5122 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005123 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005124 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005125 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005126
Toma Tabacu217116e2015-04-27 10:50:29 +00005127 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5128 // This is undocumented, but GAS seems to support it.
5129 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005130 return true;
5131 }
5132
Jim Grosbach4b905842013-09-20 23:08:21 +00005133 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005134
5135 return false;
5136}
5137
Jim Grosbach4b905842013-09-20 23:08:21 +00005138bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005139 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005140 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005141
5142 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005143 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005144 assert(getLexer().is(AsmToken::EndOfStatement));
5145
Jim Grosbach4b905842013-09-20 23:08:21 +00005146 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005147 return false;
5148}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005149
Jim Grosbach4b905842013-09-20 23:08:21 +00005150bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005151 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005152 const MCExpr *Value;
5153 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005154 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005155 return true;
5156 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5157 if (!MCE)
5158 return Error(ExprLoc, "unexpected expression in _emit");
5159 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005160 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005161 return Error(ExprLoc, "literal value out of range for directive");
5162
Craig Topper7d5b2312015-10-10 05:25:02 +00005163 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005164 return false;
5165}
5166
Jim Grosbach4b905842013-09-20 23:08:21 +00005167bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005168 const MCExpr *Value;
5169 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005170 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005171 return true;
5172 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5173 if (!MCE)
5174 return Error(ExprLoc, "unexpected expression in align");
5175 uint64_t IntValue = MCE->getValue();
5176 if (!isPowerOf2_64(IntValue))
5177 return Error(ExprLoc, "literal value not a power of two greater then zero");
5178
Craig Topper7d5b2312015-10-10 05:25:02 +00005179 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005180 return false;
5181}
5182
Chad Rosierf43fcf52013-02-13 21:27:17 +00005183// We are comparing pointers, but the pointers are relative to a single string.
5184// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005185static int rewritesSort(const AsmRewrite *AsmRewriteA,
5186 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005187 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5188 return -1;
5189 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5190 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005191
Chad Rosierfce4fab2013-04-08 17:43:47 +00005192 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5193 // rewrite to the same location. Make sure the SizeDirective rewrite is
5194 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5195 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005196 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5197 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005198 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005199
Jim Grosbach4b905842013-09-20 23:08:21 +00005200 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5201 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005202 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005203 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005204}
5205
Jim Grosbach4b905842013-09-20 23:08:21 +00005206bool AsmParser::parseMSInlineAsm(
5207 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005208 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005209 SmallVectorImpl<std::string> &Constraints,
5210 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5211 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005212 SmallVector<void *, 4> InputDecls;
5213 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005214 SmallVector<bool, 4> InputDeclsAddressOf;
5215 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005216 SmallVector<std::string, 4> InputConstraints;
5217 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005218 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005219
Benjamin Kramer1a136112013-02-15 20:37:21 +00005220 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005221
5222 // Prime the lexer.
5223 Lex();
5224
5225 // While we have input, parse each statement.
5226 unsigned InputIdx = 0;
5227 unsigned OutputIdx = 0;
5228 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005229 // Parse curly braces marking block start/end
5230 if (parseCurlyBlockScope(AsmStrRewrites))
5231 continue;
5232
Eli Friedman0f4871d2012-10-22 23:58:19 +00005233 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005234 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005235
Nirav Dave2364748a2016-09-16 18:30:20 +00005236 if (StatementErr || Info.ParseError) {
5237 // Emit pending errors if any exist.
5238 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005239 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005240 }
5241
5242 // No pending error should exist here.
5243 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005244
Benjamin Kramer1a136112013-02-15 20:37:21 +00005245 if (Info.Opcode == ~0U)
5246 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005247
Benjamin Kramer1a136112013-02-15 20:37:21 +00005248 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005249
Benjamin Kramer1a136112013-02-15 20:37:21 +00005250 // Build the list of clobbers, outputs and inputs.
5251 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005252 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005253
Benjamin Kramer1a136112013-02-15 20:37:21 +00005254 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005255 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005256 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005257
Benjamin Kramer1a136112013-02-15 20:37:21 +00005258 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005259 if (Operand.isReg() && !Operand.needAddressOf() &&
5260 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005261 unsigned NumDefs = Desc.getNumDefs();
5262 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005263 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5264 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005265 continue;
5266 }
5267
5268 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005269 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005270 if (SymName.empty())
5271 continue;
5272
David Blaikie960ea3f2014-06-08 16:18:35 +00005273 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005274 if (!OpDecl)
5275 continue;
5276
5277 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005278 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005279 if (isOutput) {
5280 ++InputIdx;
5281 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005282 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005283 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005284 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005285 } else {
5286 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005287 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5288 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005289 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005290 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005291 }
Reid Kleckneree088972013-12-10 18:27:32 +00005292
5293 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005294 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5295 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005296 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005297 }
5298
5299 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005300 NumOutputs = OutputDecls.size();
5301 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005302
5303 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005304 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5305 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5306 ClobberRegs.end());
5307 Clobbers.assign(ClobberRegs.size(), std::string());
5308 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5309 raw_string_ostream OS(Clobbers[I]);
5310 IP->printRegName(OS, ClobberRegs[I]);
5311 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005312
5313 // Merge the various outputs and inputs. Output are expected first.
5314 if (NumOutputs || NumInputs) {
5315 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005316 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005317 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005318 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005319 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005320 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005321 }
5322 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005323 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005324 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005325 }
5326 }
5327
5328 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005329 std::string AsmStringIR;
5330 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005331 StringRef ASMString =
5332 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5333 const char *AsmStart = ASMString.begin();
5334 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005335 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005336 for (const AsmRewrite &AR : AsmStrRewrites) {
5337 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005338 if (Kind == AOK_Delete)
5339 continue;
5340
David Majnemer8114c1a2014-06-23 02:17:16 +00005341 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005342 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005343
Chad Rosier120eefd2013-03-19 17:32:17 +00005344 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005345 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005346 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005347
Chad Rosier37e755c2012-10-23 17:43:43 +00005348 // Skip the original expression.
5349 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005350 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005351 continue;
5352 }
5353
Chad Rosierff10ed12013-04-12 16:26:42 +00005354 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005355 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005356 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005357 default:
5358 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005359 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005360 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005361 break;
5362 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005363 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005364 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005365 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005366 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005367 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005368 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005369 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005370 break;
5371 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005372 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005373 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005374 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005375 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005376 default: break;
5377 case 8: OS << "byte ptr "; break;
5378 case 16: OS << "word ptr "; break;
5379 case 32: OS << "dword ptr "; break;
5380 case 64: OS << "qword ptr "; break;
5381 case 80: OS << "xword ptr "; break;
5382 case 128: OS << "xmmword ptr "; break;
5383 case 256: OS << "ymmword ptr "; break;
5384 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005385 break;
5386 case AOK_Emit:
5387 OS << ".byte";
5388 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005389 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005390 // MS alignment directives are measured in bytes. If the native assembler
5391 // measures alignment in bytes, we can pass it straight through.
5392 OS << ".align";
5393 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5394 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005395
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005396 // Alignment is in log2 form, so print that instead and skip the original
5397 // immediate.
5398 unsigned Val = AR.Val;
5399 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005400 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005401 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5402 break;
5403 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005404 case AOK_EVEN:
5405 OS << ".even";
5406 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005407 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005408 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005409 OS.flush();
5410 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005411 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005412 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005413 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005414 case AOK_EndOfStatement:
5415 OS << "\n\t";
5416 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005417 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005418
Chad Rosier8bce6642012-10-18 15:49:34 +00005419 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005420 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005421 }
5422
5423 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005424 if (AsmStart != AsmEnd)
5425 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005426
5427 AsmString = OS.str();
5428 return false;
5429}
5430
Pete Cooper80d21cb2015-06-22 19:35:57 +00005431namespace llvm {
5432namespace MCParserUtils {
5433
5434/// Returns whether the given symbol is used anywhere in the given expression,
5435/// or subexpressions.
5436static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5437 switch (Value->getKind()) {
5438 case MCExpr::Binary: {
5439 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5440 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5441 isSymbolUsedInExpression(Sym, BE->getRHS());
5442 }
5443 case MCExpr::Target:
5444 case MCExpr::Constant:
5445 return false;
5446 case MCExpr::SymbolRef: {
5447 const MCSymbol &S =
5448 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5449 if (S.isVariable())
5450 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5451 return &S == Sym;
5452 }
5453 case MCExpr::Unary:
5454 return isSymbolUsedInExpression(
5455 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5456 }
5457
5458 llvm_unreachable("Unknown expr kind!");
5459}
5460
5461bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5462 MCAsmParser &Parser, MCSymbol *&Sym,
5463 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005464
5465 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005466 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005467
5468 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005469 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005470 }
5471
5472 // Note: we don't count b as used in "a = b". This is to allow
5473 // a = b
5474 // b = c
5475
Nirav Dave1a9044b2016-10-24 14:35:29 +00005476 if (Parser.parseToken(AsmToken::EndOfStatement))
5477 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005478
5479 // Validate that the LHS is allowed to be a variable (either it has not been
5480 // used as a symbol, or it is an absolute symbol).
5481 Sym = Parser.getContext().lookupSymbol(Name);
5482 if (Sym) {
5483 // Diagnose assignment to a label.
5484 //
5485 // FIXME: Diagnostics. Note the location of the definition as a label.
5486 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5487 if (isSymbolUsedInExpression(Sym, Value))
5488 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005489 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5490 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005491 ; // Allow redefinitions of undefined symbols only used in directives.
5492 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5493 ; // Allow redefinitions of variables that haven't yet been used.
5494 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5495 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5496 else if (!Sym->isVariable())
5497 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5498 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5499 return Parser.Error(EqualLoc,
5500 "invalid reassignment of non-absolute variable '" +
5501 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005502 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005503 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005504 return false;
5505 } else
5506 Sym = Parser.getContext().getOrCreateSymbol(Name);
5507
5508 Sym->setRedefinable(allow_redef);
5509
5510 return false;
5511}
5512
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005513} // end namespace MCParserUtils
5514} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005515
Daniel Dunbar01e36072010-07-17 02:26:10 +00005516/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005517MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005518 MCStreamer &Out, const MCAsmInfo &MAI,
5519 unsigned CB) {
5520 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005521}