blob: 9568394a36487b918d1ae832b9fdfe859f2bfd0b [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 Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000019#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000020#include "llvm/ADT/SmallVector.h"
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000021#include "llvm/ADT/StringExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000022#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000023#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000024#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000025#include "llvm/BinaryFormat/Dwarf.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000026#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000027#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000028#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000029#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000030#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000031#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000033#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000034#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000035#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000036#include "llvm/MC/MCParser/AsmCond.h"
37#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000038#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000039#include "llvm/MC/MCParser/MCAsmParser.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000040#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000041#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000042#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000043#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000044#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000045#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000046#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000047#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000048#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000049#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000050#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000051#include "llvm/Support/CommandLine.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000052#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000053#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000054#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000055#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000056#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000057#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000058#include <algorithm>
59#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000060#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000061#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000062#include <cstddef>
63#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000064#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000065#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000066#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000067#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000068#include <tuple>
69#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000070#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000071
Chris Lattnerb0133452009-06-21 20:16:42 +000072using namespace llvm;
73
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000074MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000075
Davide Italiano7c9fc732016-07-27 05:51:56 +000076static cl::opt<unsigned> AsmMacroMaxNestingDepth(
77 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
78 cl::desc("The maximum nesting depth allowed for assembly macros."));
79
Daniel Dunbar86033402010-07-12 17:54:38 +000080namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000081
Eli Benderskya313ae62013-01-16 18:56:50 +000082/// \brief Helper types for tracking macro definitions.
83typedef std::vector<AsmToken> MCAsmMacroArgument;
84typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000085
86struct MCAsmMacroParameter {
87 StringRef Name;
88 MCAsmMacroArgument Value;
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000089 bool Required = false;
90 bool Vararg = false;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000091
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000092 MCAsmMacroParameter() = default;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000093};
94
Eli Benderskya313ae62013-01-16 18:56:50 +000095typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
96
97struct MCAsmMacro {
98 StringRef Name;
99 StringRef Body;
100 MCAsmMacroParameters Parameters;
101
102public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000103 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
104 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +0000105};
106
Daniel Dunbar43235712010-07-18 18:54:11 +0000107/// \brief Helper class for storing information about an active macro
108/// instantiation.
109struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +0000110 /// The location of the instantiation.
111 SMLoc InstantiationLoc;
112
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000113 /// The buffer where parsing should resume upon instantiation completion.
114 int ExitBuffer;
115
Daniel Dunbar43235712010-07-18 18:54:11 +0000116 /// The location where parsing should resume upon instantiation completion.
117 SMLoc ExitLoc;
118
Nico Weber155dccd12014-07-24 17:08:39 +0000119 /// The depth of TheCondStack at the start of the instantiation.
120 size_t CondStackDepth;
121
Daniel Dunbar43235712010-07-18 18:54:11 +0000122public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000123 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000124};
125
Eli Friedman0f4871d2012-10-22 23:58:19 +0000126struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000127 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000128 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000129
Jim Grosbach4b905842013-09-20 23:08:21 +0000130 /// \brief The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000131 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000132
Jim Grosbach4b905842013-09-20 23:08:21 +0000133 /// \brief Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000134 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000135
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000136 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000137
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000138 ParseStatementInfo() = delete;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000139 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000140 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000141};
142
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000143/// \brief The concrete assembly parser instance.
144class AsmParser : public MCAsmParser {
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000145private:
146 AsmLexer Lexer;
147 MCContext &Ctx;
148 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000149 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000150 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000151 SourceMgr::DiagHandlerTy SavedDiagHandler;
152 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000153 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000154
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000155 /// This is the current buffer index we're lexing from as managed by the
156 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000157 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000158
159 AsmCond TheCondState;
160 std::vector<AsmCond> TheCondStack;
161
Jim Grosbach4b905842013-09-20 23:08:21 +0000162 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000163 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000164 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000165 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000166
Jim Grosbach4b905842013-09-20 23:08:21 +0000167 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000168 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000169
Jim Grosbach4b905842013-09-20 23:08:21 +0000170 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000171 std::vector<MacroInstantiation*> ActiveMacros;
172
Jim Grosbach4b905842013-09-20 23:08:21 +0000173 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000174 std::deque<MCAsmMacro> MacroLikeBodies;
175
Daniel Dunbar828984f2010-07-18 18:38:02 +0000176 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000177 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000178
Toma Tabacu217116e2015-04-27 10:50:29 +0000179 /// \brief Keeps track of how many .macro's have been instantiated.
180 unsigned NumOfMacroInstantiations;
181
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000182 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000183 struct CppHashInfoTy {
184 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000185 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000186 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000187 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000188 };
189 CppHashInfoTy CppHashInfo;
190
191 /// \brief List of forward directional labels for diagnosis at the end.
192 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
193
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000194 /// When generating dwarf for assembly source files we need to calculate the
195 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000196 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000197 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
198 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000199 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000200 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000201
Devang Patela173ee52012-01-31 18:14:05 +0000202 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000203 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000204
Jim Grosbach4b905842013-09-20 23:08:21 +0000205 /// \brief is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000206 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000207
Jim Grosbach4b905842013-09-20 23:08:21 +0000208 /// \brief Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000209 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000210
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000211public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000212 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000213 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000214 AsmParser(const AsmParser &) = delete;
215 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000216 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000217
Craig Topper59be68f2014-03-08 07:14:16 +0000218 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000219
Craig Topper59be68f2014-03-08 07:14:16 +0000220 void addDirectiveHandler(StringRef Directive,
221 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000222 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000223 }
224
Toma Tabacu11e14a92015-04-21 11:50:52 +0000225 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
226 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
227 }
228
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000229 /// @name MCAsmParser Interface
230 /// {
231
Craig Topper59be68f2014-03-08 07:14:16 +0000232 SourceMgr &getSourceManager() override { return SrcMgr; }
233 MCAsmLexer &getLexer() override { return Lexer; }
234 MCContext &getContext() override { return Ctx; }
235 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000236
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000237 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
238
Craig Topper59be68f2014-03-08 07:14:16 +0000239 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000240 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000241 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000242 else
243 return AssemblerDialect;
244 }
Craig Topper59be68f2014-03-08 07:14:16 +0000245 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000246 AssemblerDialect = i;
247 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000248
Nirav Dave2364748a2016-09-16 18:30:20 +0000249 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
250 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
251 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000252
Craig Topper59be68f2014-03-08 07:14:16 +0000253 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000254
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000255 void setParsingInlineAsm(bool V) override {
256 ParsingInlineAsm = V;
257 Lexer.setParsingMSInlineAsm(V);
258 }
Craig Topper59be68f2014-03-08 07:14:16 +0000259 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000260
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000261 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000262 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000263 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000264 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000265 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000266 const MCInstrInfo *MII, const MCInstPrinter *IP,
267 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000268
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000269 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000270 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
271 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
272 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000273 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
274 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000275 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000276
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000277 /// \brief Parse a floating point expression using the float \p Semantics
278 /// and set \p Res to the value.
279 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
280
Jim Grosbach4b905842013-09-20 23:08:21 +0000281 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000282 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000283 bool parseIdentifier(StringRef &Res) override;
284 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000285
Nirav Davef43cc9f2016-10-10 15:24:54 +0000286 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000287
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000288 /// }
289
290private:
Michael Zuckerman763e60e2017-05-04 10:37:00 +0000291 bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc);
Michael Zuckerman1f1a9122017-05-10 13:08:11 +0000292 void altMacroString(StringRef AltMacroStr, std::string &Res);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000293 bool parseStatement(ParseStatementInfo &Info,
294 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000295 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000296 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000297
Jim Grosbach4b905842013-09-20 23:08:21 +0000298 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000299 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000300 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000301 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000302 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000303 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000304
Eli Benderskya313ae62013-01-16 18:56:50 +0000305 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000306 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000307
308 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000309 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000310
311 /// \brief Lookup a previously defined macro.
312 /// \param Name Macro name.
313 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000314 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000315
316 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000317 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000318
319 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000320 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000321
322 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000323 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000324
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000325 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000326 ///
327 /// \param M The macro.
328 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000329 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000330
331 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000332 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000333
David Majnemer91fc4c22014-01-29 18:57:46 +0000334 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000335 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000336
337 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000338 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000339
Jim Grosbach4b905842013-09-20 23:08:21 +0000340 void printMacroInstantiations();
341 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000342 SMRange Range = None) const {
343 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000344 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000345 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000346 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000347
Jim Grosbach4b905842013-09-20 23:08:21 +0000348 /// \brief Enter the specified file. This returns true on failure.
349 bool enterIncludeFile(const std::string &Filename);
350
351 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000352 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000353 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
354 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000355
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000356 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000357 /// current token is not set; clients should ensure Lex() is called
358 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000359 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000360 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000361 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000362 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000363
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000364 /// \brief Parse up to the end of statement and a return the contents from the
365 /// current token until the end of the statement; the current token on exit
366 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000367 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000368
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000369 /// \brief Parse until the end of a statement or a comma is encountered,
370 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000371 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000372
Jim Grosbach4b905842013-09-20 23:08:21 +0000373 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000374 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000375
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000376 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
377 MCBinaryExpr::Opcode &Kind);
378
Jim Grosbach4b905842013-09-20 23:08:21 +0000379 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
380 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
381 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000382
Jim Grosbach4b905842013-09-20 23:08:21 +0000383 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000384
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000385 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
386 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
387
Eli Bendersky17233942013-01-15 22:59:42 +0000388 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000389 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000390 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000391 DK_SET,
392 DK_EQU,
393 DK_EQUIV,
394 DK_ASCII,
395 DK_ASCIZ,
396 DK_STRING,
397 DK_BYTE,
398 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000399 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000400 DK_VALUE,
401 DK_2BYTE,
402 DK_LONG,
403 DK_INT,
404 DK_4BYTE,
405 DK_QUAD,
406 DK_8BYTE,
407 DK_OCTA,
408 DK_DC,
409 DK_DC_A,
410 DK_DC_B,
411 DK_DC_D,
412 DK_DC_L,
413 DK_DC_S,
414 DK_DC_W,
415 DK_DC_X,
416 DK_DCB,
417 DK_DCB_B,
418 DK_DCB_D,
419 DK_DCB_L,
420 DK_DCB_S,
421 DK_DCB_W,
422 DK_DCB_X,
423 DK_DS,
424 DK_DS_B,
425 DK_DS_D,
426 DK_DS_L,
427 DK_DS_P,
428 DK_DS_S,
429 DK_DS_W,
430 DK_DS_X,
431 DK_SINGLE,
432 DK_FLOAT,
433 DK_DOUBLE,
434 DK_ALIGN,
435 DK_ALIGN32,
436 DK_BALIGN,
437 DK_BALIGNW,
438 DK_BALIGNL,
439 DK_P2ALIGN,
440 DK_P2ALIGNW,
441 DK_P2ALIGNL,
442 DK_ORG,
443 DK_FILL,
444 DK_ENDR,
445 DK_BUNDLE_ALIGN_MODE,
446 DK_BUNDLE_LOCK,
447 DK_BUNDLE_UNLOCK,
448 DK_ZERO,
449 DK_EXTERN,
450 DK_GLOBL,
451 DK_GLOBAL,
452 DK_LAZY_REFERENCE,
453 DK_NO_DEAD_STRIP,
454 DK_SYMBOL_RESOLVER,
455 DK_PRIVATE_EXTERN,
456 DK_REFERENCE,
457 DK_WEAK_DEFINITION,
458 DK_WEAK_REFERENCE,
459 DK_WEAK_DEF_CAN_BE_HIDDEN,
460 DK_COMM,
461 DK_COMMON,
462 DK_LCOMM,
463 DK_ABORT,
464 DK_INCLUDE,
465 DK_INCBIN,
466 DK_CODE16,
467 DK_CODE16GCC,
468 DK_REPT,
469 DK_IRP,
470 DK_IRPC,
471 DK_IF,
472 DK_IFEQ,
473 DK_IFGE,
474 DK_IFGT,
475 DK_IFLE,
476 DK_IFLT,
477 DK_IFNE,
478 DK_IFB,
479 DK_IFNB,
480 DK_IFC,
481 DK_IFEQS,
482 DK_IFNC,
483 DK_IFNES,
484 DK_IFDEF,
485 DK_IFNDEF,
486 DK_IFNOTDEF,
487 DK_ELSEIF,
488 DK_ELSE,
489 DK_ENDIF,
490 DK_SPACE,
491 DK_SKIP,
492 DK_FILE,
493 DK_LINE,
494 DK_LOC,
495 DK_STABS,
496 DK_CV_FILE,
497 DK_CV_FUNC_ID,
498 DK_CV_INLINE_SITE_ID,
499 DK_CV_LOC,
500 DK_CV_LINETABLE,
501 DK_CV_INLINE_LINETABLE,
502 DK_CV_DEF_RANGE,
503 DK_CV_STRINGTABLE,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000504 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000505 DK_CV_FILECHECKSUM_OFFSET,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000506 DK_CFI_SECTIONS,
507 DK_CFI_STARTPROC,
508 DK_CFI_ENDPROC,
509 DK_CFI_DEF_CFA,
510 DK_CFI_DEF_CFA_OFFSET,
511 DK_CFI_ADJUST_CFA_OFFSET,
512 DK_CFI_DEF_CFA_REGISTER,
513 DK_CFI_OFFSET,
514 DK_CFI_REL_OFFSET,
515 DK_CFI_PERSONALITY,
516 DK_CFI_LSDA,
517 DK_CFI_REMEMBER_STATE,
518 DK_CFI_RESTORE_STATE,
519 DK_CFI_SAME_VALUE,
520 DK_CFI_RESTORE,
521 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000522 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000523 DK_CFI_SIGNAL_FRAME,
524 DK_CFI_UNDEFINED,
525 DK_CFI_REGISTER,
526 DK_CFI_WINDOW_SAVE,
527 DK_MACROS_ON,
528 DK_MACROS_OFF,
529 DK_ALTMACRO,
530 DK_NOALTMACRO,
531 DK_MACRO,
532 DK_EXITM,
533 DK_ENDM,
534 DK_ENDMACRO,
535 DK_PURGEM,
536 DK_SLEB128,
537 DK_ULEB128,
538 DK_ERR,
539 DK_ERROR,
540 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000541 DK_PRINT,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000542 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000543 };
544
Jim Grosbach4b905842013-09-20 23:08:21 +0000545 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000546 /// directives parsed by this class.
547 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000548
549 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000550 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000551 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000552 bool parseDirectiveValue(StringRef IDVal,
553 unsigned Size); // ".byte", ".long", ...
554 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
555 bool parseDirectiveRealValue(StringRef IDVal,
556 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000557 bool parseDirectiveFill(); // ".fill"
558 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000559 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000560 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
561 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000562 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000563 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000564
Eli Bendersky17233942013-01-15 22:59:42 +0000565 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000566 bool parseDirectiveFile(SMLoc DirectiveLoc);
567 bool parseDirectiveLine();
568 bool parseDirectiveLoc();
569 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000570
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000571 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
572 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000573 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000574 bool parseDirectiveCVFuncId();
575 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000576 bool parseDirectiveCVLoc();
577 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000578 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000579 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000580 bool parseDirectiveCVStringTable();
581 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000582 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000583
Eli Bendersky17233942013-01-15 22:59:42 +0000584 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000585 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000586 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000587 bool parseDirectiveCFISections();
588 bool parseDirectiveCFIStartProc();
589 bool parseDirectiveCFIEndProc();
590 bool parseDirectiveCFIDefCfaOffset();
591 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
592 bool parseDirectiveCFIAdjustCfaOffset();
593 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
594 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
595 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
596 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
597 bool parseDirectiveCFIRememberState();
598 bool parseDirectiveCFIRestoreState();
599 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
600 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
601 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000602 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000603 bool parseDirectiveCFISignalFrame();
604 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000605
606 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000607 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000608 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000609 bool parseDirectiveEndMacro(StringRef Directive);
610 bool parseDirectiveMacro(SMLoc DirectiveLoc);
611 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000612 // alternate macro mode directives
613 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000614 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000615 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000616 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000617 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000618 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000619 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000620
Eli Bendersky17233942013-01-15 22:59:42 +0000621 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000622 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000623
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000624 // ".dcb"
625 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
626 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000627 // ".ds"
628 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000629
Eli Bendersky17233942013-01-15 22:59:42 +0000630 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000631 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000632
Jim Grosbach4b905842013-09-20 23:08:21 +0000633 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000634 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000635 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000636
Jim Grosbach4b905842013-09-20 23:08:21 +0000637 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000638
Jim Grosbach4b905842013-09-20 23:08:21 +0000639 bool parseDirectiveAbort(); // ".abort"
640 bool parseDirectiveInclude(); // ".include"
641 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000642
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000643 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
644 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000645 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000646 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000647 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000648 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000649 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
650 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000651 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000652 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
653 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
654 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
655 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000656 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000657
Jim Grosbach4b905842013-09-20 23:08:21 +0000658 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000659 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000660
Rafael Espindola34b9c512012-06-03 23:57:14 +0000661 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000662 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
663 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000664 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000665 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000666 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
667 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
668 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000669
Chad Rosierc7f552c2013-02-12 21:33:51 +0000670 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000671 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000672 size_t Len);
673
674 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000675 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000676
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000677 // "end"
678 bool parseDirectiveEnd(SMLoc DirectiveLoc);
679
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000680 // ".err" or ".error"
681 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000682
Nico Weber404012b2014-07-24 16:26:06 +0000683 // ".warning"
684 bool parseDirectiveWarning(SMLoc DirectiveLoc);
685
Coby Tayree01e53202017-10-02 14:36:31 +0000686 // .print <double-quotes-string>
687 bool parseDirectivePrint(SMLoc DirectiveLoc);
688
Eli Bendersky17233942013-01-15 22:59:42 +0000689 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000690};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000691
692} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000693
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000694namespace llvm {
695
696extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000697extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000698extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000699
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000700} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000701
Chris Lattnerc35681b2010-01-19 19:46:13 +0000702enum { DEFAULT_ADDRSPACE = 0 };
703
David Blaikie9f380a32015-03-16 18:06:57 +0000704AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000705 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000706 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000707 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000708 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000709 // Save the old handler.
710 SavedDiagHandler = SrcMgr.getDiagHandler();
711 SavedDiagContext = SrcMgr.getDiagContext();
712 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000713 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000714 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000715
Daniel Dunbarc5011082010-07-12 18:12:02 +0000716 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000717 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
718 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000719 PlatformParser.reset(createCOFFAsmParser());
720 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000721 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000722 PlatformParser.reset(createDarwinAsmParser());
723 IsDarwin = true;
724 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000725 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000726 PlatformParser.reset(createELFAsmParser());
727 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000728 case MCObjectFileInfo::IsWasm:
729 llvm_unreachable("Wasm parsing not supported yet");
730 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000731 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000732
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000733 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000734 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000735
736 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000737}
738
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000739AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000740 assert((HadError || ActiveMacros.empty()) &&
741 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000742
743 // Restore the saved diagnostics handler and context for use during
744 // finalization.
745 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000746}
747
Jim Grosbach4b905842013-09-20 23:08:21 +0000748void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000749 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000750 for (std::vector<MacroInstantiation *>::const_reverse_iterator
751 it = ActiveMacros.rbegin(),
752 ie = ActiveMacros.rend();
753 it != ie; ++it)
754 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000755 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000756}
757
Nirav Dave2364748a2016-09-16 18:30:20 +0000758void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
759 printPendingErrors();
760 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000761 printMacroInstantiations();
762}
763
Nirav Dave2364748a2016-09-16 18:30:20 +0000764bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000765 if(getTargetParser().getTargetOptions().MCNoWarn)
766 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000767 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000768 return Error(L, Msg, Range);
769 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000770 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000771 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000772}
773
Nirav Dave2364748a2016-09-16 18:30:20 +0000774bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000775 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000776 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000777 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000778 return true;
779}
780
Jim Grosbach4b905842013-09-20 23:08:21 +0000781bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000782 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000783 unsigned NewBuf =
784 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
785 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000786 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000787
Sean Callanan7a77eae2010-01-21 00:19:58 +0000788 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000789 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000790 return false;
791}
Daniel Dunbar43235712010-07-18 18:54:11 +0000792
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000793/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000794/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000795/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000796bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
797 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000798 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000799 unsigned NewBuf =
800 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
801 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000802 return true;
803
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000804 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000805 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
806 Bytes = Bytes.drop_front(Skip);
807 if (Count) {
808 int64_t Res;
809 if (!Count->evaluateAsAbsolute(Res))
810 return Error(Loc, "expected absolute expression");
811 if (Res < 0)
812 return Warning(Loc, "negative count has no effect");
813 Bytes = Bytes.take_front(Res);
814 }
815 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000816 return false;
817}
818
Alp Tokera55b95b2014-07-06 10:33:31 +0000819void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
820 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000821 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
822 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000823}
824
Sean Callanan7a77eae2010-01-21 00:19:58 +0000825const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000826 if (Lexer.getTok().is(AsmToken::Error))
827 Error(Lexer.getErrLoc(), Lexer.getErr());
828
Nirav Dave53a72f42016-07-11 12:42:14 +0000829 // if it's a end of statement with a comment in it
830 if (getTok().is(AsmToken::EndOfStatement)) {
831 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000832 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000833 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
834 Out.addExplicitComment(Twine(getTok().getString()));
835 }
836
Sean Callanan7a77eae2010-01-21 00:19:58 +0000837 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000838
839 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000840 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000841 if (MAI.preserveAsmComments())
842 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000843 tok = &Lexer.Lex();
844 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000845
Sean Callanan7a77eae2010-01-21 00:19:58 +0000846 if (tok->is(AsmToken::Eof)) {
847 // If this is the end of an included file, pop the parent file off the
848 // include stack.
849 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
850 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000851 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000852 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000853 }
854 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000855
Sean Callanan7a77eae2010-01-21 00:19:58 +0000856 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000857}
858
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000859bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000860 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000861 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000862 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000863
Chris Lattner36e02122009-06-21 20:54:55 +0000864 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000865 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000866
867 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000868 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000869 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000870
Kevin Enderby6469fc22011-11-01 22:27:22 +0000871 // If we are generating dwarf for assembly source files save the initial text
872 // section and generate a .file directive.
873 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000874 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000875 if (!Sec->getBeginSymbol()) {
876 MCSymbol *SectionStartSym = getContext().createTempSymbol();
877 getStreamer().EmitLabel(SectionStartSym);
878 Sec->setBeginSymbol(SectionStartSym);
879 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000880 bool InsertResult = getContext().addGenDwarfSection(Sec);
881 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000882 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000883 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
884 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000885 }
886
Chris Lattner73f36112009-07-02 21:53:43 +0000887 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000888 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000889 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000890 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000891 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000892
Nirav Dave2364748a2016-09-16 18:30:20 +0000893 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
894 // for printing ErrMsg via Lex() only if no (presumably better) parser error
895 // exists.
896 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000897 Lex();
898 }
899
Nirav Dave2364748a2016-09-16 18:30:20 +0000900 // parseStatement returned true so may need to emit an error.
901 printPendingErrors();
902
903 // Skipping to the next line if needed.
904 if (!getLexer().isAtStartOfStatement())
905 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000906 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000907
Nirav Dave2364748a2016-09-16 18:30:20 +0000908 // All errors should have been emitted.
909 assert(!hasPendingError() && "unexpected error from parseStatement");
910
Oliver Stannard21718282016-07-26 14:19:47 +0000911 getTargetParser().flushPendingInstructions(getStreamer());
912
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000913 if (TheCondState.TheCond != StartingCondState.TheCond ||
914 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000915 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000916 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000917 const auto &LineTables = getContext().getMCDwarfLineTables();
918 if (!LineTables.empty()) {
919 unsigned Index = 0;
920 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
921 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000922 printError(getTok().getLoc(), "unassigned file number: " +
923 Twine(Index) +
924 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000925 ++Index;
926 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000927 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000928
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000929 // Check to see that all assembler local symbols were actually defined.
930 // Targets that don't do subsections via symbols may not want this, though,
931 // so conservatively exclude them. Only do this if we're finalizing, though,
932 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000933 if (!NoFinalize) {
934 if (MAI.hasSubsectionsViaSymbols()) {
935 for (const auto &TableEntry : getContext().getSymbols()) {
936 MCSymbol *Sym = TableEntry.getValue();
937 // Variable symbols may not be marked as defined, so check those
938 // explicitly. If we know it's a variable, we have a definition for
939 // the purposes of this check.
940 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
941 // FIXME: We would really like to refer back to where the symbol was
942 // first referenced for a source location. We need to add something
943 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000944 printError(getTok().getLoc(), "assembler local symbol '" +
945 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000946 }
947 }
948
949 // Temporary symbols like the ones for directional jumps don't go in the
950 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000951 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
952 if (std::get<2>(LocSym)->isUndefined()) {
953 // Reset the state of any "# line file" directives we've seen to the
954 // context as it was at the diagnostic site.
955 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000956 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000957 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000958 }
959 }
960
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000961 // Finalize the output stream if there are no errors and if the client wants
962 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000963 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000964 Out.Finish();
965
Oliver Stannard07b43d32015-11-17 09:58:07 +0000966 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000967}
968
Nirav Davef43cc9f2016-10-10 15:24:54 +0000969bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000970 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000971 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000972 return Error(getTok().getLoc(),
973 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000974 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000975 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000976}
977
Jim Grosbach4b905842013-09-20 23:08:21 +0000978/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000979void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000980 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000981 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000982
Chris Lattnere5074c42009-06-22 01:29:09 +0000983 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000984 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000985 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000986}
987
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000988StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000989 const char *Start = getTok().getLoc().getPointer();
990
Jim Grosbach4b905842013-09-20 23:08:21 +0000991 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000992 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000993
994 const char *End = getTok().getLoc().getPointer();
995 return StringRef(Start, End - Start);
996}
Chris Lattner78db3622009-06-22 05:51:26 +0000997
Jim Grosbach4b905842013-09-20 23:08:21 +0000998StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000999 const char *Start = getTok().getLoc().getPointer();
1000
1001 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +00001002 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +00001003 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00001004
1005 const char *End = getTok().getLoc().getPointer();
1006 return StringRef(Start, End - Start);
1007}
1008
Jim Grosbach4b905842013-09-20 23:08:21 +00001009/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001010/// NOTE: This assumes the leading '(' has already been consumed.
1011///
1012/// parenexpr ::= expr)
1013///
Jim Grosbach4b905842013-09-20 23:08:21 +00001014bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1015 if (parseExpression(Res))
1016 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001017 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +00001018 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001019 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001020 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +00001021 return false;
1022}
Chris Lattner78db3622009-06-22 05:51:26 +00001023
Jim Grosbach4b905842013-09-20 23:08:21 +00001024/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001025/// NOTE: This assumes the leading '[' has already been consumed.
1026///
1027/// bracketexpr ::= expr]
1028///
Jim Grosbach4b905842013-09-20 23:08:21 +00001029bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1030 if (parseExpression(Res))
1031 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001032 EndLoc = getTok().getEndLoc();
1033 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1034 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001035 return false;
1036}
1037
Jim Grosbach4b905842013-09-20 23:08:21 +00001038/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001039/// primaryexpr ::= (parenexpr
1040/// primaryexpr ::= symbol
1041/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001042/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001043/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001044bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001045 SMLoc FirstTokenLoc = getLexer().getLoc();
1046 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1047 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001048 default:
1049 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001050 // If we have an error assume that we've already handled it.
1051 case AsmToken::Error:
1052 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001053 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001054 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001055 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001056 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001057 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001058 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001059 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001060 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001061 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001062 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001063 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001064 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001065 // We may have failed but $ may be a valid token.
1066 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001067 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001068 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001069 // This is a '$' reference, which references the current PC. Emit a
1070 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001071 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001072 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001073 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001074 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001075 EndLoc = FirstTokenLoc;
1076 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001077 }
1078 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001079 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001080 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001081 // Parse symbol variant
1082 std::pair<StringRef, StringRef> Split;
1083 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001084 if (FirstTokenKind == AsmToken::String) {
1085 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001086 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001087 SMLoc AtLoc = getLexer().getLoc();
1088 StringRef VName;
1089 if (parseIdentifier(VName))
1090 return Error(AtLoc, "expected symbol variant after '@'");
1091
1092 Split = std::make_pair(Identifier, VName);
1093 }
1094 } else {
1095 Split = Identifier.split('@');
1096 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001097 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001098 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001099 StringRef VName;
1100 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001101 // eat ')'.
1102 if (parseToken(AsmToken::RParen,
1103 "unexpected token in variant, expected ')'"))
1104 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001105 Split = std::make_pair(Identifier, VName);
1106 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001107
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001108 EndLoc = SMLoc::getFromPointer(Identifier.end());
1109
Daniel Dunbard20cda02009-10-16 01:34:54 +00001110 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001111 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001112 if (SymbolName.empty())
1113 return true;
1114
Hans Wennborgce69d772013-10-18 20:46:28 +00001115 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001116
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001117 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001118 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001119 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001120 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1121 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001122 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001123 Variant = MCSymbolRefExpr::VK_None;
1124 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001125 return Error(SMLoc::getFromPointer(Split.second.begin()),
1126 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001127 }
1128 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001129
Jim Grosbach6f482002015-05-18 18:43:14 +00001130 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001131
Daniel Dunbard20cda02009-10-16 01:34:54 +00001132 // If this is an absolute variable reference, substitute it now to preserve
1133 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001134 if (Sym->isVariable() &&
1135 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001136 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001137 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001138
Vedant Kumar86dbd922015-08-31 17:44:53 +00001139 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001140 return false;
1141 }
1142
1143 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001144 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001145 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001146 }
David Woodhousef42a6662014-02-01 16:20:54 +00001147 case AsmToken::BigNum:
1148 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001149 case AsmToken::Integer: {
1150 SMLoc Loc = getTok().getLoc();
1151 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001152 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001153 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001154 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001155 // Look for 'b' or 'f' following an Integer as a directional label
1156 if (Lexer.getKind() == AsmToken::Identifier) {
1157 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001158 // Lookup the symbol variant if used.
1159 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1160 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1161 if (Split.first.size() != IDVal.size()) {
1162 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001163 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001164 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001165 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001166 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001167 if (IDVal == "f" || IDVal == "b") {
1168 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001169 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001170 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001171 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001172 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001173 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001174 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001175 Lex(); // Eat identifier.
1176 }
1177 }
Chris Lattner78db3622009-06-22 05:51:26 +00001178 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001179 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001180 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001181 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001182 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001183 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001184 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001185 Lex(); // Eat token.
1186 return false;
1187 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001188 case AsmToken::Dot: {
1189 // This is a '.' reference, which references the current PC. Emit a
1190 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001191 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001192 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001193 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001194 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001195 Lex(); // Eat identifier.
1196 return false;
1197 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001198 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001199 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001200 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001201 case AsmToken::LBrac:
1202 if (!PlatformParser->HasBracketExpressions())
1203 return TokError("brackets expression not supported on this target");
1204 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001205 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001206 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001207 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001208 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001209 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001210 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001211 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001212 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001213 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001214 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001215 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001216 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001217 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001218 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001219 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001220 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001221 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001222 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001223 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001224 // MIPS unary expression operators. The lexer won't generate these tokens if
1225 // MCAsmInfo::HasMipsExpressions is false for the target.
1226 case AsmToken::PercentCall16:
1227 case AsmToken::PercentCall_Hi:
1228 case AsmToken::PercentCall_Lo:
1229 case AsmToken::PercentDtprel_Hi:
1230 case AsmToken::PercentDtprel_Lo:
1231 case AsmToken::PercentGot:
1232 case AsmToken::PercentGot_Disp:
1233 case AsmToken::PercentGot_Hi:
1234 case AsmToken::PercentGot_Lo:
1235 case AsmToken::PercentGot_Ofst:
1236 case AsmToken::PercentGot_Page:
1237 case AsmToken::PercentGottprel:
1238 case AsmToken::PercentGp_Rel:
1239 case AsmToken::PercentHi:
1240 case AsmToken::PercentHigher:
1241 case AsmToken::PercentHighest:
1242 case AsmToken::PercentLo:
1243 case AsmToken::PercentNeg:
1244 case AsmToken::PercentPcrel_Hi:
1245 case AsmToken::PercentPcrel_Lo:
1246 case AsmToken::PercentTlsgd:
1247 case AsmToken::PercentTlsldm:
1248 case AsmToken::PercentTprel_Hi:
1249 case AsmToken::PercentTprel_Lo:
1250 Lex(); // Eat the operator.
1251 if (Lexer.isNot(AsmToken::LParen))
1252 return TokError("expected '(' after operator");
1253 Lex(); // Eat the operator.
1254 if (parseExpression(Res, EndLoc))
1255 return true;
1256 if (Lexer.isNot(AsmToken::RParen))
1257 return TokError("expected ')'");
1258 Lex(); // Eat the operator.
1259 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1260 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001261 }
1262}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001263
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001264bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001265 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001266 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001267}
1268
Daniel Dunbar55f16672010-09-17 02:47:07 +00001269const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001270AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001271 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001272 // Ask the target implementation about this expression first.
1273 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1274 if (NewE)
1275 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001276 // Recurse over the given expression, rebuilding it to apply the given variant
1277 // if there is exactly one symbol.
1278 switch (E->getKind()) {
1279 case MCExpr::Target:
1280 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001281 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001282
1283 case MCExpr::SymbolRef: {
1284 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1285
1286 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001287 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1288 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001289 return E;
1290 }
1291
Jim Grosbach13760bd2015-05-30 01:25:56 +00001292 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001293 }
1294
1295 case MCExpr::Unary: {
1296 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001297 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001298 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001299 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001300 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001301 }
1302
1303 case MCExpr::Binary: {
1304 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001305 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1306 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001307
1308 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001309 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001310
Jim Grosbach4b905842013-09-20 23:08:21 +00001311 if (!LHS)
1312 LHS = BE->getLHS();
1313 if (!RHS)
1314 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001315
Jim Grosbach13760bd2015-05-30 01:25:56 +00001316 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001317 }
1318 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001319
Craig Toppera2886c22012-02-07 05:05:23 +00001320 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001321}
1322
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001323/// This function checks if the next token is <string> type or arithmetic.
1324/// string that begin with character '<' must end with character '>'.
1325/// otherwise it is arithmetics.
1326/// If the function returns a 'true' value,
1327/// the End argument will be filled with the last location pointed to the '>'
1328/// character.
1329
1330/// There is a gap between the AltMacro's documentation and the single quote implementation.
1331/// GCC does not fully support this feature and so we will not support it.
1332/// TODO: Adding single quote as a string.
1333bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1334 assert((StrLoc.getPointer() != NULL) &&
1335 "Argument to the function cannot be a NULL value");
1336 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001337 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1338 (*CharPtr != '\0')) {
1339 if (*CharPtr == '!')
1340 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001341 CharPtr++;
1342 }
1343 if (*CharPtr == '>') {
1344 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1345 return true;
1346 }
1347 return false;
1348}
1349
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001350/// \brief creating a string without the escape characters '!'.
1351void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) {
Michael Zuckermanff298792017-05-10 14:00:57 +00001352 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001353 if (AltMacroStr[Pos] == '!')
1354 Pos++;
1355 Res += AltMacroStr[Pos];
1356 }
1357}
1358
Jim Grosbach4b905842013-09-20 23:08:21 +00001359/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001360///
Jim Grosbachbd164242011-08-20 16:24:13 +00001361/// expr ::= expr &&,|| expr -> lowest.
1362/// expr ::= expr |,^,&,! expr
1363/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1364/// expr ::= expr <<,>> expr
1365/// expr ::= expr +,- expr
1366/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001367/// expr ::= primaryexpr
1368///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001369bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001370 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001371 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001372 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001373 return true;
1374
Daniel Dunbar55f16672010-09-17 02:47:07 +00001375 // As a special case, we support 'a op b @ modifier' by rewriting the
1376 // expression to include the modifier. This is inefficient, but in general we
1377 // expect users to use 'a@modifier op b'.
1378 if (Lexer.getKind() == AsmToken::At) {
1379 Lex();
1380
1381 if (Lexer.isNot(AsmToken::Identifier))
1382 return TokError("unexpected symbol modifier following '@'");
1383
1384 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001385 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001386 if (Variant == MCSymbolRefExpr::VK_Invalid)
1387 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1388
Jim Grosbach4b905842013-09-20 23:08:21 +00001389 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001390 if (!ModifiedRes) {
1391 return TokError("invalid modifier '" + getTok().getIdentifier() +
1392 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001393 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001394
Daniel Dunbar55f16672010-09-17 02:47:07 +00001395 Res = ModifiedRes;
1396 Lex();
1397 }
1398
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001399 // Try to constant fold it up front, if possible.
1400 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001401 if (Res->evaluateAsAbsolute(Value))
1402 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001403
1404 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001405}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001406
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001407bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001408 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001409 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001410}
1411
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001412bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1413 SMLoc &EndLoc) {
1414 if (parseParenExpr(Res, EndLoc))
1415 return true;
1416
1417 for (; ParenDepth > 0; --ParenDepth) {
1418 if (parseBinOpRHS(1, Res, EndLoc))
1419 return true;
1420
1421 // We don't Lex() the last RParen.
1422 // This is the same behavior as parseParenExpression().
1423 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001424 EndLoc = getTok().getEndLoc();
1425 if (parseToken(AsmToken::RParen,
1426 "expected ')' in parentheses expression"))
1427 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001428 }
1429 }
1430 return false;
1431}
1432
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001433bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001434 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001435
Daniel Dunbar75630b32009-06-30 02:10:03 +00001436 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001437 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001438 return true;
1439
Jim Grosbach13760bd2015-05-30 01:25:56 +00001440 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001441 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001442
1443 return false;
1444}
1445
David Majnemer0993e0b2015-10-26 03:15:34 +00001446static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1447 MCBinaryExpr::Opcode &Kind,
1448 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001449 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001450 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001451 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001452
Jim Grosbach4b905842013-09-20 23:08:21 +00001453 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001454 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001455 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001456 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001457 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001458 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001459 return 1;
1460
Jim Grosbach4b905842013-09-20 23:08:21 +00001461 // Low Precedence: |, &, ^
1462 //
1463 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001464 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001465 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001466 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001467 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001468 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001469 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001470 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001471 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001472 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001473
Jim Grosbach4b905842013-09-20 23:08:21 +00001474 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001475 case AsmToken::EqualEqual:
1476 Kind = MCBinaryExpr::EQ;
1477 return 3;
1478 case AsmToken::ExclaimEqual:
1479 case AsmToken::LessGreater:
1480 Kind = MCBinaryExpr::NE;
1481 return 3;
1482 case AsmToken::Less:
1483 Kind = MCBinaryExpr::LT;
1484 return 3;
1485 case AsmToken::LessEqual:
1486 Kind = MCBinaryExpr::LTE;
1487 return 3;
1488 case AsmToken::Greater:
1489 Kind = MCBinaryExpr::GT;
1490 return 3;
1491 case AsmToken::GreaterEqual:
1492 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001493 return 3;
1494
Jim Grosbach4b905842013-09-20 23:08:21 +00001495 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001496 case AsmToken::LessLess:
1497 Kind = MCBinaryExpr::Shl;
1498 return 4;
1499 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001500 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001501 return 4;
1502
Jim Grosbach4b905842013-09-20 23:08:21 +00001503 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001504 case AsmToken::Plus:
1505 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001506 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001507 case AsmToken::Minus:
1508 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001509 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001510
Jim Grosbach4b905842013-09-20 23:08:21 +00001511 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001512 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001513 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001514 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001515 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001516 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001517 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001518 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001519 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001520 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001521 }
1522}
1523
David Majnemer0993e0b2015-10-26 03:15:34 +00001524static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1525 MCBinaryExpr::Opcode &Kind,
1526 bool ShouldUseLogicalShr) {
1527 switch (K) {
1528 default:
1529 return 0; // not a binop.
1530
1531 // Lowest Precedence: &&, ||
1532 case AsmToken::AmpAmp:
1533 Kind = MCBinaryExpr::LAnd;
1534 return 2;
1535 case AsmToken::PipePipe:
1536 Kind = MCBinaryExpr::LOr;
1537 return 1;
1538
1539 // Low Precedence: ==, !=, <>, <, <=, >, >=
1540 case AsmToken::EqualEqual:
1541 Kind = MCBinaryExpr::EQ;
1542 return 3;
1543 case AsmToken::ExclaimEqual:
1544 case AsmToken::LessGreater:
1545 Kind = MCBinaryExpr::NE;
1546 return 3;
1547 case AsmToken::Less:
1548 Kind = MCBinaryExpr::LT;
1549 return 3;
1550 case AsmToken::LessEqual:
1551 Kind = MCBinaryExpr::LTE;
1552 return 3;
1553 case AsmToken::Greater:
1554 Kind = MCBinaryExpr::GT;
1555 return 3;
1556 case AsmToken::GreaterEqual:
1557 Kind = MCBinaryExpr::GTE;
1558 return 3;
1559
1560 // Low Intermediate Precedence: +, -
1561 case AsmToken::Plus:
1562 Kind = MCBinaryExpr::Add;
1563 return 4;
1564 case AsmToken::Minus:
1565 Kind = MCBinaryExpr::Sub;
1566 return 4;
1567
1568 // High Intermediate Precedence: |, &, ^
1569 //
1570 // FIXME: gas seems to support '!' as an infix operator?
1571 case AsmToken::Pipe:
1572 Kind = MCBinaryExpr::Or;
1573 return 5;
1574 case AsmToken::Caret:
1575 Kind = MCBinaryExpr::Xor;
1576 return 5;
1577 case AsmToken::Amp:
1578 Kind = MCBinaryExpr::And;
1579 return 5;
1580
1581 // Highest Precedence: *, /, %, <<, >>
1582 case AsmToken::Star:
1583 Kind = MCBinaryExpr::Mul;
1584 return 6;
1585 case AsmToken::Slash:
1586 Kind = MCBinaryExpr::Div;
1587 return 6;
1588 case AsmToken::Percent:
1589 Kind = MCBinaryExpr::Mod;
1590 return 6;
1591 case AsmToken::LessLess:
1592 Kind = MCBinaryExpr::Shl;
1593 return 6;
1594 case AsmToken::GreaterGreater:
1595 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1596 return 6;
1597 }
1598}
1599
1600unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1601 MCBinaryExpr::Opcode &Kind) {
1602 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1603 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1604 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1605}
1606
Jim Grosbach4b905842013-09-20 23:08:21 +00001607/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001608/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001609bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001610 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001611 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001612 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001613 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001614 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001615
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001616 // If the next token is lower precedence than we are allowed to eat, return
1617 // successfully with what we ate already.
1618 if (TokPrec < Precedence)
1619 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001620
Sean Callanan686ed8d2010-01-19 20:22:31 +00001621 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001622
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001623 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001624 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001625 if (parsePrimaryExpr(RHS, EndLoc))
1626 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001627
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001628 // If BinOp binds less tightly with RHS than the operator after RHS, let
1629 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001630 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001631 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001632 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1633 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001634
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001635 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001636 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001637 }
1638}
1639
Chris Lattner36e02122009-06-21 20:54:55 +00001640/// ParseStatement:
1641/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001642/// ::= Label* Directive ...Operands... EndOfStatement
1643/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001644bool AsmParser::parseStatement(ParseStatementInfo &Info,
1645 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001646 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001647 // Eat initial spaces and comments
1648 while (Lexer.is(AsmToken::Space))
1649 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001650 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001651 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001652 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001653 getTok().getString().front() == '\n')
1654 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001655 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001656 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001657 }
Nirav Davefd910412016-06-17 16:06:17 +00001658 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001659 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001660 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001661 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001662 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001663 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001664 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001665 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001666 if (Lexer.is(AsmToken::Integer)) {
1667 LocalLabelVal = getTok().getIntVal();
1668 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001669 if (!TheCondState.Ignore) {
1670 Lex(); // always eat a token
1671 return Error(IDLoc, "unexpected token at start of statement");
1672 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001673 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001674 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001675 IDVal = getTok().getString();
1676 Lex(); // Consume the integer token to be used as an identifier token.
1677 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001678 if (!TheCondState.Ignore) {
1679 Lex(); // always eat a token
1680 return Error(IDLoc, "unexpected token at start of statement");
1681 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001682 }
1683 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001684 } else if (Lexer.is(AsmToken::Dot)) {
1685 // Treat '.' as a valid identifier in this context.
1686 Lex();
1687 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001688 } else if (Lexer.is(AsmToken::LCurly)) {
1689 // Treat '{' as a valid identifier in this context.
1690 Lex();
1691 IDVal = "{";
1692
1693 } else if (Lexer.is(AsmToken::RCurly)) {
1694 // Treat '}' as a valid identifier in this context.
1695 Lex();
1696 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001697 } else if (Lexer.is(AsmToken::Star) &&
1698 getTargetParser().starIsStartOfStatement()) {
1699 // Accept '*' as a valid start of statement.
1700 Lex();
1701 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001702 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001703 if (!TheCondState.Ignore) {
1704 Lex(); // always eat a token
1705 return Error(IDLoc, "unexpected token at start of statement");
1706 }
Chris Lattner926885c2010-04-17 18:14:27 +00001707 IDVal = "";
1708 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001709
Chris Lattner926885c2010-04-17 18:14:27 +00001710 // Handle conditional assembly here before checking for skipping. We
1711 // have to do this so that .endif isn't skipped in a ".if 0" block for
1712 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001713 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001714 DirectiveKindMap.find(IDVal);
1715 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1716 ? DK_NO_DIRECTIVE
1717 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001718 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001719 default:
1720 break;
1721 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001722 case DK_IFEQ:
1723 case DK_IFGE:
1724 case DK_IFGT:
1725 case DK_IFLE:
1726 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001727 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001728 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001729 case DK_IFB:
1730 return parseDirectiveIfb(IDLoc, true);
1731 case DK_IFNB:
1732 return parseDirectiveIfb(IDLoc, false);
1733 case DK_IFC:
1734 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001735 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001736 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001737 case DK_IFNC:
1738 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001739 case DK_IFNES:
1740 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001741 case DK_IFDEF:
1742 return parseDirectiveIfdef(IDLoc, true);
1743 case DK_IFNDEF:
1744 case DK_IFNOTDEF:
1745 return parseDirectiveIfdef(IDLoc, false);
1746 case DK_ELSEIF:
1747 return parseDirectiveElseIf(IDLoc);
1748 case DK_ELSE:
1749 return parseDirectiveElse(IDLoc);
1750 case DK_ENDIF:
1751 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001752 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001753
Eli Bendersky88024712013-01-16 19:32:36 +00001754 // Ignore the statement if in the middle of inactive conditional
1755 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001756 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001757 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001758 return false;
1759 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001760
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001761 // FIXME: Recurse on local labels?
1762
1763 // See what kind of statement we have.
1764 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001765 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001766 if (!getTargetParser().isLabel(ID))
1767 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001768 if (checkForValidSection())
1769 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001770
Chris Lattner36e02122009-06-21 20:54:55 +00001771 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001772 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001773
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001774 // Diagnose attempt to use '.' as a label.
1775 if (IDVal == ".")
1776 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1777
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001778 // Diagnose attempt to use a variable as a label.
1779 //
1780 // FIXME: Diagnostics. Note the location of the definition as a label.
1781 // FIXME: This doesn't diagnose assignment to a symbol which has been
1782 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001783 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001784 if (LocalLabelVal == -1) {
1785 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001786 StringRef RewrittenLabel =
1787 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001788 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001789 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001790 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1791 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001792 IDVal = RewrittenLabel;
1793 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001794 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001795 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001796 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001797 // End of Labels should be treated as end of line for lexing
1798 // purposes but that information is not available to the Lexer who
1799 // does not understand Labels. This may cause us to see a Hash
1800 // here instead of a preprocessor line comment.
1801 if (getTok().is(AsmToken::Hash)) {
1802 StringRef CommentStr = parseStringToEndOfStatement();
1803 Lexer.Lex();
1804 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1805 }
1806
Nirav Dave8ea792d2016-07-13 14:03:12 +00001807 // Consume any end of statement token, if present, to avoid spurious
1808 // AddBlankLine calls().
1809 if (getTok().is(AsmToken::EndOfStatement)) {
1810 Lex();
1811 }
1812
Daniel Dunbare73b2672009-08-26 22:13:22 +00001813 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001814 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001815 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001816
Kevin Enderbye7739d42011-12-09 18:09:40 +00001817 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001818 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001819 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001820 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1821 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001822
Tim Northover1744d0a2013-10-25 12:49:50 +00001823 getTargetParser().onLabelParsed(Sym);
1824
Eli Friedman0f4871d2012-10-22 23:58:19 +00001825 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001826 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001827
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001828 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001829 if (!getTargetParser().equalIsAsmAssignment())
1830 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001831 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001832 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001833
Jim Grosbach4b905842013-09-20 23:08:21 +00001834 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001835
1836 default: // Normal instruction or directive.
1837 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001838 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001839
1840 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001841 if (areMacrosEnabled())
1842 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1843 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001844 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001845
Michael J. Spencer530ce852010-10-09 11:00:50 +00001846 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001847
Eli Bendersky17233942013-01-15 22:59:42 +00001848 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001849 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001850 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001851 //
Eli Bendersky17233942013-01-15 22:59:42 +00001852 // 1. The target-specific assembly parser. Some directives are target
1853 // specific or may potentially behave differently on certain targets.
1854 // 2. Asm parser extensions. For example, platform-specific parsers
1855 // (like the ELF parser) register themselves as extensions.
1856 // 3. The generic directive parser implemented by this class. These are
1857 // all the directives that behave in a target and platform independent
1858 // manner, or at least have a default behavior that's shared between
1859 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001860
Oliver Stannard21718282016-07-26 14:19:47 +00001861 getTargetParser().flushPendingInstructions(getStreamer());
1862
Nirav Dave2364748a2016-09-16 18:30:20 +00001863 SMLoc StartTokLoc = getTok().getLoc();
1864 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1865
1866 if (hasPendingError())
1867 return true;
1868 // Currently the return value should be true if we are
1869 // uninterested but as this is at odds with the standard parsing
1870 // convention (return true = error) we have instances of a parsed
1871 // directive that fails returning true as an error. Catch these
1872 // cases as best as possible errors here.
1873 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1874 return true;
1875 // Return if we did some parsing or believe we succeeded.
1876 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001877 return false;
1878
Alp Tokercb402912014-01-24 17:20:08 +00001879 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001880 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001881 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1882 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001883 if (Handler.first)
1884 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1885
1886 // Finally, if no one else is interested in this directive, it must be
1887 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001888 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001889 default:
1890 break;
1891 case DK_SET:
1892 case DK_EQU:
1893 return parseDirectiveSet(IDVal, true);
1894 case DK_EQUIV:
1895 return parseDirectiveSet(IDVal, false);
1896 case DK_ASCII:
1897 return parseDirectiveAscii(IDVal, false);
1898 case DK_ASCIZ:
1899 case DK_STRING:
1900 return parseDirectiveAscii(IDVal, true);
1901 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001902 case DK_DC_B:
1903 return parseDirectiveValue(IDVal, 1);
1904 case DK_DC:
1905 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001906 case DK_SHORT:
1907 case DK_VALUE:
1908 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001909 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001910 case DK_LONG:
1911 case DK_INT:
1912 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001913 case DK_DC_L:
1914 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001915 case DK_QUAD:
1916 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001917 return parseDirectiveValue(IDVal, 8);
1918 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001919 return parseDirectiveValue(
1920 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001921 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001922 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001923 case DK_SINGLE:
1924 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001925 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001926 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001927 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001928 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001929 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001930 case DK_ALIGN: {
1931 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1932 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1933 }
1934 case DK_ALIGN32: {
1935 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1936 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1937 }
1938 case DK_BALIGN:
1939 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1940 case DK_BALIGNW:
1941 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1942 case DK_BALIGNL:
1943 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1944 case DK_P2ALIGN:
1945 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1946 case DK_P2ALIGNW:
1947 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1948 case DK_P2ALIGNL:
1949 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1950 case DK_ORG:
1951 return parseDirectiveOrg();
1952 case DK_FILL:
1953 return parseDirectiveFill();
1954 case DK_ZERO:
1955 return parseDirectiveZero();
1956 case DK_EXTERN:
1957 eatToEndOfStatement(); // .extern is the default, ignore it.
1958 return false;
1959 case DK_GLOBL:
1960 case DK_GLOBAL:
1961 return parseDirectiveSymbolAttribute(MCSA_Global);
1962 case DK_LAZY_REFERENCE:
1963 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1964 case DK_NO_DEAD_STRIP:
1965 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1966 case DK_SYMBOL_RESOLVER:
1967 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1968 case DK_PRIVATE_EXTERN:
1969 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1970 case DK_REFERENCE:
1971 return parseDirectiveSymbolAttribute(MCSA_Reference);
1972 case DK_WEAK_DEFINITION:
1973 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1974 case DK_WEAK_REFERENCE:
1975 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1976 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1977 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1978 case DK_COMM:
1979 case DK_COMMON:
1980 return parseDirectiveComm(/*IsLocal=*/false);
1981 case DK_LCOMM:
1982 return parseDirectiveComm(/*IsLocal=*/true);
1983 case DK_ABORT:
1984 return parseDirectiveAbort();
1985 case DK_INCLUDE:
1986 return parseDirectiveInclude();
1987 case DK_INCBIN:
1988 return parseDirectiveIncbin();
1989 case DK_CODE16:
1990 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001991 return TokError(Twine(IDVal) +
1992 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001993 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001994 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001995 case DK_IRP:
1996 return parseDirectiveIrp(IDLoc);
1997 case DK_IRPC:
1998 return parseDirectiveIrpc(IDLoc);
1999 case DK_ENDR:
2000 return parseDirectiveEndr(IDLoc);
2001 case DK_BUNDLE_ALIGN_MODE:
2002 return parseDirectiveBundleAlignMode();
2003 case DK_BUNDLE_LOCK:
2004 return parseDirectiveBundleLock();
2005 case DK_BUNDLE_UNLOCK:
2006 return parseDirectiveBundleUnlock();
2007 case DK_SLEB128:
2008 return parseDirectiveLEB128(true);
2009 case DK_ULEB128:
2010 return parseDirectiveLEB128(false);
2011 case DK_SPACE:
2012 case DK_SKIP:
2013 return parseDirectiveSpace(IDVal);
2014 case DK_FILE:
2015 return parseDirectiveFile(IDLoc);
2016 case DK_LINE:
2017 return parseDirectiveLine();
2018 case DK_LOC:
2019 return parseDirectiveLoc();
2020 case DK_STABS:
2021 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002022 case DK_CV_FILE:
2023 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002024 case DK_CV_FUNC_ID:
2025 return parseDirectiveCVFuncId();
2026 case DK_CV_INLINE_SITE_ID:
2027 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002028 case DK_CV_LOC:
2029 return parseDirectiveCVLoc();
2030 case DK_CV_LINETABLE:
2031 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002032 case DK_CV_INLINE_LINETABLE:
2033 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002034 case DK_CV_DEF_RANGE:
2035 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002036 case DK_CV_STRINGTABLE:
2037 return parseDirectiveCVStringTable();
2038 case DK_CV_FILECHECKSUMS:
2039 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002040 case DK_CV_FILECHECKSUM_OFFSET:
2041 return parseDirectiveCVFileChecksumOffset();
Jim Grosbach4b905842013-09-20 23:08:21 +00002042 case DK_CFI_SECTIONS:
2043 return parseDirectiveCFISections();
2044 case DK_CFI_STARTPROC:
2045 return parseDirectiveCFIStartProc();
2046 case DK_CFI_ENDPROC:
2047 return parseDirectiveCFIEndProc();
2048 case DK_CFI_DEF_CFA:
2049 return parseDirectiveCFIDefCfa(IDLoc);
2050 case DK_CFI_DEF_CFA_OFFSET:
2051 return parseDirectiveCFIDefCfaOffset();
2052 case DK_CFI_ADJUST_CFA_OFFSET:
2053 return parseDirectiveCFIAdjustCfaOffset();
2054 case DK_CFI_DEF_CFA_REGISTER:
2055 return parseDirectiveCFIDefCfaRegister(IDLoc);
2056 case DK_CFI_OFFSET:
2057 return parseDirectiveCFIOffset(IDLoc);
2058 case DK_CFI_REL_OFFSET:
2059 return parseDirectiveCFIRelOffset(IDLoc);
2060 case DK_CFI_PERSONALITY:
2061 return parseDirectiveCFIPersonalityOrLsda(true);
2062 case DK_CFI_LSDA:
2063 return parseDirectiveCFIPersonalityOrLsda(false);
2064 case DK_CFI_REMEMBER_STATE:
2065 return parseDirectiveCFIRememberState();
2066 case DK_CFI_RESTORE_STATE:
2067 return parseDirectiveCFIRestoreState();
2068 case DK_CFI_SAME_VALUE:
2069 return parseDirectiveCFISameValue(IDLoc);
2070 case DK_CFI_RESTORE:
2071 return parseDirectiveCFIRestore(IDLoc);
2072 case DK_CFI_ESCAPE:
2073 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002074 case DK_CFI_RETURN_COLUMN:
2075 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002076 case DK_CFI_SIGNAL_FRAME:
2077 return parseDirectiveCFISignalFrame();
2078 case DK_CFI_UNDEFINED:
2079 return parseDirectiveCFIUndefined(IDLoc);
2080 case DK_CFI_REGISTER:
2081 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002082 case DK_CFI_WINDOW_SAVE:
2083 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002084 case DK_MACROS_ON:
2085 case DK_MACROS_OFF:
2086 return parseDirectiveMacrosOnOff(IDVal);
2087 case DK_MACRO:
2088 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002089 case DK_ALTMACRO:
2090 case DK_NOALTMACRO:
2091 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002092 case DK_EXITM:
2093 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002094 case DK_ENDM:
2095 case DK_ENDMACRO:
2096 return parseDirectiveEndMacro(IDVal);
2097 case DK_PURGEM:
2098 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002099 case DK_END:
2100 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002101 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002102 return parseDirectiveError(IDLoc, false);
2103 case DK_ERROR:
2104 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002105 case DK_WARNING:
2106 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002107 case DK_RELOC:
2108 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002109 case DK_DCB:
2110 case DK_DCB_W:
2111 return parseDirectiveDCB(IDVal, 2);
2112 case DK_DCB_B:
2113 return parseDirectiveDCB(IDVal, 1);
2114 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002115 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002116 case DK_DCB_L:
2117 return parseDirectiveDCB(IDVal, 4);
2118 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002119 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002120 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002121 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002122 return TokError(Twine(IDVal) +
2123 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002124 case DK_DS:
2125 case DK_DS_W:
2126 return parseDirectiveDS(IDVal, 2);
2127 case DK_DS_B:
2128 return parseDirectiveDS(IDVal, 1);
2129 case DK_DS_D:
2130 return parseDirectiveDS(IDVal, 8);
2131 case DK_DS_L:
2132 case DK_DS_S:
2133 return parseDirectiveDS(IDVal, 4);
2134 case DK_DS_P:
2135 case DK_DS_X:
2136 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002137 case DK_PRINT:
2138 return parseDirectivePrint(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00002139 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002140
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002141 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002142 }
Chris Lattner36e02122009-06-21 20:54:55 +00002143
Chad Rosierc7f552c2013-02-12 21:33:51 +00002144 // __asm _emit or __asm __emit
2145 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2146 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002147 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002148
2149 // __asm align
2150 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002151 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002152
Coby Tayree3847be92017-04-04 17:57:23 +00002153 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002154 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002155 if (checkForValidSection())
2156 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002157
Chris Lattner7cbfa442010-05-19 23:34:33 +00002158 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002159 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002160 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002161 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2162 Info.ParsedOperands);
2163 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002164
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002165 // Dump the parsed representation, if requested.
2166 if (getShowParsedOperands()) {
2167 SmallString<256> Str;
2168 raw_svector_ostream OS(Str);
2169 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002170 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002171 if (i != 0)
2172 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002173 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002174 }
2175 OS << "]";
2176
Jim Grosbach4b905842013-09-20 23:08:21 +00002177 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002178 }
2179
Nirav Dave2364748a2016-09-16 18:30:20 +00002180 // Fail even if ParseInstruction erroneously returns false.
2181 if (hasPendingError() || ParseHadError)
2182 return true;
2183
Oliver Stannard8b273082014-06-19 15:52:37 +00002184 // If we are generating dwarf for the current section then generate a .loc
2185 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002186 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002187 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002188 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002189 unsigned Line;
2190 if (ActiveMacros.empty())
2191 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2192 else
Frederic Riss16238d92015-06-25 21:57:33 +00002193 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2194 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002195
Eli Bendersky88024712013-01-16 19:32:36 +00002196 // If we previously parsed a cpp hash file line comment then make sure the
2197 // current Dwarf File is for the CppHashFilename if not then emit the
2198 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002199 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002200 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002201 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002202 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002203
Jim Grosbach4b905842013-09-20 23:08:21 +00002204 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2205 // cache with the different Loc from the call above we save the last
2206 // info we queried here with SrcMgr.FindLineNumber().
2207 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002208 if (LastQueryIDLoc == CppHashInfo.Loc &&
2209 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002210 CppHashLocLineNo = LastQueryLine;
2211 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002212 CppHashLocLineNo =
2213 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002214 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002215 LastQueryIDLoc = CppHashInfo.Loc;
2216 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002217 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002218 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002219 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002220
Jim Grosbach4b905842013-09-20 23:08:21 +00002221 getStreamer().EmitDwarfLocDirective(
2222 getContext().getGenDwarfFileNumber(), Line, 0,
2223 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2224 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002225 }
2226
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002227 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002228 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002229 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002230 if (getTargetParser().MatchAndEmitInstruction(
2231 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2232 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002233 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002234 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002235 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002236}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002237
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002238// Parse and erase curly braces marking block start/end
2239bool
2240AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2241 // Identify curly brace marking block start/end
2242 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2243 return false;
2244
2245 SMLoc StartLoc = Lexer.getLoc();
2246 Lex(); // Eat the brace
2247 if (Lexer.is(AsmToken::EndOfStatement))
2248 Lex(); // Eat EndOfStatement following the brace
2249
2250 // Erase the block start/end brace from the output asm string
2251 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2252 StartLoc.getPointer());
2253 return true;
2254}
2255
Jim Grosbach4b905842013-09-20 23:08:21 +00002256/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002257/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002258bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002259 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002260 // Lexer only ever emits HashDirective if it fully formed if it's
2261 // done the checking already so this is an internal error.
2262 assert(getTok().is(AsmToken::Integer) &&
2263 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002264 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002265 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002266 assert(getTok().is(AsmToken::String) &&
2267 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002268 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002269 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002270
Kevin Enderby72553612011-09-13 23:45:18 +00002271 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002272 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002273
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002274 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002275 CppHashInfo.Loc = L;
2276 CppHashInfo.Filename = Filename;
2277 CppHashInfo.LineNumber = LineNumber;
2278 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002279 return false;
2280}
2281
Jim Grosbach4b905842013-09-20 23:08:21 +00002282/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002283/// for the Filename and LineNo if any in the diagnostic.
2284void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002285 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002286 raw_ostream &OS = errs();
2287
2288 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002289 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002290 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2291 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002292 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002293
Jim Grosbach4b905842013-09-20 23:08:21 +00002294 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002295 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002296 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2297 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2298 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002299 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2300 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002301 }
2302
Eric Christophera7c32732012-12-18 00:30:54 +00002303 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002304 // manager changed or buffer changed (like in a nested include) then just
2305 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002306 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002307 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002308 if (Parser->SavedDiagHandler)
2309 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2310 else
Craig Topper353eda42014-04-24 06:44:33 +00002311 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002312 return;
2313 }
2314
Eric Christophera7c32732012-12-18 00:30:54 +00002315 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002316 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2317 // for the diagnostic.
2318 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002319
2320 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2321 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002322 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002323 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002324 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002325
Jim Grosbach4b905842013-09-20 23:08:21 +00002326 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2327 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002328 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002329
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002330 if (Parser->SavedDiagHandler)
2331 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2332 else
Craig Topper353eda42014-04-24 06:44:33 +00002333 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002334}
2335
Rafael Espindola2c064482012-08-21 18:29:30 +00002336// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2337// difference being that that function accepts '@' as part of identifiers and
2338// we can't do that. AsmLexer.cpp should probably be changed to handle
2339// '@' as a special case when needed.
2340static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002341 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2342 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002343}
2344
Rafael Espindola34b9c512012-06-03 23:57:14 +00002345bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002346 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002347 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002348 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002349 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002350 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002351 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002352 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002353
Preston Gurd05500642012-09-19 20:36:12 +00002354 // A macro without parameters is handled differently on Darwin:
2355 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002356 while (!Body.empty()) {
2357 // Scan for the next substitution.
2358 std::size_t End = Body.size(), Pos = 0;
2359 for (; Pos != End; ++Pos) {
2360 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002361 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002362 // This macro has no parameters, look for $0, $1, etc.
2363 if (Body[Pos] != '$' || Pos + 1 == End)
2364 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002365
Rafael Espindola1134ab232011-06-05 02:43:45 +00002366 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002367 if (Next == '$' || Next == 'n' ||
2368 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002369 break;
2370 } else {
2371 // This macro has parameters, look for \foo, \bar, etc.
2372 if (Body[Pos] == '\\' && Pos + 1 != End)
2373 break;
2374 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002375 }
2376
2377 // Add the prefix.
2378 OS << Body.slice(0, Pos);
2379
2380 // Check if we reached the end.
2381 if (Pos == End)
2382 break;
2383
Benjamin Kramer513e7442014-02-20 13:36:32 +00002384 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002385 switch (Body[Pos + 1]) {
2386 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002387 case '$':
2388 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002389 break;
2390
Jim Grosbach4b905842013-09-20 23:08:21 +00002391 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002392 case 'n':
2393 OS << A.size();
2394 break;
2395
Jim Grosbach4b905842013-09-20 23:08:21 +00002396 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002397 default: {
2398 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002399 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002400 if (Index >= A.size())
2401 break;
2402
2403 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002404 for (const AsmToken &Token : A[Index])
2405 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002406 break;
2407 }
2408 }
2409 Pos += 2;
2410 } else {
2411 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002412
2413 // Check for the \@ pseudo-variable.
2414 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002415 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002416 else
2417 while (isIdentifierChar(Body[I]) && I + 1 != End)
2418 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002419
Jim Grosbach4b905842013-09-20 23:08:21 +00002420 const char *Begin = Body.data() + Pos + 1;
2421 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002422 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002423
Toma Tabacu217116e2015-04-27 10:50:29 +00002424 if (Argument == "@") {
2425 OS << NumOfMacroInstantiations;
2426 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002427 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002428 for (; Index < NParameters; ++Index)
2429 if (Parameters[Index].Name == Argument)
2430 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002431
Toma Tabacu217116e2015-04-27 10:50:29 +00002432 if (Index == NParameters) {
2433 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2434 Pos += 3;
2435 else {
2436 OS << '\\' << Argument;
2437 Pos = I;
2438 }
2439 } else {
2440 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002441 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002442 // For altmacro mode, you can write '%expr'.
2443 // The prefix '%' evaluates the expression 'expr'
2444 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2445 // Here, we identify the integer token which is the result of the
2446 // absolute expression evaluation and replace it with its string representation.
2447 if ((Lexer.IsaAltMacroMode()) &&
2448 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2449 // Emit an integer value to the buffer.
2450 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002451 // Only Token that was validated as a string and begins with '<'
2452 // is considered altMacroString!!!
2453 else if ((Lexer.IsaAltMacroMode()) &&
2454 (*(Token.getString().begin()) == '<') &&
2455 Token.is(AsmToken::String)) {
2456 std::string Res;
2457 altMacroString(Token.getStringContents(), Res);
2458 OS << Res;
2459 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002460 // We expect no quotes around the string's contents when
2461 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002462 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002463 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002464 else
Craig Topper84008482015-10-10 05:38:14 +00002465 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002466
2467 Pos += 1 + Argument.size();
2468 }
Preston Gurd05500642012-09-19 20:36:12 +00002469 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002470 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002471 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002472 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002473 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002474
Rafael Espindola1134ab232011-06-05 02:43:45 +00002475 return false;
2476}
Daniel Dunbar43235712010-07-18 18:54:11 +00002477
Nico Weber2a8f9222014-07-24 16:29:04 +00002478MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002479 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002480 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002481 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002482
Jim Grosbach4b905842013-09-20 23:08:21 +00002483static bool isOperator(AsmToken::TokenKind kind) {
2484 switch (kind) {
2485 default:
2486 return false;
2487 case AsmToken::Plus:
2488 case AsmToken::Minus:
2489 case AsmToken::Tilde:
2490 case AsmToken::Slash:
2491 case AsmToken::Star:
2492 case AsmToken::Dot:
2493 case AsmToken::Equal:
2494 case AsmToken::EqualEqual:
2495 case AsmToken::Pipe:
2496 case AsmToken::PipePipe:
2497 case AsmToken::Caret:
2498 case AsmToken::Amp:
2499 case AsmToken::AmpAmp:
2500 case AsmToken::Exclaim:
2501 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002502 case AsmToken::Less:
2503 case AsmToken::LessEqual:
2504 case AsmToken::LessLess:
2505 case AsmToken::LessGreater:
2506 case AsmToken::Greater:
2507 case AsmToken::GreaterEqual:
2508 case AsmToken::GreaterGreater:
2509 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002510 }
2511}
2512
David Majnemer16252452014-01-29 00:07:39 +00002513namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002514
David Majnemer16252452014-01-29 00:07:39 +00002515class AsmLexerSkipSpaceRAII {
2516public:
2517 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2518 Lexer.setSkipSpace(SkipSpace);
2519 }
2520
2521 ~AsmLexerSkipSpaceRAII() {
2522 Lexer.setSkipSpace(true);
2523 }
2524
2525private:
2526 AsmLexer &Lexer;
2527};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002528
2529} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002530
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002531bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2532
2533 if (Vararg) {
2534 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2535 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002536 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002537 }
2538 return false;
2539 }
2540
Rafael Espindola768b41c2012-06-15 14:02:34 +00002541 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002542
David Majnemer16252452014-01-29 00:07:39 +00002543 // Darwin doesn't use spaces to delmit arguments.
2544 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002545
Scott Egertona1fa68a2016-02-11 13:48:49 +00002546 bool SpaceEaten;
2547
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002548 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002549 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002550 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002551 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002552
Scott Egertona1fa68a2016-02-11 13:48:49 +00002553 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002554
Scott Egertona1fa68a2016-02-11 13:48:49 +00002555 if (Lexer.is(AsmToken::Comma))
2556 break;
2557
2558 if (Lexer.is(AsmToken::Space)) {
2559 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002560 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002561 }
Preston Gurd05500642012-09-19 20:36:12 +00002562
2563 // Spaces can delimit parameters, but could also be part an expression.
2564 // If the token after a space is an operator, add the token and the next
2565 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002566 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002567 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002568 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002569 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002570
Scott Egertona1fa68a2016-02-11 13:48:49 +00002571 // Whitespace after an operator can be ignored.
2572 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002573 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002574
2575 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002576 }
2577 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002578 if (SpaceEaten)
2579 break;
Preston Gurd05500642012-09-19 20:36:12 +00002580 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002581
Jim Grosbach4b905842013-09-20 23:08:21 +00002582 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002583 // to be able to fill in the remaining default parameter values
2584 if (Lexer.is(AsmToken::EndOfStatement))
2585 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002586
2587 // Adjust the current parentheses level.
2588 if (Lexer.is(AsmToken::LParen))
2589 ++ParenLevel;
2590 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2591 --ParenLevel;
2592
2593 // Append the token to the current argument list.
2594 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002595 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002596 }
Preston Gurd05500642012-09-19 20:36:12 +00002597
Rafael Espindola768b41c2012-06-15 14:02:34 +00002598 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002599 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002600 return false;
2601}
2602
2603// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002604bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002605 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002606 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002607 bool NamedParametersFound = false;
2608 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002609
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002610 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002611 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002612
Rafael Espindola768b41c2012-06-15 14:02:34 +00002613 // Parse two kinds of macro invocations:
2614 // - macros defined without any parameters accept an arbitrary number of them
2615 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002616 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002617 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2618 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002619 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002620 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002621
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002622 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002623 if (parseIdentifier(FA.Name))
2624 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002625
Nirav Dave2364748a2016-09-16 18:30:20 +00002626 if (Lexer.isNot(AsmToken::Equal))
2627 return TokError("expected '=' after formal parameter identifier");
2628
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002629 Lex();
2630
2631 NamedParametersFound = true;
2632 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002633 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002634
Nirav Dave2364748a2016-09-16 18:30:20 +00002635 if (NamedParametersFound && FA.Name.empty())
2636 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002637
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002638 SMLoc StrLoc = Lexer.getLoc();
2639 SMLoc EndLoc;
Michael Zuckerman56704612017-05-01 13:20:12 +00002640 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
Michael Zuckerman56704612017-05-01 13:20:12 +00002641 const MCExpr *AbsoluteExp;
2642 int64_t Value;
2643 /// Eat '%'
2644 Lex();
2645 if (parseExpression(AbsoluteExp, EndLoc))
2646 return false;
2647 if (!AbsoluteExp->evaluateAsAbsolute(Value))
2648 return Error(StrLoc, "expected absolute expression");
2649 const char *StrChar = StrLoc.getPointer();
2650 const char *EndChar = EndLoc.getPointer();
2651 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2652 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002653 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2654 isAltmacroString(StrLoc, EndLoc)) {
2655 const char *StrChar = StrLoc.getPointer();
2656 const char *EndChar = EndLoc.getPointer();
2657 jumpToLoc(EndLoc, CurBuffer);
2658 /// Eat from '<' to '>'
2659 Lex();
2660 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2661 FA.Value.push_back(newToken);
2662 } else if(parseMacroArgument(FA.Value, Vararg))
Michael Zuckerman56704612017-05-01 13:20:12 +00002663 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002664
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002665 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002666 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002667 unsigned FAI = 0;
2668 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002669 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002670 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002671
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002672 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002673 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002674 return Error(IDLoc, "parameter named '" + FA.Name +
2675 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002676 }
2677 PI = FAI;
2678 }
2679
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002680 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002681 if (A.size() <= PI)
2682 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002683 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002684
2685 if (FALocs.size() <= PI)
2686 FALocs.resize(PI + 1);
2687
2688 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002689 }
Jim Grosbach206661622012-07-30 22:44:17 +00002690
Preston Gurd242ed3152012-09-19 20:29:04 +00002691 // At the end of the statement, fill in remaining arguments that have
2692 // default values. If there aren't any, then the next argument is
2693 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002694 if (Lexer.is(AsmToken::EndOfStatement)) {
2695 bool Failure = false;
2696 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2697 if (A[FAI].empty()) {
2698 if (M->Parameters[FAI].Required) {
2699 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2700 "missing value for required parameter "
2701 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2702 Failure = true;
2703 }
2704
2705 if (!M->Parameters[FAI].Value.empty())
2706 A[FAI] = M->Parameters[FAI].Value;
2707 }
2708 }
2709 return Failure;
2710 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002711
2712 if (Lexer.is(AsmToken::Comma))
2713 Lex();
2714 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002715
2716 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002717}
2718
Jim Grosbach4b905842013-09-20 23:08:21 +00002719const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002720 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2721 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002722}
2723
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002724void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2725 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002726}
2727
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002728void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002729
Jim Grosbach4b905842013-09-20 23:08:21 +00002730bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002731 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2732 // eliminate this, although we should protect against infinite loops.
2733 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2734 if (ActiveMacros.size() == MaxNestingDepth) {
2735 std::ostringstream MaxNestingDepthError;
2736 MaxNestingDepthError << "macros cannot be nested more than "
2737 << MaxNestingDepth << " levels deep."
2738 << " Use -asm-macro-max-nesting-depth to increase "
2739 "this limit.";
2740 return TokError(MaxNestingDepthError.str());
2741 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002742
Eli Bendersky38274122013-01-14 23:22:36 +00002743 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002744 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002745 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002746
Rafael Espindola1134ab232011-06-05 02:43:45 +00002747 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2748 // to hold the macro body with substitutions.
2749 SmallString<256> Buf;
2750 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002751 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002752
Toma Tabacu217116e2015-04-27 10:50:29 +00002753 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002754 return true;
2755
Eli Bendersky38274122013-01-14 23:22:36 +00002756 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002757 // instantiation.
2758 OS << ".endmacro\n";
2759
Rafael Espindola3560ff22014-08-27 20:03:13 +00002760 std::unique_ptr<MemoryBuffer> Instantiation =
2761 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002762
Daniel Dunbar43235712010-07-18 18:54:11 +00002763 // Create the macro instantiation object and add to the current macro
2764 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002765 MacroInstantiation *MI = new MacroInstantiation(
2766 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002767 ActiveMacros.push_back(MI);
2768
Toma Tabacu217116e2015-04-27 10:50:29 +00002769 ++NumOfMacroInstantiations;
2770
Daniel Dunbar43235712010-07-18 18:54:11 +00002771 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002772 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002773 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002774 Lex();
2775
2776 return false;
2777}
2778
Jim Grosbach4b905842013-09-20 23:08:21 +00002779void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002780 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002781 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002782 Lex();
2783
2784 // Pop the instantiation entry.
2785 delete ActiveMacros.back();
2786 ActiveMacros.pop_back();
2787}
2788
Jim Grosbach4b905842013-09-20 23:08:21 +00002789bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002790 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002791 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002792 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002793 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2794 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002795 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002796
Pete Cooper80d21cb2015-06-22 19:35:57 +00002797 if (!Sym) {
2798 // In the case where we parse an expression starting with a '.', we will
2799 // not generate an error, nor will we create a symbol. In this case we
2800 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002801 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002802 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002803
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002804 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002805 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002806 if (NoDeadStrip)
2807 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2808
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002809 return false;
2810}
2811
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002812/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002813/// ::= identifier
2814/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002815bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002816 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002817 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2818 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002819 // handle this as a context dependent token, instead we detect adjacent tokens
2820 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002821 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2822 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002823
Hans Wennborgce69d772013-10-18 20:46:28 +00002824 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002825
2826 AsmToken Buf[1];
2827 Lexer.peekTokens(Buf, false);
2828
2829 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002830 return true;
2831
Hans Wennborgce69d772013-10-18 20:46:28 +00002832 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002833 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002834 return true;
2835
Nirav Daved0463322016-10-12 13:58:07 +00002836 // eat $ or @
2837 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002838 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002839 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002840 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002841 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002842 return false;
2843 }
2844
Jim Grosbach4b905842013-09-20 23:08:21 +00002845 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002846 return true;
2847
Sean Callanan936b0d32010-01-19 21:44:56 +00002848 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002849
Sean Callanan686ed8d2010-01-19 20:22:31 +00002850 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002851
2852 return false;
2853}
2854
Jim Grosbach4b905842013-09-20 23:08:21 +00002855/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002856/// ::= .equ identifier ',' expression
2857/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002858/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002859bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002860 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002861 if (check(parseIdentifier(Name), "expected identifier") ||
2862 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2863 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2864 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002865}
2866
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002867bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002868 if (check(getTok().isNot(AsmToken::String), "expected string"))
2869 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002870
2871 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002872 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002873 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2874 if (Str[i] != '\\') {
2875 Data += Str[i];
2876 continue;
2877 }
2878
2879 // Recognize escaped characters. Note that this escape semantics currently
2880 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2881 ++i;
2882 if (i == e)
2883 return TokError("unexpected backslash at end of string");
2884
2885 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002886 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002887 // Consume up to three octal characters.
2888 unsigned Value = Str[i] - '0';
2889
Jim Grosbach4b905842013-09-20 23:08:21 +00002890 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002891 ++i;
2892 Value = Value * 8 + (Str[i] - '0');
2893
Jim Grosbach4b905842013-09-20 23:08:21 +00002894 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002895 ++i;
2896 Value = Value * 8 + (Str[i] - '0');
2897 }
2898 }
2899
2900 if (Value > 255)
2901 return TokError("invalid octal escape sequence (out of range)");
2902
Jim Grosbach4b905842013-09-20 23:08:21 +00002903 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002904 continue;
2905 }
2906
2907 // Otherwise recognize individual escapes.
2908 switch (Str[i]) {
2909 default:
2910 // Just reject invalid escape sequences for now.
2911 return TokError("invalid escape sequence (unrecognized character)");
2912
2913 case 'b': Data += '\b'; break;
2914 case 'f': Data += '\f'; break;
2915 case 'n': Data += '\n'; break;
2916 case 'r': Data += '\r'; break;
2917 case 't': Data += '\t'; break;
2918 case '"': Data += '"'; break;
2919 case '\\': Data += '\\'; break;
2920 }
2921 }
2922
Nirav Davea645433c2016-07-18 15:24:03 +00002923 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002924 return false;
2925}
2926
Jim Grosbach4b905842013-09-20 23:08:21 +00002927/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002928/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002929bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002930 auto parseOp = [&]() -> bool {
2931 std::string Data;
2932 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002933 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002934 getStreamer().EmitBytes(Data);
2935 if (ZeroTerminated)
2936 getStreamer().EmitBytes(StringRef("\0", 1));
2937 return false;
2938 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002939
Nirav Dave1a9044b2016-10-24 14:35:29 +00002940 if (parseMany(parseOp))
2941 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002942 return false;
2943}
2944
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002945/// parseDirectiveReloc
2946/// ::= .reloc expression , identifier [ , expression ]
2947bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2948 const MCExpr *Offset;
2949 const MCExpr *Expr = nullptr;
2950
2951 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002952 int64_t OffsetValue;
2953 // We can only deal with constant expressions at the moment.
2954
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002955 if (parseExpression(Offset))
2956 return true;
2957
Nirav Davea645433c2016-07-18 15:24:03 +00002958 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2959 "expression is not a constant value") ||
2960 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2961 parseToken(AsmToken::Comma, "expected comma") ||
2962 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2963 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002964
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002965 SMLoc NameLoc = Lexer.getTok().getLoc();
2966 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002967 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002968
2969 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002970 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002971 SMLoc ExprLoc = Lexer.getLoc();
2972 if (parseExpression(Expr))
2973 return true;
2974
2975 MCValue Value;
2976 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2977 return Error(ExprLoc, "expression must be relocatable");
2978 }
2979
Nirav Davea645433c2016-07-18 15:24:03 +00002980 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002981 "unexpected token in .reloc directive"))
2982 return true;
2983
2984 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2985 return Error(NameLoc, "unknown relocation name");
2986
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002987 return false;
2988}
2989
Jim Grosbach4b905842013-09-20 23:08:21 +00002990/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002991/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002992bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2993 auto parseOp = [&]() -> bool {
2994 const MCExpr *Value;
2995 SMLoc ExprLoc = getLexer().getLoc();
2996 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002997 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002998 // Special case constant expressions to match code generator.
2999 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3000 assert(Size <= 8 && "Invalid size");
3001 uint64_t IntValue = MCE->getValue();
3002 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
3003 return Error(ExprLoc, "out of range literal value");
3004 getStreamer().EmitIntValue(IntValue, Size);
3005 } else
3006 getStreamer().EmitValue(Value, Size, ExprLoc);
3007 return false;
3008 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00003009
Nirav Dave1a9044b2016-10-24 14:35:29 +00003010 if (parseMany(parseOp))
3011 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00003012 return false;
3013}
3014
David Woodhoused6de0d92014-02-01 16:20:59 +00003015/// ParseDirectiveOctaValue
3016/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003017
3018bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3019 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00003020 if (checkForValidSection())
3021 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003022 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
3023 return TokError("unknown token in expression");
3024 SMLoc ExprLoc = getTok().getLoc();
3025 APInt IntValue = getTok().getAPIntVal();
3026 uint64_t hi, lo;
3027 Lex();
3028 if (!IntValue.isIntN(128))
3029 return Error(ExprLoc, "out of range literal value");
3030 if (!IntValue.isIntN(64)) {
3031 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3032 lo = IntValue.getLoBits(64).getZExtValue();
3033 } else {
3034 hi = 0;
3035 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00003036 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003037 if (MAI.isLittleEndian()) {
3038 getStreamer().EmitIntValue(lo, 8);
3039 getStreamer().EmitIntValue(hi, 8);
3040 } else {
3041 getStreamer().EmitIntValue(hi, 8);
3042 getStreamer().EmitIntValue(lo, 8);
3043 }
3044 return false;
3045 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003046
Nirav Dave1a9044b2016-10-24 14:35:29 +00003047 if (parseMany(parseOp))
3048 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003049 return false;
3050}
3051
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003052bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3053 // We don't truly support arithmetic on floating point expressions, so we
3054 // have to manually parse unary prefixes.
3055 bool IsNeg = false;
3056 if (getLexer().is(AsmToken::Minus)) {
3057 Lexer.Lex();
3058 IsNeg = true;
3059 } else if (getLexer().is(AsmToken::Plus))
3060 Lexer.Lex();
3061
3062 if (Lexer.is(AsmToken::Error))
3063 return TokError(Lexer.getErr());
3064 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3065 Lexer.isNot(AsmToken::Identifier))
3066 return TokError("unexpected token in directive");
3067
3068 // Convert to an APFloat.
3069 APFloat Value(Semantics);
3070 StringRef IDVal = getTok().getString();
3071 if (getLexer().is(AsmToken::Identifier)) {
3072 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3073 Value = APFloat::getInf(Semantics);
3074 else if (!IDVal.compare_lower("nan"))
3075 Value = APFloat::getNaN(Semantics, false, ~0);
3076 else
3077 return TokError("invalid floating point literal");
3078 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3079 APFloat::opInvalidOp)
3080 return TokError("invalid floating point literal");
3081 if (IsNeg)
3082 Value.changeSign();
3083
3084 // Consume the numeric token.
3085 Lex();
3086
3087 Res = Value.bitcastToAPInt();
3088
3089 return false;
3090}
3091
Jim Grosbach4b905842013-09-20 23:08:21 +00003092/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003093/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003094bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3095 const fltSemantics &Semantics) {
3096 auto parseOp = [&]() -> bool {
3097 APInt AsInt;
3098 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003099 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003100 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3101 AsInt.getBitWidth() / 8);
3102 return false;
3103 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003104
Nirav Dave1a9044b2016-10-24 14:35:29 +00003105 if (parseMany(parseOp))
3106 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003107 return false;
3108}
3109
Jim Grosbach4b905842013-09-20 23:08:21 +00003110/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003111/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003112bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003113 SMLoc NumBytesLoc = Lexer.getLoc();
3114 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003115 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003116 return true;
3117
Rafael Espindolab91bac62010-10-05 19:42:57 +00003118 int64_t Val = 0;
3119 if (getLexer().is(AsmToken::Comma)) {
3120 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003121 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003122 return true;
3123 }
3124
Nirav Davea645433c2016-07-18 15:24:03 +00003125 if (parseToken(AsmToken::EndOfStatement,
3126 "unexpected token in '.zero' directive"))
3127 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003128 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003129
3130 return false;
3131}
3132
Jim Grosbach4b905842013-09-20 23:08:21 +00003133/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003134/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003135bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003136 SMLoc NumValuesLoc = Lexer.getLoc();
3137 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003138 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003139 return true;
3140
Roman Divackye33098f2013-09-24 17:44:41 +00003141 int64_t FillSize = 1;
3142 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003143
David Majnemer522d3db2014-02-01 07:19:38 +00003144 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003145
Nirav Dave1a9044b2016-10-24 14:35:29 +00003146 if (parseOptionalToken(AsmToken::Comma)) {
3147 SizeLoc = getTok().getLoc();
3148 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003149 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003150 if (parseOptionalToken(AsmToken::Comma)) {
3151 ExprLoc = getTok().getLoc();
3152 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003153 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003154 }
3155 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003156 if (parseToken(AsmToken::EndOfStatement,
3157 "unexpected token in '.fill' directive"))
3158 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003159
David Majnemer522d3db2014-02-01 07:19:38 +00003160 if (FillSize < 0) {
3161 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003162 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003163 }
3164 if (FillSize > 8) {
3165 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3166 FillSize = 8;
3167 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003168
David Majnemer522d3db2014-02-01 07:19:38 +00003169 if (!isUInt<32>(FillExpr) && FillSize > 4)
3170 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3171
Petr Hosek67a94a72016-05-28 05:57:48 +00003172 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003173
3174 return false;
3175}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003176
Jim Grosbach4b905842013-09-20 23:08:21 +00003177/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003178/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003179bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003180 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003181 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003182 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003183 return true;
3184
3185 // Parse optional fill expression.
3186 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003187 if (parseOptionalToken(AsmToken::Comma))
3188 if (parseAbsoluteExpression(FillExpr))
3189 return addErrorSuffix(" in '.org' directive");
3190 if (parseToken(AsmToken::EndOfStatement))
3191 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003192
Oliver Stannard268f42f2016-12-14 10:43:58 +00003193 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003194 return false;
3195}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003196
Jim Grosbach4b905842013-09-20 23:08:21 +00003197/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003198/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003199bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003200 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003201 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003202 SMLoc MaxBytesLoc;
3203 bool HasFillExpr = false;
3204 int64_t FillExpr = 0;
3205 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003206
3207 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003208 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003209 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003210 if (parseOptionalToken(AsmToken::Comma)) {
3211 // The fill expression can be omitted while specifying a maximum number of
3212 // alignment bytes, e.g:
3213 // .align 3,,4
3214 if (getTok().isNot(AsmToken::Comma)) {
3215 HasFillExpr = true;
3216 if (parseAbsoluteExpression(FillExpr))
3217 return true;
3218 }
3219 if (parseOptionalToken(AsmToken::Comma))
3220 if (parseTokenLoc(MaxBytesLoc) ||
3221 parseAbsoluteExpression(MaxBytesToFill))
3222 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003223 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003224 return parseToken(AsmToken::EndOfStatement);
3225 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003226
Coby Tayreed483a102017-08-02 17:36:10 +00003227 if (checkForValidSection())
3228 return addErrorSuffix(" in directive");
3229 // Ignore empty '.p2align' directives for GNU-as compatibility
3230 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3231 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3232 return parseToken(AsmToken::EndOfStatement);
3233 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003234 if (parseAlign())
3235 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003236
Nirav Dave2364748a2016-09-16 18:30:20 +00003237 // Always emit an alignment here even if we thrown an error.
3238 bool ReturnVal = false;
3239
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003240 // Compute alignment in bytes.
3241 if (IsPow2) {
3242 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003243 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003244 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003245 Alignment = 31;
3246 }
3247
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003248 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003249 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003250 // Reject alignments that aren't either a power of two or zero,
3251 // for gas compatibility. Alignment of zero is silently rounded
3252 // up to one.
3253 if (Alignment == 0)
3254 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003255 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003256 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003257 }
3258
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003259 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003260 if (MaxBytesLoc.isValid()) {
3261 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003262 ReturnVal |= Error(MaxBytesLoc,
3263 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003264 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003265 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003266 }
3267
3268 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003269 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003270 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003271 MaxBytesToFill = 0;
3272 }
3273 }
3274
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003275 // Check whether we should use optimal code alignment for this .align
3276 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003277 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003278 assert(Section && "must have section to emit alignment");
3279 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003280 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3281 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003282 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003283 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003284 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003285 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3286 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003287 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003288
Nirav Dave2364748a2016-09-16 18:30:20 +00003289 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003290}
3291
Jim Grosbach4b905842013-09-20 23:08:21 +00003292/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003293/// ::= .file [number] filename
3294/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003295bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003296 // FIXME: I'm not sure what this is.
3297 int64_t FileNumber = -1;
3298 SMLoc FileNumberLoc = getLexer().getLoc();
3299 if (getLexer().is(AsmToken::Integer)) {
3300 FileNumber = getTok().getIntVal();
3301 Lex();
3302
3303 if (FileNumber < 1)
3304 return TokError("file number less than one");
3305 }
3306
Nirav Davea645433c2016-07-18 15:24:03 +00003307 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003308
3309 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003310 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003311 if (check(getTok().isNot(AsmToken::String),
3312 "unexpected token in '.file' directive") ||
3313 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003314 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003315
3316 StringRef Directory;
3317 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003318 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003319 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003320 if (check(FileNumber == -1,
3321 "explicit path specified, but no file number") ||
3322 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003323 return true;
3324 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003325 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003326 } else {
3327 Filename = Path;
3328 }
3329
Nirav Davea645433c2016-07-18 15:24:03 +00003330 if (parseToken(AsmToken::EndOfStatement,
3331 "unexpected token in '.file' directive"))
3332 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003333
3334 if (FileNumber == -1)
3335 getStreamer().EmitFileDirective(Filename);
3336 else {
David Blaikie22748082016-05-26 00:22:26 +00003337 // If there is -g option as well as debug info from directive file,
3338 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003339 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003340 getContext().setGenDwarfForAssembly(false);
3341 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003342 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003343 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003344 }
3345
3346 return false;
3347}
3348
Jim Grosbach4b905842013-09-20 23:08:21 +00003349/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003350/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003351bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003352 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003353 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003354 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3355 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003356 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003357 // FIXME: Do something with the .line.
3358 }
Nirav Davea645433c2016-07-18 15:24:03 +00003359 if (parseToken(AsmToken::EndOfStatement,
3360 "unexpected token in '.line' directive"))
3361 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003362
3363 return false;
3364}
3365
Jim Grosbach4b905842013-09-20 23:08:21 +00003366/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003367/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3368/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3369/// The first number is a file number, must have been previously assigned with
3370/// a .file directive, the second number is the line number and optionally the
3371/// third number is a column position (zero if not specified). The remaining
3372/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003373bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003374 int64_t FileNumber = 0, LineNumber = 0;
3375 SMLoc Loc = getTok().getLoc();
3376 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3377 check(FileNumber < 1, Loc,
3378 "file number less than one in '.loc' directive") ||
3379 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3380 "unassigned file number in '.loc' directive"))
3381 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003382
Nirav Davea645433c2016-07-18 15:24:03 +00003383 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003384 if (getLexer().is(AsmToken::Integer)) {
3385 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003386 if (LineNumber < 0)
3387 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003388 Lex();
3389 }
3390
3391 int64_t ColumnPos = 0;
3392 if (getLexer().is(AsmToken::Integer)) {
3393 ColumnPos = getTok().getIntVal();
3394 if (ColumnPos < 0)
3395 return TokError("column position less than zero in '.loc' directive");
3396 Lex();
3397 }
3398
3399 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3400 unsigned Isa = 0;
3401 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003402
Nirav Dave1a9044b2016-10-24 14:35:29 +00003403 auto parseLocOp = [&]() -> bool {
3404 StringRef Name;
3405 SMLoc Loc = getTok().getLoc();
3406 if (parseIdentifier(Name))
3407 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003408
Nirav Dave1a9044b2016-10-24 14:35:29 +00003409 if (Name == "basic_block")
3410 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3411 else if (Name == "prologue_end")
3412 Flags |= DWARF2_FLAG_PROLOGUE_END;
3413 else if (Name == "epilogue_begin")
3414 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
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 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3422 int Value = MCE->getValue();
3423 if (Value == 0)
3424 Flags &= ~DWARF2_FLAG_IS_STMT;
3425 else if (Value == 1)
3426 Flags |= DWARF2_FLAG_IS_STMT;
3427 else
3428 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003429 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003430 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003431 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003432 } else if (Name == "isa") {
3433 Loc = getTok().getLoc();
3434 const MCExpr *Value;
3435 if (parseExpression(Value))
3436 return true;
3437 // The expression must be a constant greater or equal to 0.
3438 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3439 int Value = MCE->getValue();
3440 if (Value < 0)
3441 return Error(Loc, "isa number less than zero");
3442 Isa = Value;
3443 } else {
3444 return Error(Loc, "isa number not a constant value");
3445 }
3446 } else if (Name == "discriminator") {
3447 if (parseAbsoluteExpression(Discriminator))
3448 return true;
3449 } else {
3450 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003451 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003452 return false;
3453 };
3454
Nirav Davee2369aa2016-10-26 17:28:58 +00003455 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003456 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003457
3458 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3459 Isa, Discriminator, StringRef());
3460
3461 return false;
3462}
3463
Jim Grosbach4b905842013-09-20 23:08:21 +00003464/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003465/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003466bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003467 return TokError("unsupported directive '.stabs'");
3468}
3469
Reid Kleckner2214ed82016-01-29 00:49:42 +00003470/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003471/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003472bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003473 SMLoc FileNumberLoc = getTok().getLoc();
3474 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003475 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003476 std::string Checksum;
3477 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003478
3479 if (parseIntToken(FileNumber,
3480 "expected file number in '.cv_file' directive") ||
3481 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3482 check(getTok().isNot(AsmToken::String),
3483 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003484 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003485 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003486 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3487 if (check(getTok().isNot(AsmToken::String),
3488 "unexpected token in '.cv_file' directive") ||
3489 parseEscapedString(Checksum) ||
3490 parseIntToken(ChecksumKind,
3491 "expected checksum kind in '.cv_file' directive") ||
3492 parseToken(AsmToken::EndOfStatement,
3493 "unexpected token in '.cv_file' directive"))
3494 return true;
3495 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003496
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003497 Checksum = fromHex(Checksum);
3498 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3499 memcpy(CKMem, Checksum.data(), Checksum.size());
3500 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3501 Checksum.size());
3502
3503 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3504 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003505 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003506
3507 return false;
3508}
3509
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003510bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3511 StringRef DirectiveName) {
3512 SMLoc Loc;
3513 return parseTokenLoc(Loc) ||
3514 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3515 "' directive") ||
3516 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3517 "expected function id within range [0, UINT_MAX)");
3518}
3519
3520bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3521 SMLoc Loc;
3522 return parseTokenLoc(Loc) ||
3523 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3524 "' directive") ||
3525 check(FileNumber < 1, Loc, "file number less than one in '" +
3526 DirectiveName + "' directive") ||
3527 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3528 "unassigned file number in '" + DirectiveName + "' directive");
3529}
3530
3531/// parseDirectiveCVFuncId
3532/// ::= .cv_func_id FunctionId
3533///
3534/// Introduces a function ID that can be used with .cv_loc.
3535bool AsmParser::parseDirectiveCVFuncId() {
3536 SMLoc FunctionIdLoc = getTok().getLoc();
3537 int64_t FunctionId;
3538
3539 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3540 parseToken(AsmToken::EndOfStatement,
3541 "unexpected token in '.cv_func_id' directive"))
3542 return true;
3543
3544 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003545 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003546
3547 return false;
3548}
3549
3550/// parseDirectiveCVInlineSiteId
3551/// ::= .cv_inline_site_id FunctionId
3552/// "within" IAFunc
3553/// "inlined_at" IAFile IALine [IACol]
3554///
3555/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3556/// at" source location information for use in the line table of the caller,
3557/// whether the caller is a real function or another inlined call site.
3558bool AsmParser::parseDirectiveCVInlineSiteId() {
3559 SMLoc FunctionIdLoc = getTok().getLoc();
3560 int64_t FunctionId;
3561 int64_t IAFunc;
3562 int64_t IAFile;
3563 int64_t IALine;
3564 int64_t IACol = 0;
3565
3566 // FunctionId
3567 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3568 return true;
3569
3570 // "within"
3571 if (check((getLexer().isNot(AsmToken::Identifier) ||
3572 getTok().getIdentifier() != "within"),
3573 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3574 return true;
3575 Lex();
3576
3577 // IAFunc
3578 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3579 return true;
3580
3581 // "inlined_at"
3582 if (check((getLexer().isNot(AsmToken::Identifier) ||
3583 getTok().getIdentifier() != "inlined_at"),
3584 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3585 "directive") )
3586 return true;
3587 Lex();
3588
3589 // IAFile IALine
3590 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3591 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3592 return true;
3593
3594 // [IACol]
3595 if (getLexer().is(AsmToken::Integer)) {
3596 IACol = getTok().getIntVal();
3597 Lex();
3598 }
3599
3600 if (parseToken(AsmToken::EndOfStatement,
3601 "unexpected token in '.cv_inline_site_id' directive"))
3602 return true;
3603
3604 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3605 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003606 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003607
3608 return false;
3609}
3610
Reid Kleckner2214ed82016-01-29 00:49:42 +00003611/// parseDirectiveCVLoc
3612/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3613/// [is_stmt VALUE]
3614/// The first number is a file number, must have been previously assigned with
3615/// a .file directive, the second number is the line number and optionally the
3616/// third number is a column position (zero if not specified). The remaining
3617/// optional items are .loc sub-directives.
3618bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003619 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003620 SMLoc Loc;
3621 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003622 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3623 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003624 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003625
3626 int64_t LineNumber = 0;
3627 if (getLexer().is(AsmToken::Integer)) {
3628 LineNumber = getTok().getIntVal();
3629 if (LineNumber < 0)
3630 return TokError("line number less than zero in '.cv_loc' directive");
3631 Lex();
3632 }
3633
3634 int64_t ColumnPos = 0;
3635 if (getLexer().is(AsmToken::Integer)) {
3636 ColumnPos = getTok().getIntVal();
3637 if (ColumnPos < 0)
3638 return TokError("column position less than zero in '.cv_loc' directive");
3639 Lex();
3640 }
3641
3642 bool PrologueEnd = false;
3643 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003644
3645 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003646 StringRef Name;
3647 SMLoc Loc = getTok().getLoc();
3648 if (parseIdentifier(Name))
3649 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003650 if (Name == "prologue_end")
3651 PrologueEnd = true;
3652 else if (Name == "is_stmt") {
3653 Loc = getTok().getLoc();
3654 const MCExpr *Value;
3655 if (parseExpression(Value))
3656 return true;
3657 // The expression must be the constant 0 or 1.
3658 IsStmt = ~0ULL;
3659 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3660 IsStmt = MCE->getValue();
3661
3662 if (IsStmt > 1)
3663 return Error(Loc, "is_stmt value not 0 or 1");
3664 } else {
3665 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3666 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003667 return false;
3668 };
3669
3670 if (parseMany(parseOp, false /*hasComma*/))
3671 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003672
3673 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003674 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3675 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003676 return false;
3677}
3678
3679/// parseDirectiveCVLinetable
3680/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3681bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003682 int64_t FunctionId;
3683 StringRef FnStartName, FnEndName;
3684 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003685 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003686 parseToken(AsmToken::Comma,
3687 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003688 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3689 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003690 parseToken(AsmToken::Comma,
3691 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003692 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3693 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003694 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003695
3696 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3697 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3698
3699 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3700 return false;
3701}
3702
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003703/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003704/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003705bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003706 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3707 StringRef FnStartName, FnEndName;
3708 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003709 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003710 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003711 parseIntToken(
3712 SourceFileId,
3713 "expected SourceField in '.cv_inline_linetable' directive") ||
3714 check(SourceFileId <= 0, Loc,
3715 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003716 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003717 parseIntToken(
3718 SourceLineNum,
3719 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3720 check(SourceLineNum < 0, Loc,
3721 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003722 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3723 "expected identifier in directive") ||
3724 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3725 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003726 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003727
Nirav Davea645433c2016-07-18 15:24:03 +00003728 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3729 return true;
3730
3731 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3732 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003733 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3734 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003735 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003736 return false;
3737}
3738
David Majnemer408b5e62016-02-05 01:55:49 +00003739/// parseDirectiveCVDefRange
3740/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3741bool AsmParser::parseDirectiveCVDefRange() {
3742 SMLoc Loc;
3743 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3744 while (getLexer().is(AsmToken::Identifier)) {
3745 Loc = getLexer().getLoc();
3746 StringRef GapStartName;
3747 if (parseIdentifier(GapStartName))
3748 return Error(Loc, "expected identifier in directive");
3749 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3750
3751 Loc = getLexer().getLoc();
3752 StringRef GapEndName;
3753 if (parseIdentifier(GapEndName))
3754 return Error(Loc, "expected identifier in directive");
3755 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3756
3757 Ranges.push_back({GapStartSym, GapEndSym});
3758 }
3759
David Majnemer408b5e62016-02-05 01:55:49 +00003760 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003761 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3762 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003763 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003764
3765 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3766 return false;
3767}
3768
Reid Kleckner2214ed82016-01-29 00:49:42 +00003769/// parseDirectiveCVStringTable
3770/// ::= .cv_stringtable
3771bool AsmParser::parseDirectiveCVStringTable() {
3772 getStreamer().EmitCVStringTableDirective();
3773 return false;
3774}
3775
3776/// parseDirectiveCVFileChecksums
3777/// ::= .cv_filechecksums
3778bool AsmParser::parseDirectiveCVFileChecksums() {
3779 getStreamer().EmitCVFileChecksumsDirective();
3780 return false;
3781}
3782
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003783/// parseDirectiveCVFileChecksumOffset
3784/// ::= .cv_filechecksumoffset fileno
3785bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3786 int64_t FileNo;
3787 if (parseIntToken(FileNo, "expected identifier in directive"))
3788 return true;
3789 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3790 return true;
3791 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3792 return false;
3793}
3794
Jim Grosbach4b905842013-09-20 23:08:21 +00003795/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003796/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003797bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003798 StringRef Name;
3799 bool EH = false;
3800 bool Debug = false;
3801
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003802 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003803 return TokError("Expected an identifier");
3804
3805 if (Name == ".eh_frame")
3806 EH = true;
3807 else if (Name == ".debug_frame")
3808 Debug = true;
3809
3810 if (getLexer().is(AsmToken::Comma)) {
3811 Lex();
3812
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003813 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003814 return TokError("Expected an identifier");
3815
3816 if (Name == ".eh_frame")
3817 EH = true;
3818 else if (Name == ".debug_frame")
3819 Debug = true;
3820 }
3821
3822 getStreamer().EmitCFISections(EH, Debug);
3823 return false;
3824}
3825
Jim Grosbach4b905842013-09-20 23:08:21 +00003826/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003827/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003828bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003829 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003830 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3831 if (check(parseIdentifier(Simple) || Simple != "simple",
3832 "unexpected token") ||
3833 parseToken(AsmToken::EndOfStatement))
3834 return addErrorSuffix(" in '.cfi_startproc' directive");
3835 }
Nirav Davea645433c2016-07-18 15:24:03 +00003836
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003837 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003838 return false;
3839}
3840
Jim Grosbach4b905842013-09-20 23:08:21 +00003841/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003842/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003843bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003844 getStreamer().EmitCFIEndProc();
3845 return false;
3846}
3847
Jim Grosbach4b905842013-09-20 23:08:21 +00003848/// \brief parse register name or number.
3849bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003850 SMLoc DirectiveLoc) {
3851 unsigned RegNo;
3852
3853 if (getLexer().isNot(AsmToken::Integer)) {
3854 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3855 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003856 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003857 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003858 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003859
3860 return false;
3861}
3862
Jim Grosbach4b905842013-09-20 23:08:21 +00003863/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003864/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003865bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003866 int64_t Register = 0, Offset = 0;
3867 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3868 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3869 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003870 return true;
3871
3872 getStreamer().EmitCFIDefCfa(Register, Offset);
3873 return false;
3874}
3875
Jim Grosbach4b905842013-09-20 23:08:21 +00003876/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003877/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003878bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003879 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003880 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003881 return true;
3882
3883 getStreamer().EmitCFIDefCfaOffset(Offset);
3884 return false;
3885}
3886
Jim Grosbach4b905842013-09-20 23:08:21 +00003887/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003888/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003889bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003890 int64_t Register1 = 0, Register2 = 0;
3891 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3892 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3893 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003894 return true;
3895
3896 getStreamer().EmitCFIRegister(Register1, Register2);
3897 return false;
3898}
3899
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003900/// parseDirectiveCFIWindowSave
3901/// ::= .cfi_window_save
3902bool AsmParser::parseDirectiveCFIWindowSave() {
3903 getStreamer().EmitCFIWindowSave();
3904 return false;
3905}
3906
Jim Grosbach4b905842013-09-20 23:08:21 +00003907/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003908/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003909bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003910 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003911 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003912 return true;
3913
3914 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3915 return false;
3916}
3917
Jim Grosbach4b905842013-09-20 23:08:21 +00003918/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003919/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003920bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003921 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003922 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003923 return true;
3924
3925 getStreamer().EmitCFIDefCfaRegister(Register);
3926 return false;
3927}
3928
Jim Grosbach4b905842013-09-20 23:08:21 +00003929/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003930/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003931bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003932 int64_t Register = 0;
3933 int64_t Offset = 0;
3934
Nirav Davea645433c2016-07-18 15:24:03 +00003935 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3936 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3937 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003938 return true;
3939
3940 getStreamer().EmitCFIOffset(Register, Offset);
3941 return false;
3942}
3943
Jim Grosbach4b905842013-09-20 23:08:21 +00003944/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003945/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003946bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003947 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003948
Nirav Davea645433c2016-07-18 15:24:03 +00003949 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3950 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3951 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003952 return true;
3953
3954 getStreamer().EmitCFIRelOffset(Register, Offset);
3955 return false;
3956}
3957
3958static bool isValidEncoding(int64_t Encoding) {
3959 if (Encoding & ~0xff)
3960 return false;
3961
3962 if (Encoding == dwarf::DW_EH_PE_omit)
3963 return true;
3964
3965 const unsigned Format = Encoding & 0xf;
3966 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3967 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3968 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3969 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3970 return false;
3971
3972 const unsigned Application = Encoding & 0x70;
3973 if (Application != dwarf::DW_EH_PE_absptr &&
3974 Application != dwarf::DW_EH_PE_pcrel)
3975 return false;
3976
3977 return true;
3978}
3979
Jim Grosbach4b905842013-09-20 23:08:21 +00003980/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003981/// IsPersonality true for cfi_personality, false for cfi_lsda
3982/// ::= .cfi_personality encoding, [symbol_name]
3983/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003984bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003985 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003986 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003987 return true;
3988 if (Encoding == dwarf::DW_EH_PE_omit)
3989 return false;
3990
Eli Bendersky17233942013-01-15 22:59:42 +00003991 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003992 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3993 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3994 check(parseIdentifier(Name), "expected identifier in directive"))
3995 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003996
Jim Grosbach6f482002015-05-18 18:43:14 +00003997 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003998
3999 if (IsPersonality)
4000 getStreamer().EmitCFIPersonality(Sym, Encoding);
4001 else
4002 getStreamer().EmitCFILsda(Sym, Encoding);
4003 return false;
4004}
4005
Jim Grosbach4b905842013-09-20 23:08:21 +00004006/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004007/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004008bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004009 getStreamer().EmitCFIRememberState();
4010 return false;
4011}
4012
Jim Grosbach4b905842013-09-20 23:08:21 +00004013/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004014/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004015bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004016 getStreamer().EmitCFIRestoreState();
4017 return false;
4018}
4019
Jim Grosbach4b905842013-09-20 23:08:21 +00004020/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004021/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004022bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004023 int64_t Register = 0;
4024
Jim Grosbach4b905842013-09-20 23:08:21 +00004025 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004026 return true;
4027
4028 getStreamer().EmitCFISameValue(Register);
4029 return false;
4030}
4031
Jim Grosbach4b905842013-09-20 23:08:21 +00004032/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004033/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004034bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004035 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004036 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004037 return true;
4038
4039 getStreamer().EmitCFIRestore(Register);
4040 return false;
4041}
4042
Jim Grosbach4b905842013-09-20 23:08:21 +00004043/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004044/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004045bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004046 std::string Values;
4047 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004048 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004049 return true;
4050
4051 Values.push_back((uint8_t)CurrValue);
4052
4053 while (getLexer().is(AsmToken::Comma)) {
4054 Lex();
4055
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004056 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004057 return true;
4058
4059 Values.push_back((uint8_t)CurrValue);
4060 }
4061
4062 getStreamer().EmitCFIEscape(Values);
4063 return false;
4064}
4065
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004066/// parseDirectiveCFIReturnColumn
4067/// ::= .cfi_return_column register
4068bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4069 int64_t Register = 0;
4070 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4071 return true;
4072 getStreamer().EmitCFIReturnColumn(Register);
4073 return false;
4074}
4075
Jim Grosbach4b905842013-09-20 23:08:21 +00004076/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004077/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004078bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004079 if (parseToken(AsmToken::EndOfStatement,
4080 "unexpected token in '.cfi_signal_frame'"))
4081 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004082
4083 getStreamer().EmitCFISignalFrame();
4084 return false;
4085}
4086
Jim Grosbach4b905842013-09-20 23:08:21 +00004087/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004088/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004089bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004090 int64_t Register = 0;
4091
Jim Grosbach4b905842013-09-20 23:08:21 +00004092 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004093 return true;
4094
4095 getStreamer().EmitCFIUndefined(Register);
4096 return false;
4097}
4098
Michael Zuckerman56704612017-05-01 13:20:12 +00004099/// parseDirectiveAltmacro
4100/// ::= .altmacro
4101/// ::= .noaltmacro
4102bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4103 if (getLexer().isNot(AsmToken::EndOfStatement))
4104 return TokError("unexpected token in '" + Directive + "' directive");
4105 if (Directive == ".altmacro")
4106 getLexer().SetAltMacroMode(true);
4107 else
4108 getLexer().SetAltMacroMode(false);
4109 return false;
4110}
4111
Jim Grosbach4b905842013-09-20 23:08:21 +00004112/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004113/// ::= .macros_on
4114/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004115bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004116 if (parseToken(AsmToken::EndOfStatement,
4117 "unexpected token in '" + Directive + "' directive"))
4118 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004119
Jim Grosbach4b905842013-09-20 23:08:21 +00004120 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004121 return false;
4122}
4123
Jim Grosbach4b905842013-09-20 23:08:21 +00004124/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004125/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004126bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004127 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004128 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004129 return TokError("expected identifier in '.macro' directive");
4130
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004131 if (getLexer().is(AsmToken::Comma))
4132 Lex();
4133
Eli Bendersky17233942013-01-15 22:59:42 +00004134 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004135 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004136
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004137 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004138 return Error(Lexer.getLoc(),
4139 "Vararg parameter '" + Parameters.back().Name +
4140 "' should be last one in the list of parameters.");
4141
David Majnemer91fc4c22014-01-29 18:57:46 +00004142 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004143 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004144 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004145
Coby Tayreebedaae02017-04-08 20:29:03 +00004146 // Emit an error if two (or more) named parameters share the same name
4147 for (const MCAsmMacroParameter& CurrParam : Parameters)
4148 if (CurrParam.Name.equals(Parameter.Name))
4149 return TokError("macro '" + Name + "' has multiple parameters"
4150 " named '" + Parameter.Name + "'");
4151
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004152 if (Lexer.is(AsmToken::Colon)) {
4153 Lex(); // consume ':'
4154
4155 SMLoc QualLoc;
4156 StringRef Qualifier;
4157
4158 QualLoc = Lexer.getLoc();
4159 if (parseIdentifier(Qualifier))
4160 return Error(QualLoc, "missing parameter qualifier for "
4161 "'" + Parameter.Name + "' in macro '" + Name + "'");
4162
4163 if (Qualifier == "req")
4164 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004165 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004166 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004167 else
4168 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4169 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4170 }
4171
David Majnemer91fc4c22014-01-29 18:57:46 +00004172 if (getLexer().is(AsmToken::Equal)) {
4173 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004174
4175 SMLoc ParamLoc;
4176
4177 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004178 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004179 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004180
4181 if (Parameter.Required)
4182 Warning(ParamLoc, "pointless default value for required parameter "
4183 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004184 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004185
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004186 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004187
4188 if (getLexer().is(AsmToken::Comma))
4189 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004190 }
4191
Nirav Dave1180e6892016-06-02 17:15:05 +00004192 // Eat just the end of statement.
4193 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004194
Nirav Dave1180e6892016-06-02 17:15:05 +00004195 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004196 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004197 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004198 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004199 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004200 // Ignore Lexing errors in macros.
4201 while (Lexer.is(AsmToken::Error)) {
4202 Lexer.Lex();
4203 }
4204
Eli Bendersky17233942013-01-15 22:59:42 +00004205 // Check whether we have reached the end of the file.
4206 if (getLexer().is(AsmToken::Eof))
4207 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4208
4209 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004210 if (getLexer().is(AsmToken::Identifier)) {
4211 if (getTok().getIdentifier() == ".endm" ||
4212 getTok().getIdentifier() == ".endmacro") {
4213 if (MacroDepth == 0) { // Outermost macro.
4214 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004215 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004216 if (getLexer().isNot(AsmToken::EndOfStatement))
4217 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4218 "' directive");
4219 break;
4220 } else {
4221 // Otherwise we just found the end of an inner macro.
4222 --MacroDepth;
4223 }
4224 } else if (getTok().getIdentifier() == ".macro") {
4225 // We allow nested macros. Those aren't instantiated until the outermost
4226 // macro is expanded so just ignore them for now.
4227 ++MacroDepth;
4228 }
Eli Bendersky17233942013-01-15 22:59:42 +00004229 }
4230
4231 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004232 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004233 }
4234
Jim Grosbach4b905842013-09-20 23:08:21 +00004235 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004236 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4237 }
4238
4239 const char *BodyStart = StartToken.getLoc().getPointer();
4240 const char *BodyEnd = EndToken.getLoc().getPointer();
4241 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004242 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004243 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00004244 return false;
4245}
4246
Jim Grosbach4b905842013-09-20 23:08:21 +00004247/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004248///
4249/// With the support added for named parameters there may be code out there that
4250/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004251/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004252/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004253/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004254/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4255/// warning that the positional parameter found in body which have no effect.
4256/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004257/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004258/// intended or change the macro to use the named parameters. It is possible
4259/// this warning will trigger when the none of the named parameters are used
4260/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004261void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004262 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004263 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004264 // If this macro is not defined with named parameters the warning we are
4265 // checking for here doesn't apply.
4266 unsigned NParameters = Parameters.size();
4267 if (NParameters == 0)
4268 return;
4269
4270 bool NamedParametersFound = false;
4271 bool PositionalParametersFound = false;
4272
4273 // Look at the body of the macro for use of both the named parameters and what
4274 // are likely to be positional parameters. This is what expandMacro() is
4275 // doing when it finds the parameters in the body.
4276 while (!Body.empty()) {
4277 // Scan for the next possible parameter.
4278 std::size_t End = Body.size(), Pos = 0;
4279 for (; Pos != End; ++Pos) {
4280 // Check for a substitution or escape.
4281 // This macro is defined with parameters, look for \foo, \bar, etc.
4282 if (Body[Pos] == '\\' && Pos + 1 != End)
4283 break;
4284
4285 // This macro should have parameters, but look for $0, $1, ..., $n too.
4286 if (Body[Pos] != '$' || Pos + 1 == End)
4287 continue;
4288 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004289 if (Next == '$' || Next == 'n' ||
4290 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004291 break;
4292 }
4293
4294 // Check if we reached the end.
4295 if (Pos == End)
4296 break;
4297
4298 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004299 switch (Body[Pos + 1]) {
4300 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004301 case '$':
4302 break;
4303
Jim Grosbach4b905842013-09-20 23:08:21 +00004304 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004305 case 'n':
4306 PositionalParametersFound = true;
4307 break;
4308
Jim Grosbach4b905842013-09-20 23:08:21 +00004309 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004310 default: {
4311 PositionalParametersFound = true;
4312 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004313 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004314 }
4315 Pos += 2;
4316 } else {
4317 unsigned I = Pos + 1;
4318 while (isIdentifierChar(Body[I]) && I + 1 != End)
4319 ++I;
4320
Jim Grosbach4b905842013-09-20 23:08:21 +00004321 const char *Begin = Body.data() + Pos + 1;
4322 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004323 unsigned Index = 0;
4324 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004325 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004326 break;
4327
4328 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004329 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4330 Pos += 3;
4331 else {
4332 Pos = I;
4333 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004334 } else {
4335 NamedParametersFound = true;
4336 Pos += 1 + Argument.size();
4337 }
4338 }
4339 // Update the scan point.
4340 Body = Body.substr(Pos);
4341 }
4342
4343 if (!NamedParametersFound && PositionalParametersFound)
4344 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4345 "used in macro body, possible positional parameter "
4346 "found in body which will have no effect");
4347}
4348
Nico Weber155dccd12014-07-24 17:08:39 +00004349/// parseDirectiveExitMacro
4350/// ::= .exitm
4351bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004352 if (parseToken(AsmToken::EndOfStatement,
4353 "unexpected token in '" + Directive + "' directive"))
4354 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004355
4356 if (!isInsideMacroInstantiation())
4357 return TokError("unexpected '" + Directive + "' in file, "
4358 "no current macro definition");
4359
4360 // Exit all conditionals that are active in the current macro.
4361 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4362 TheCondState = TheCondStack.back();
4363 TheCondStack.pop_back();
4364 }
4365
4366 handleMacroExit();
4367 return false;
4368}
4369
Jim Grosbach4b905842013-09-20 23:08:21 +00004370/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004371/// ::= .endm
4372/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004373bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004374 if (getLexer().isNot(AsmToken::EndOfStatement))
4375 return TokError("unexpected token in '" + Directive + "' directive");
4376
4377 // If we are inside a macro instantiation, terminate the current
4378 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004379 if (isInsideMacroInstantiation()) {
4380 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004381 return false;
4382 }
4383
4384 // Otherwise, this .endmacro is a stray entry in the file; well formed
4385 // .endmacro directives are handled during the macro definition parsing.
4386 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004387 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004388}
4389
Jim Grosbach4b905842013-09-20 23:08:21 +00004390/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004391/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004392bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004393 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004394 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004395 if (parseTokenLoc(Loc) ||
4396 check(parseIdentifier(Name), Loc,
4397 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004398 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004399 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004400 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004401
Nirav Dave1ab71992016-07-18 19:35:21 +00004402 if (!lookupMacro(Name))
4403 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4404
Jim Grosbach4b905842013-09-20 23:08:21 +00004405 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004406 return false;
4407}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004408
Jim Grosbach4b905842013-09-20 23:08:21 +00004409/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004410/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004411bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004412 // Expect a single argument: an expression that evaluates to a constant
4413 // in the inclusive range 0-30.
4414 SMLoc ExprLoc = getLexer().getLoc();
4415 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004416 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004417 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4418 "in '.bundle_align_mode' "
4419 "directive") ||
4420 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4421 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004422 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004423
4424 // Because of AlignSizePow2's verified range we can safely truncate it to
4425 // unsigned.
4426 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4427 return false;
4428}
4429
Jim Grosbach4b905842013-09-20 23:08:21 +00004430/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004431/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004432bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004433 if (checkForValidSection())
4434 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004435 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004436
Nirav Dave1a9044b2016-10-24 14:35:29 +00004437 StringRef Option;
4438 SMLoc Loc = getTok().getLoc();
4439 const char *kInvalidOptionError =
4440 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004441
Nirav Dave1a9044b2016-10-24 14:35:29 +00004442 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004443 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4444 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004445 parseToken(AsmToken::EndOfStatement,
4446 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004447 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004448 AlignToEnd = true;
4449 }
4450
Eli Bendersky802b6282013-01-07 21:51:08 +00004451 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004452 return false;
4453}
4454
Jim Grosbach4b905842013-09-20 23:08:21 +00004455/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004456/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004457bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004458 if (checkForValidSection() ||
4459 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004460 "unexpected token in '.bundle_unlock' directive"))
4461 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004462
4463 getStreamer().EmitBundleUnlock();
4464 return false;
4465}
4466
Jim Grosbach4b905842013-09-20 23:08:21 +00004467/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004468/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004469bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004470 SMLoc NumBytesLoc = Lexer.getLoc();
4471 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004472 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004473 return true;
4474
4475 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004476 if (parseOptionalToken(AsmToken::Comma))
4477 if (parseAbsoluteExpression(FillExpr))
4478 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4479 if (parseToken(AsmToken::EndOfStatement))
4480 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004481
Eli Bendersky17233942013-01-15 22:59:42 +00004482 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004483 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004484
4485 return false;
4486}
4487
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004488/// parseDirectiveDCB
4489/// ::= .dcb.{b, l, w} expression, expression
4490bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004491 SMLoc NumValuesLoc = Lexer.getLoc();
4492 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004493 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004494 return true;
4495
4496 if (NumValues < 0) {
4497 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4498 return false;
4499 }
4500
4501 if (parseToken(AsmToken::Comma,
4502 "unexpected token in '" + Twine(IDVal) + "' directive"))
4503 return true;
4504
4505 const MCExpr *Value;
4506 SMLoc ExprLoc = getLexer().getLoc();
4507 if (parseExpression(Value))
4508 return true;
4509
4510 // Special case constant expressions to match code generator.
4511 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4512 assert(Size <= 8 && "Invalid size");
4513 uint64_t IntValue = MCE->getValue();
4514 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4515 return Error(ExprLoc, "literal value out of range for directive");
4516 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4517 getStreamer().EmitIntValue(IntValue, Size);
4518 } else {
4519 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4520 getStreamer().EmitValue(Value, Size, ExprLoc);
4521 }
4522
4523 if (parseToken(AsmToken::EndOfStatement,
4524 "unexpected token in '" + Twine(IDVal) + "' directive"))
4525 return true;
4526
4527 return false;
4528}
4529
4530/// parseDirectiveRealDCB
4531/// ::= .dcb.{d, s} expression, expression
4532bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004533 SMLoc NumValuesLoc = Lexer.getLoc();
4534 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004535 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004536 return true;
4537
4538 if (NumValues < 0) {
4539 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4540 return false;
4541 }
4542
4543 if (parseToken(AsmToken::Comma,
4544 "unexpected token in '" + Twine(IDVal) + "' directive"))
4545 return true;
4546
4547 APInt AsInt;
4548 if (parseRealValue(Semantics, AsInt))
4549 return true;
4550
4551 if (parseToken(AsmToken::EndOfStatement,
4552 "unexpected token in '" + Twine(IDVal) + "' directive"))
4553 return true;
4554
4555 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4556 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4557 AsInt.getBitWidth() / 8);
4558
4559 return false;
4560}
4561
Petr Hosek85b2f672016-09-23 21:53:36 +00004562/// parseDirectiveDS
4563/// ::= .ds.{b, d, l, p, s, w, x} expression
4564bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004565 SMLoc NumValuesLoc = Lexer.getLoc();
4566 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004567 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004568 return true;
4569
4570 if (NumValues < 0) {
4571 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4572 return false;
4573 }
4574
4575 if (parseToken(AsmToken::EndOfStatement,
4576 "unexpected token in '" + Twine(IDVal) + "' directive"))
4577 return true;
4578
4579 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4580 getStreamer().emitFill(Size, 0);
4581
4582 return false;
4583}
4584
Jim Grosbach4b905842013-09-20 23:08:21 +00004585/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004586/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004587bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004588 if (checkForValidSection())
4589 return true;
4590
Nirav Dave1a9044b2016-10-24 14:35:29 +00004591 auto parseOp = [&]() -> bool {
4592 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004593 if (parseExpression(Value))
4594 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004595 if (Signed)
4596 getStreamer().EmitSLEB128Value(Value);
4597 else
4598 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004599 return false;
4600 };
Eli Bendersky17233942013-01-15 22:59:42 +00004601
Nirav Dave1a9044b2016-10-24 14:35:29 +00004602 if (parseMany(parseOp))
4603 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004604
4605 return false;
4606}
4607
Jim Grosbach4b905842013-09-20 23:08:21 +00004608/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004609/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004610bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004611 auto parseOp = [&]() -> bool {
4612 StringRef Name;
4613 SMLoc Loc = getTok().getLoc();
4614 if (parseIdentifier(Name))
4615 return Error(Loc, "expected identifier");
4616 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004617
Nirav Dave1a9044b2016-10-24 14:35:29 +00004618 // Assembler local symbols don't make any sense here. Complain loudly.
4619 if (Sym->isTemporary())
4620 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004621
Nirav Dave1a9044b2016-10-24 14:35:29 +00004622 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4623 return Error(Loc, "unable to emit symbol attribute");
4624 return false;
4625 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004626
Nirav Dave1a9044b2016-10-24 14:35:29 +00004627 if (parseMany(parseOp))
4628 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004629 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004630}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004631
Jim Grosbach4b905842013-09-20 23:08:21 +00004632/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004633/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004634bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004635 if (checkForValidSection())
4636 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004637
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004638 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004639 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004640 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004641 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004642
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004643 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004644 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004645
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004646 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004647 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004648 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004649
4650 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004651 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004652 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004653 return true;
4654
4655 int64_t Pow2Alignment = 0;
4656 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004657 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004658 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004659 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004660 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004661 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004662
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004663 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4664 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004665 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4666
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004667 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004668 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4669 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004670 if (!isPowerOf2_64(Pow2Alignment))
4671 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4672 Pow2Alignment = Log2_64(Pow2Alignment);
4673 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004674 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004675
Nirav Dave1a9044b2016-10-24 14:35:29 +00004676 if (parseToken(AsmToken::EndOfStatement,
4677 "unexpected token in '.comm' or '.lcomm' directive"))
4678 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004679
Chris Lattner28ad7542009-07-09 17:25:12 +00004680 // NOTE: a size of zero for a .comm should create a undefined symbol
4681 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004682 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004683 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004684 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004685
Eric Christopherbc818852010-05-14 01:38:54 +00004686 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004687 // may internally end up wanting an alignment in bytes.
4688 // FIXME: Diagnose overflow.
4689 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004690 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004691 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004692
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004693 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004694 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004695 return Error(IDLoc, "invalid symbol redefinition");
4696
Chris Lattner28ad7542009-07-09 17:25:12 +00004697 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004698 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004699 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004700 return false;
4701 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004702
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004703 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004704 return false;
4705}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004706
Jim Grosbach4b905842013-09-20 23:08:21 +00004707/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004708/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004709bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004710 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004711 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004712
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004713 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004714 if (parseToken(AsmToken::EndOfStatement,
4715 "unexpected token in '.abort' directive"))
4716 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004717
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004718 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004719 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004720 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004721 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004722 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004723
4724 return false;
4725}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004726
Jim Grosbach4b905842013-09-20 23:08:21 +00004727/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004728/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004729bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004730 // Allow the strings to have escaped octal character sequence.
4731 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004732 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004733
Nirav Davea645433c2016-07-18 15:24:03 +00004734 if (check(getTok().isNot(AsmToken::String),
4735 "expected string in '.include' directive") ||
4736 parseEscapedString(Filename) ||
4737 check(getTok().isNot(AsmToken::EndOfStatement),
4738 "unexpected token in '.include' directive") ||
4739 // Attempt to switch the lexer to the included file before consuming the
4740 // end of statement to avoid losing it when we switch.
4741 check(enterIncludeFile(Filename), IncludeLoc,
4742 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004743 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004744
4745 return false;
4746}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004747
Jim Grosbach4b905842013-09-20 23:08:21 +00004748/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004749/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004750bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004751 // Allow the strings to have escaped octal character sequence.
4752 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004753 SMLoc IncbinLoc = getTok().getLoc();
4754 if (check(getTok().isNot(AsmToken::String),
4755 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004756 parseEscapedString(Filename))
4757 return true;
4758
4759 int64_t Skip = 0;
4760 const MCExpr *Count = nullptr;
4761 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004762 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004763 // The skip expression can be omitted while specifying the count, e.g:
4764 // .incbin "filename",,4
4765 if (getTok().isNot(AsmToken::Comma)) {
4766 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4767 return true;
4768 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004769 if (parseOptionalToken(AsmToken::Comma)) {
4770 CountLoc = getTok().getLoc();
4771 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004772 return true;
4773 }
4774 }
4775
4776 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004777 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004778 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004779
Petr Hosek2f4ac442016-09-23 00:41:06 +00004780 if (check(Skip < 0, SkipLoc, "skip is negative"))
4781 return true;
4782
Nirav Dave1ab71992016-07-18 19:35:21 +00004783 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004784 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004785 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004786 return false;
4787}
4788
Jim Grosbach4b905842013-09-20 23:08:21 +00004789/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004790/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4791bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004792 TheCondStack.push_back(TheCondState);
4793 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004794 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004795 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004796 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004797 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004798 if (parseAbsoluteExpression(ExprValue) ||
4799 parseToken(AsmToken::EndOfStatement,
4800 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004801 return true;
4802
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004803 switch (DirKind) {
4804 default:
4805 llvm_unreachable("unsupported directive");
4806 case DK_IF:
4807 case DK_IFNE:
4808 break;
4809 case DK_IFEQ:
4810 ExprValue = ExprValue == 0;
4811 break;
4812 case DK_IFGE:
4813 ExprValue = ExprValue >= 0;
4814 break;
4815 case DK_IFGT:
4816 ExprValue = ExprValue > 0;
4817 break;
4818 case DK_IFLE:
4819 ExprValue = ExprValue <= 0;
4820 break;
4821 case DK_IFLT:
4822 ExprValue = ExprValue < 0;
4823 break;
4824 }
4825
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004826 TheCondState.CondMet = ExprValue;
4827 TheCondState.Ignore = !TheCondState.CondMet;
4828 }
4829
4830 return false;
4831}
4832
Jim Grosbach4b905842013-09-20 23:08:21 +00004833/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004834/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004835bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004836 TheCondStack.push_back(TheCondState);
4837 TheCondState.TheCond = AsmCond::IfCond;
4838
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004839 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004840 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004841 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004842 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004843
Nirav Davea645433c2016-07-18 15:24:03 +00004844 if (parseToken(AsmToken::EndOfStatement,
4845 "unexpected token in '.ifb' directive"))
4846 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004847
4848 TheCondState.CondMet = ExpectBlank == Str.empty();
4849 TheCondState.Ignore = !TheCondState.CondMet;
4850 }
4851
4852 return false;
4853}
4854
Jim Grosbach4b905842013-09-20 23:08:21 +00004855/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004856/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004857/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004858bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004859 TheCondStack.push_back(TheCondState);
4860 TheCondState.TheCond = AsmCond::IfCond;
4861
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004862 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004863 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004864 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004865 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004866
Nirav Davea645433c2016-07-18 15:24:03 +00004867 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4868 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004869
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004870 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004871
Nirav Davea645433c2016-07-18 15:24:03 +00004872 if (parseToken(AsmToken::EndOfStatement,
4873 "unexpected token in '.ifc' directive"))
4874 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004875
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004876 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004877 TheCondState.Ignore = !TheCondState.CondMet;
4878 }
4879
4880 return false;
4881}
4882
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004883/// parseDirectiveIfeqs
4884/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004885bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004886 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004887 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004888 return TokError("expected string parameter for '.ifeqs' directive");
4889 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004890 }
4891
4892 StringRef String1 = getTok().getStringContents();
4893 Lex();
4894
4895 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004896 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004897 return TokError(
4898 "expected comma after first string for '.ifeqs' directive");
4899 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004900 }
4901
4902 Lex();
4903
4904 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004905 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004906 return TokError("expected string parameter for '.ifeqs' directive");
4907 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004908 }
4909
4910 StringRef String2 = getTok().getStringContents();
4911 Lex();
4912
4913 TheCondStack.push_back(TheCondState);
4914 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004915 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004916 TheCondState.Ignore = !TheCondState.CondMet;
4917
4918 return false;
4919}
4920
Jim Grosbach4b905842013-09-20 23:08:21 +00004921/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004922/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004923bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004924 StringRef Name;
4925 TheCondStack.push_back(TheCondState);
4926 TheCondState.TheCond = AsmCond::IfCond;
4927
4928 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004929 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004930 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004931 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4932 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4933 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004934
Jim Grosbach6f482002015-05-18 18:43:14 +00004935 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004936
4937 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004938 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004939 else
Craig Topper353eda42014-04-24 06:44:33 +00004940 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004941 TheCondState.Ignore = !TheCondState.CondMet;
4942 }
4943
4944 return false;
4945}
4946
Jim Grosbach4b905842013-09-20 23:08:21 +00004947/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004948/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004949bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004950 if (TheCondState.TheCond != AsmCond::IfCond &&
4951 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004952 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4953 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004954 TheCondState.TheCond = AsmCond::ElseIfCond;
4955
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004956 bool LastIgnoreState = false;
4957 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004958 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004959 if (LastIgnoreState || TheCondState.CondMet) {
4960 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004961 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004962 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004963 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004964 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004965 return true;
4966
Nirav Dave1a9044b2016-10-24 14:35:29 +00004967 if (parseToken(AsmToken::EndOfStatement,
4968 "unexpected token in '.elseif' directive"))
4969 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004970
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004971 TheCondState.CondMet = ExprValue;
4972 TheCondState.Ignore = !TheCondState.CondMet;
4973 }
4974
4975 return false;
4976}
4977
Jim Grosbach4b905842013-09-20 23:08:21 +00004978/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004979/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004980bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004981 if (parseToken(AsmToken::EndOfStatement,
4982 "unexpected token in '.else' directive"))
4983 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004984
4985 if (TheCondState.TheCond != AsmCond::IfCond &&
4986 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004987 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4988 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004989 TheCondState.TheCond = AsmCond::ElseCond;
4990 bool LastIgnoreState = false;
4991 if (!TheCondStack.empty())
4992 LastIgnoreState = TheCondStack.back().Ignore;
4993 if (LastIgnoreState || TheCondState.CondMet)
4994 TheCondState.Ignore = true;
4995 else
4996 TheCondState.Ignore = false;
4997
4998 return false;
4999}
5000
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005001/// parseDirectiveEnd
5002/// ::= .end
5003bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005004 if (parseToken(AsmToken::EndOfStatement,
5005 "unexpected token in '.end' directive"))
5006 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005007
5008 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005009 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005010
5011 return false;
5012}
5013
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005014/// parseDirectiveError
5015/// ::= .err
5016/// ::= .error [string]
5017bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5018 if (!TheCondStack.empty()) {
5019 if (TheCondStack.back().Ignore) {
5020 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005021 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005022 }
5023 }
5024
5025 if (!WithMessage)
5026 return Error(L, ".err encountered");
5027
5028 StringRef Message = ".error directive invoked in source file";
5029 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005030 if (Lexer.isNot(AsmToken::String))
5031 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005032
5033 Message = getTok().getStringContents();
5034 Lex();
5035 }
5036
Nirav Dave2364748a2016-09-16 18:30:20 +00005037 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005038}
5039
Nico Weber404012b2014-07-24 16:26:06 +00005040/// parseDirectiveWarning
5041/// ::= .warning [string]
5042bool AsmParser::parseDirectiveWarning(SMLoc L) {
5043 if (!TheCondStack.empty()) {
5044 if (TheCondStack.back().Ignore) {
5045 eatToEndOfStatement();
5046 return false;
5047 }
5048 }
5049
5050 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005051
5052 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005053 if (Lexer.isNot(AsmToken::String))
5054 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005055
5056 Message = getTok().getStringContents();
5057 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005058 if (parseToken(AsmToken::EndOfStatement,
5059 "expected end of statement in '.warning' directive"))
5060 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005061 }
5062
Nirav Dave2364748a2016-09-16 18:30:20 +00005063 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005064}
5065
Jim Grosbach4b905842013-09-20 23:08:21 +00005066/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005067/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005068bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005069 if (parseToken(AsmToken::EndOfStatement,
5070 "unexpected token in '.endif' directive"))
5071 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005072
Jim Grosbach4b905842013-09-20 23:08:21 +00005073 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005074 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5075 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005076 if (!TheCondStack.empty()) {
5077 TheCondState = TheCondStack.back();
5078 TheCondStack.pop_back();
5079 }
5080
5081 return false;
5082}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005083
Eli Bendersky17233942013-01-15 22:59:42 +00005084void AsmParser::initializeDirectiveKindMap() {
5085 DirectiveKindMap[".set"] = DK_SET;
5086 DirectiveKindMap[".equ"] = DK_EQU;
5087 DirectiveKindMap[".equiv"] = DK_EQUIV;
5088 DirectiveKindMap[".ascii"] = DK_ASCII;
5089 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5090 DirectiveKindMap[".string"] = DK_STRING;
5091 DirectiveKindMap[".byte"] = DK_BYTE;
5092 DirectiveKindMap[".short"] = DK_SHORT;
5093 DirectiveKindMap[".value"] = DK_VALUE;
5094 DirectiveKindMap[".2byte"] = DK_2BYTE;
5095 DirectiveKindMap[".long"] = DK_LONG;
5096 DirectiveKindMap[".int"] = DK_INT;
5097 DirectiveKindMap[".4byte"] = DK_4BYTE;
5098 DirectiveKindMap[".quad"] = DK_QUAD;
5099 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005100 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005101 DirectiveKindMap[".single"] = DK_SINGLE;
5102 DirectiveKindMap[".float"] = DK_FLOAT;
5103 DirectiveKindMap[".double"] = DK_DOUBLE;
5104 DirectiveKindMap[".align"] = DK_ALIGN;
5105 DirectiveKindMap[".align32"] = DK_ALIGN32;
5106 DirectiveKindMap[".balign"] = DK_BALIGN;
5107 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5108 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5109 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5110 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5111 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5112 DirectiveKindMap[".org"] = DK_ORG;
5113 DirectiveKindMap[".fill"] = DK_FILL;
5114 DirectiveKindMap[".zero"] = DK_ZERO;
5115 DirectiveKindMap[".extern"] = DK_EXTERN;
5116 DirectiveKindMap[".globl"] = DK_GLOBL;
5117 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005118 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5119 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5120 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5121 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5122 DirectiveKindMap[".reference"] = DK_REFERENCE;
5123 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5124 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5125 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5126 DirectiveKindMap[".comm"] = DK_COMM;
5127 DirectiveKindMap[".common"] = DK_COMMON;
5128 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5129 DirectiveKindMap[".abort"] = DK_ABORT;
5130 DirectiveKindMap[".include"] = DK_INCLUDE;
5131 DirectiveKindMap[".incbin"] = DK_INCBIN;
5132 DirectiveKindMap[".code16"] = DK_CODE16;
5133 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5134 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005135 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005136 DirectiveKindMap[".irp"] = DK_IRP;
5137 DirectiveKindMap[".irpc"] = DK_IRPC;
5138 DirectiveKindMap[".endr"] = DK_ENDR;
5139 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5140 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5141 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5142 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005143 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5144 DirectiveKindMap[".ifge"] = DK_IFGE;
5145 DirectiveKindMap[".ifgt"] = DK_IFGT;
5146 DirectiveKindMap[".ifle"] = DK_IFLE;
5147 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005148 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005149 DirectiveKindMap[".ifb"] = DK_IFB;
5150 DirectiveKindMap[".ifnb"] = DK_IFNB;
5151 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005152 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005153 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005154 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005155 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5156 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5157 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5158 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5159 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005160 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005161 DirectiveKindMap[".endif"] = DK_ENDIF;
5162 DirectiveKindMap[".skip"] = DK_SKIP;
5163 DirectiveKindMap[".space"] = DK_SPACE;
5164 DirectiveKindMap[".file"] = DK_FILE;
5165 DirectiveKindMap[".line"] = DK_LINE;
5166 DirectiveKindMap[".loc"] = DK_LOC;
5167 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005168 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005169 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005170 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5171 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005172 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005173 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005174 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005175 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5176 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005177 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Eli Bendersky17233942013-01-15 22:59:42 +00005178 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5179 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5180 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5181 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5182 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5183 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5184 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5185 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5186 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5187 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5188 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5189 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5190 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5191 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5192 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5193 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5194 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5195 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005196 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005197 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5198 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5199 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005200 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005201 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5202 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5203 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005204 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005205 DirectiveKindMap[".endm"] = DK_ENDM;
5206 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5207 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005208 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005209 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005210 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005211 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5212 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005213 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005214 DirectiveKindMap[".dc"] = DK_DC;
5215 DirectiveKindMap[".dc.a"] = DK_DC_A;
5216 DirectiveKindMap[".dc.b"] = DK_DC_B;
5217 DirectiveKindMap[".dc.d"] = DK_DC_D;
5218 DirectiveKindMap[".dc.l"] = DK_DC_L;
5219 DirectiveKindMap[".dc.s"] = DK_DC_S;
5220 DirectiveKindMap[".dc.w"] = DK_DC_W;
5221 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005222 DirectiveKindMap[".dcb"] = DK_DCB;
5223 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5224 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5225 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5226 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5227 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5228 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005229 DirectiveKindMap[".ds"] = DK_DS;
5230 DirectiveKindMap[".ds.b"] = DK_DS_B;
5231 DirectiveKindMap[".ds.d"] = DK_DS_D;
5232 DirectiveKindMap[".ds.l"] = DK_DS_L;
5233 DirectiveKindMap[".ds.p"] = DK_DS_P;
5234 DirectiveKindMap[".ds.s"] = DK_DS_S;
5235 DirectiveKindMap[".ds.w"] = DK_DS_W;
5236 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005237 DirectiveKindMap[".print"] = DK_PRINT;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005238}
5239
Jim Grosbach4b905842013-09-20 23:08:21 +00005240MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005241 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005242
Rafael Espindola34b9c512012-06-03 23:57:14 +00005243 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005244 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005245 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005246 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005247 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005248 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005249 }
5250
Rafael Espindola34b9c512012-06-03 23:57:14 +00005251 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005252 (getTok().getIdentifier() == ".rept" ||
5253 getTok().getIdentifier() == ".irp" ||
5254 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005255 ++NestLevel;
5256 }
5257
5258 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005259 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005260 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005261 EndToken = getTok();
5262 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005263 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005264 printError(getTok().getLoc(),
5265 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005266 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005267 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005268 break;
5269 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005270 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005271 }
5272
Rafael Espindola34b9c512012-06-03 23:57:14 +00005273 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005274 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005275 }
5276
5277 const char *BodyStart = StartToken.getLoc().getPointer();
5278 const char *BodyEnd = EndToken.getLoc().getPointer();
5279 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5280
Rafael Espindola34b9c512012-06-03 23:57:14 +00005281 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005282 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005283 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005284}
5285
Jim Grosbach4b905842013-09-20 23:08:21 +00005286void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005287 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005288 OS << ".endr\n";
5289
Rafael Espindola3560ff22014-08-27 20:03:13 +00005290 std::unique_ptr<MemoryBuffer> Instantiation =
5291 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005292
Rafael Espindola34b9c512012-06-03 23:57:14 +00005293 // Create the macro instantiation object and add to the current macro
5294 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005295 MacroInstantiation *MI = new MacroInstantiation(
5296 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005297 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005298
Rafael Espindola34b9c512012-06-03 23:57:14 +00005299 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005300 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005301 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005302 Lex();
5303}
5304
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005305/// parseDirectiveRept
5306/// ::= .rep | .rept count
5307bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005308 const MCExpr *CountExpr;
5309 SMLoc CountLoc = getTok().getLoc();
5310 if (parseExpression(CountExpr))
5311 return true;
5312
Rafael Espindola34b9c512012-06-03 23:57:14 +00005313 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005314 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005315 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5316 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005317
Nirav Davea645433c2016-07-18 15:24:03 +00005318 if (check(Count < 0, CountLoc, "Count is negative") ||
5319 parseToken(AsmToken::EndOfStatement,
5320 "unexpected token in '" + Dir + "' directive"))
5321 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005322
5323 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005324 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005325 if (!M)
5326 return true;
5327
5328 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5329 // to hold the macro body with substitutions.
5330 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005331 raw_svector_ostream OS(Buf);
5332 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005333 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5334 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005335 return true;
5336 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005337 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005338
5339 return false;
5340}
5341
Jim Grosbach4b905842013-09-20 23:08:21 +00005342/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005343/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005344bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005345 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005346 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005347 if (check(parseIdentifier(Parameter.Name),
5348 "expected identifier in '.irp' directive") ||
5349 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5350 parseMacroArguments(nullptr, A) ||
5351 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005352 return true;
5353
Rafael Espindola768b41c2012-06-15 14:02:34 +00005354 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005355 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005356 if (!M)
5357 return true;
5358
5359 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5360 // to hold the macro body with substitutions.
5361 SmallString<256> Buf;
5362 raw_svector_ostream OS(Buf);
5363
Craig Topper84008482015-10-10 05:38:14 +00005364 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005365 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5366 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005367 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005368 return true;
5369 }
5370
Jim Grosbach4b905842013-09-20 23:08:21 +00005371 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005372
5373 return false;
5374}
5375
Jim Grosbach4b905842013-09-20 23:08:21 +00005376/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005377/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005378bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005379 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005380 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005381
5382 if (check(parseIdentifier(Parameter.Name),
5383 "expected identifier in '.irpc' directive") ||
5384 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5385 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005386 return true;
5387
5388 if (A.size() != 1 || A.front().size() != 1)
5389 return TokError("unexpected token in '.irpc' directive");
5390
5391 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005392 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5393 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005394
5395 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005396 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005397 if (!M)
5398 return true;
5399
5400 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5401 // to hold the macro body with substitutions.
5402 SmallString<256> Buf;
5403 raw_svector_ostream OS(Buf);
5404
5405 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005406 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005407 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005408 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005409
Toma Tabacu217116e2015-04-27 10:50:29 +00005410 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5411 // This is undocumented, but GAS seems to support it.
5412 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005413 return true;
5414 }
5415
Jim Grosbach4b905842013-09-20 23:08:21 +00005416 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005417
5418 return false;
5419}
5420
Jim Grosbach4b905842013-09-20 23:08:21 +00005421bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005422 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005423 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005424
5425 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005426 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005427 assert(getLexer().is(AsmToken::EndOfStatement));
5428
Jim Grosbach4b905842013-09-20 23:08:21 +00005429 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005430 return false;
5431}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005432
Jim Grosbach4b905842013-09-20 23:08:21 +00005433bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005434 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005435 const MCExpr *Value;
5436 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005437 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005438 return true;
5439 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5440 if (!MCE)
5441 return Error(ExprLoc, "unexpected expression in _emit");
5442 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005443 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005444 return Error(ExprLoc, "literal value out of range for directive");
5445
Craig Topper7d5b2312015-10-10 05:25:02 +00005446 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005447 return false;
5448}
5449
Jim Grosbach4b905842013-09-20 23:08:21 +00005450bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005451 const MCExpr *Value;
5452 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005453 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005454 return true;
5455 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5456 if (!MCE)
5457 return Error(ExprLoc, "unexpected expression in align");
5458 uint64_t IntValue = MCE->getValue();
5459 if (!isPowerOf2_64(IntValue))
5460 return Error(ExprLoc, "literal value not a power of two greater then zero");
5461
Craig Topper7d5b2312015-10-10 05:25:02 +00005462 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005463 return false;
5464}
5465
Coby Tayree01e53202017-10-02 14:36:31 +00005466bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5467 const AsmToken StrTok = getTok();
5468 Lex();
5469 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5470 return Error(DirectiveLoc, "expected double quoted string after .print");
5471 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5472 return true;
5473 llvm::outs() << StrTok.getStringContents() << '\n';
5474 return false;
5475}
5476
Chad Rosierf43fcf52013-02-13 21:27:17 +00005477// We are comparing pointers, but the pointers are relative to a single string.
5478// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005479static int rewritesSort(const AsmRewrite *AsmRewriteA,
5480 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005481 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5482 return -1;
5483 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5484 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005485
Chad Rosierfce4fab2013-04-08 17:43:47 +00005486 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5487 // rewrite to the same location. Make sure the SizeDirective rewrite is
5488 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5489 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005490 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5491 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005492 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005493
Jim Grosbach4b905842013-09-20 23:08:21 +00005494 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5495 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005496 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005497 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005498}
5499
Jim Grosbach4b905842013-09-20 23:08:21 +00005500bool AsmParser::parseMSInlineAsm(
5501 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005502 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005503 SmallVectorImpl<std::string> &Constraints,
5504 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5505 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005506 SmallVector<void *, 4> InputDecls;
5507 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005508 SmallVector<bool, 4> InputDeclsAddressOf;
5509 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005510 SmallVector<std::string, 4> InputConstraints;
5511 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005512 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005513
Benjamin Kramer1a136112013-02-15 20:37:21 +00005514 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005515
5516 // Prime the lexer.
5517 Lex();
5518
5519 // While we have input, parse each statement.
5520 unsigned InputIdx = 0;
5521 unsigned OutputIdx = 0;
5522 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005523 // Parse curly braces marking block start/end
5524 if (parseCurlyBlockScope(AsmStrRewrites))
5525 continue;
5526
Eli Friedman0f4871d2012-10-22 23:58:19 +00005527 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005528 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005529
Nirav Dave2364748a2016-09-16 18:30:20 +00005530 if (StatementErr || Info.ParseError) {
5531 // Emit pending errors if any exist.
5532 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005533 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005534 }
5535
5536 // No pending error should exist here.
5537 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005538
Benjamin Kramer1a136112013-02-15 20:37:21 +00005539 if (Info.Opcode == ~0U)
5540 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005541
Benjamin Kramer1a136112013-02-15 20:37:21 +00005542 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005543
Benjamin Kramer1a136112013-02-15 20:37:21 +00005544 // Build the list of clobbers, outputs and inputs.
5545 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005546 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005547
Benjamin Kramer1a136112013-02-15 20:37:21 +00005548 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005549 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005550 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005551
Benjamin Kramer1a136112013-02-15 20:37:21 +00005552 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005553 if (Operand.isReg() && !Operand.needAddressOf() &&
5554 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005555 unsigned NumDefs = Desc.getNumDefs();
5556 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005557 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5558 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005559 continue;
5560 }
5561
5562 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005563 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005564 if (SymName.empty())
5565 continue;
5566
David Blaikie960ea3f2014-06-08 16:18:35 +00005567 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005568 if (!OpDecl)
5569 continue;
5570
5571 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005572 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005573 if (isOutput) {
5574 ++InputIdx;
5575 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005576 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005577 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005578 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005579 } else {
5580 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005581 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5582 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005583 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005584 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005585 }
Reid Kleckneree088972013-12-10 18:27:32 +00005586
5587 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005588 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5589 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005590 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005591 }
5592
5593 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005594 NumOutputs = OutputDecls.size();
5595 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005596
5597 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005598 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5599 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5600 ClobberRegs.end());
5601 Clobbers.assign(ClobberRegs.size(), std::string());
5602 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5603 raw_string_ostream OS(Clobbers[I]);
5604 IP->printRegName(OS, ClobberRegs[I]);
5605 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005606
5607 // Merge the various outputs and inputs. Output are expected first.
5608 if (NumOutputs || NumInputs) {
5609 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005610 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005611 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005612 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005613 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005614 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005615 }
5616 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005617 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005618 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005619 }
5620 }
5621
5622 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005623 std::string AsmStringIR;
5624 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005625 StringRef ASMString =
5626 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5627 const char *AsmStart = ASMString.begin();
5628 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005629 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005630 for (const AsmRewrite &AR : AsmStrRewrites) {
5631 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005632
David Majnemer8114c1a2014-06-23 02:17:16 +00005633 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005634 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005635
Chad Rosier120eefd2013-03-19 17:32:17 +00005636 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005637 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005638 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005639
Chad Rosier37e755c2012-10-23 17:43:43 +00005640 // Skip the original expression.
5641 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005642 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005643 continue;
5644 }
5645
Chad Rosierff10ed12013-04-12 16:26:42 +00005646 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005647 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005648 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005649 default:
5650 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005651 case AOK_IntelExpr:
5652 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5653 if (AR.IntelExp.NeedBracs)
5654 OS << "[";
5655 if (AR.IntelExp.hasBaseReg())
5656 OS << AR.IntelExp.BaseReg;
5657 if (AR.IntelExp.hasIndexReg())
5658 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5659 << AR.IntelExp.IndexReg;
5660 if (AR.IntelExp.Scale > 1)
5661 OS << " * $$" << AR.IntelExp.Scale;
5662 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5663 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5664 if (AR.IntelExp.NeedBracs)
5665 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005666 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005667 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005668 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005669 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005670 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005671 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005672 break;
5673 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005674 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005675 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005676 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005677 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005678 default: break;
5679 case 8: OS << "byte ptr "; break;
5680 case 16: OS << "word ptr "; break;
5681 case 32: OS << "dword ptr "; break;
5682 case 64: OS << "qword ptr "; break;
5683 case 80: OS << "xword ptr "; break;
5684 case 128: OS << "xmmword ptr "; break;
5685 case 256: OS << "ymmword ptr "; break;
5686 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005687 break;
5688 case AOK_Emit:
5689 OS << ".byte";
5690 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005691 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005692 // MS alignment directives are measured in bytes. If the native assembler
5693 // measures alignment in bytes, we can pass it straight through.
5694 OS << ".align";
5695 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5696 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005697
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005698 // Alignment is in log2 form, so print that instead and skip the original
5699 // immediate.
5700 unsigned Val = AR.Val;
5701 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005702 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005703 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5704 break;
5705 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005706 case AOK_EVEN:
5707 OS << ".even";
5708 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005709 case AOK_EndOfStatement:
5710 OS << "\n\t";
5711 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005712 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005713
Chad Rosier8bce6642012-10-18 15:49:34 +00005714 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005715 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005716 }
5717
5718 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005719 if (AsmStart != AsmEnd)
5720 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005721
5722 AsmString = OS.str();
5723 return false;
5724}
5725
Pete Cooper80d21cb2015-06-22 19:35:57 +00005726namespace llvm {
5727namespace MCParserUtils {
5728
5729/// Returns whether the given symbol is used anywhere in the given expression,
5730/// or subexpressions.
5731static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5732 switch (Value->getKind()) {
5733 case MCExpr::Binary: {
5734 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5735 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5736 isSymbolUsedInExpression(Sym, BE->getRHS());
5737 }
5738 case MCExpr::Target:
5739 case MCExpr::Constant:
5740 return false;
5741 case MCExpr::SymbolRef: {
5742 const MCSymbol &S =
5743 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5744 if (S.isVariable())
5745 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5746 return &S == Sym;
5747 }
5748 case MCExpr::Unary:
5749 return isSymbolUsedInExpression(
5750 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5751 }
5752
5753 llvm_unreachable("Unknown expr kind!");
5754}
5755
5756bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5757 MCAsmParser &Parser, MCSymbol *&Sym,
5758 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005759
5760 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005761 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005762
5763 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005764 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005765 }
5766
5767 // Note: we don't count b as used in "a = b". This is to allow
5768 // a = b
5769 // b = c
5770
Nirav Dave1a9044b2016-10-24 14:35:29 +00005771 if (Parser.parseToken(AsmToken::EndOfStatement))
5772 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005773
5774 // Validate that the LHS is allowed to be a variable (either it has not been
5775 // used as a symbol, or it is an absolute symbol).
5776 Sym = Parser.getContext().lookupSymbol(Name);
5777 if (Sym) {
5778 // Diagnose assignment to a label.
5779 //
5780 // FIXME: Diagnostics. Note the location of the definition as a label.
5781 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5782 if (isSymbolUsedInExpression(Sym, Value))
5783 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005784 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5785 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005786 ; // Allow redefinitions of undefined symbols only used in directives.
5787 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5788 ; // Allow redefinitions of variables that haven't yet been used.
5789 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5790 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5791 else if (!Sym->isVariable())
5792 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5793 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5794 return Parser.Error(EqualLoc,
5795 "invalid reassignment of non-absolute variable '" +
5796 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005797 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005798 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005799 return false;
5800 } else
5801 Sym = Parser.getContext().getOrCreateSymbol(Name);
5802
5803 Sym->setRedefinable(allow_redef);
5804
5805 return false;
5806}
5807
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005808} // end namespace MCParserUtils
5809} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005810
Daniel Dunbar01e36072010-07-17 02:26:10 +00005811/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005812MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005813 MCStreamer &Out, const MCAsmInfo &MAI,
5814 unsigned CB) {
5815 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005816}