blob: 2756cb71ed94f52ea3d9df1bf7c5b7d1dac9ed40 [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"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000021#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000023#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000024#include "llvm/BinaryFormat/Dwarf.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000025#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000026#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000027#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000028#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000029#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000030#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000031#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000032#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000033#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000034#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000035#include "llvm/MC/MCParser/AsmCond.h"
36#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000037#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000038#include "llvm/MC/MCParser/MCAsmParser.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000039#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000040#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000041#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000042#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000043#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000044#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000045#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000046#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000047#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000048#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000049#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000050#include "llvm/Support/CommandLine.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000051#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000052#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000053#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000054#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000055#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000056#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000057#include <algorithm>
58#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000059#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000060#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000061#include <cstddef>
62#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000063#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000064#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000065#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000066#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000067#include <tuple>
68#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000069#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000070
Chris Lattnerb0133452009-06-21 20:16:42 +000071using namespace llvm;
72
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000073MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000074
Davide Italiano7c9fc732016-07-27 05:51:56 +000075static cl::opt<unsigned> AsmMacroMaxNestingDepth(
76 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
77 cl::desc("The maximum nesting depth allowed for assembly macros."));
78
Daniel Dunbar86033402010-07-12 17:54:38 +000079namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000080
Eli Benderskya313ae62013-01-16 18:56:50 +000081/// \brief Helper types for tracking macro definitions.
82typedef std::vector<AsmToken> MCAsmMacroArgument;
83typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000084
85struct MCAsmMacroParameter {
86 StringRef Name;
87 MCAsmMacroArgument Value;
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000088 bool Required = false;
89 bool Vararg = false;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000090
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000091 MCAsmMacroParameter() = default;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000092};
93
Eli Benderskya313ae62013-01-16 18:56:50 +000094typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
95
96struct MCAsmMacro {
97 StringRef Name;
98 StringRef Body;
99 MCAsmMacroParameters Parameters;
100
101public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000102 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
103 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +0000104};
105
Daniel Dunbar43235712010-07-18 18:54:11 +0000106/// \brief Helper class for storing information about an active macro
107/// instantiation.
108struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +0000109 /// The location of the instantiation.
110 SMLoc InstantiationLoc;
111
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000112 /// The buffer where parsing should resume upon instantiation completion.
113 int ExitBuffer;
114
Daniel Dunbar43235712010-07-18 18:54:11 +0000115 /// The location where parsing should resume upon instantiation completion.
116 SMLoc ExitLoc;
117
Nico Weber155dccd12014-07-24 17:08:39 +0000118 /// The depth of TheCondStack at the start of the instantiation.
119 size_t CondStackDepth;
120
Daniel Dunbar43235712010-07-18 18:54:11 +0000121public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000122 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000123};
124
Eli Friedman0f4871d2012-10-22 23:58:19 +0000125struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000126 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000127 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000128
Jim Grosbach4b905842013-09-20 23:08:21 +0000129 /// \brief The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000130 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000131
Jim Grosbach4b905842013-09-20 23:08:21 +0000132 /// \brief Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000133 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000134
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000135 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000136
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000137 ParseStatementInfo() = delete;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000138 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000139 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000140};
141
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000142/// \brief The concrete assembly parser instance.
143class AsmParser : public MCAsmParser {
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000144private:
145 AsmLexer Lexer;
146 MCContext &Ctx;
147 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000148 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000149 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000150 SourceMgr::DiagHandlerTy SavedDiagHandler;
151 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000152 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000153
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000154 /// This is the current buffer index we're lexing from as managed by the
155 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000156 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000157
158 AsmCond TheCondState;
159 std::vector<AsmCond> TheCondStack;
160
Jim Grosbach4b905842013-09-20 23:08:21 +0000161 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000162 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000163 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000164 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000165
Jim Grosbach4b905842013-09-20 23:08:21 +0000166 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000167 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000168
Jim Grosbach4b905842013-09-20 23:08:21 +0000169 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000170 std::vector<MacroInstantiation*> ActiveMacros;
171
Jim Grosbach4b905842013-09-20 23:08:21 +0000172 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000173 std::deque<MCAsmMacro> MacroLikeBodies;
174
Daniel Dunbar828984f2010-07-18 18:38:02 +0000175 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000176 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000177
Toma Tabacu217116e2015-04-27 10:50:29 +0000178 /// \brief Keeps track of how many .macro's have been instantiated.
179 unsigned NumOfMacroInstantiations;
180
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000181 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000182 struct CppHashInfoTy {
183 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000184 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000185 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000186 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000187 };
188 CppHashInfoTy CppHashInfo;
189
190 /// \brief List of forward directional labels for diagnosis at the end.
191 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
192
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000193 /// When generating dwarf for assembly source files we need to calculate the
194 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000195 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000196 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
197 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000198 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000199 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000200
Devang Patela173ee52012-01-31 18:14:05 +0000201 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000202 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000203
Jim Grosbach4b905842013-09-20 23:08:21 +0000204 /// \brief is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000205 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000206
Jim Grosbach4b905842013-09-20 23:08:21 +0000207 /// \brief Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000208 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000209
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000210public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000211 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000212 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000213 AsmParser(const AsmParser &) = delete;
214 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000215 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000216
Craig Topper59be68f2014-03-08 07:14:16 +0000217 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000218
Craig Topper59be68f2014-03-08 07:14:16 +0000219 void addDirectiveHandler(StringRef Directive,
220 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000221 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000222 }
223
Toma Tabacu11e14a92015-04-21 11:50:52 +0000224 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
225 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
226 }
227
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000228 /// @name MCAsmParser Interface
229 /// {
230
Craig Topper59be68f2014-03-08 07:14:16 +0000231 SourceMgr &getSourceManager() override { return SrcMgr; }
232 MCAsmLexer &getLexer() override { return Lexer; }
233 MCContext &getContext() override { return Ctx; }
234 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000235
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000236 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
237
Craig Topper59be68f2014-03-08 07:14:16 +0000238 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000239 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000240 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000241 else
242 return AssemblerDialect;
243 }
Craig Topper59be68f2014-03-08 07:14:16 +0000244 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000245 AssemblerDialect = i;
246 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000247
Nirav Dave2364748a2016-09-16 18:30:20 +0000248 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
249 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
250 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000251
Craig Topper59be68f2014-03-08 07:14:16 +0000252 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000254 void setParsingInlineAsm(bool V) override {
255 ParsingInlineAsm = V;
256 Lexer.setParsingMSInlineAsm(V);
257 }
Craig Topper59be68f2014-03-08 07:14:16 +0000258 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000259
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000260 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000261 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000262 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000263 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000264 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000265 const MCInstrInfo *MII, const MCInstPrinter *IP,
266 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000267
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000268 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000269 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
270 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
271 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000272 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
273 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000274 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000275
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000276 /// \brief Parse a floating point expression using the float \p Semantics
277 /// and set \p Res to the value.
278 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
279
Jim Grosbach4b905842013-09-20 23:08:21 +0000280 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000281 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000282 bool parseIdentifier(StringRef &Res) override;
283 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000284
Nirav Davef43cc9f2016-10-10 15:24:54 +0000285 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000286
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000287 /// }
288
289private:
Michael Zuckerman763e60e2017-05-04 10:37:00 +0000290 bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc);
Michael Zuckerman1f1a9122017-05-10 13:08:11 +0000291 void altMacroString(StringRef AltMacroStr, std::string &Res);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000292 bool parseStatement(ParseStatementInfo &Info,
293 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000294 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000295 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000296
Jim Grosbach4b905842013-09-20 23:08:21 +0000297 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000298 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000299 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000300 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000301 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000302 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000303
Eli Benderskya313ae62013-01-16 18:56:50 +0000304 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000305 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000306
307 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000308 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000309
310 /// \brief Lookup a previously defined macro.
311 /// \param Name Macro name.
312 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000313 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000314
315 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000316 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000317
318 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000319 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000320
321 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000322 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000323
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000324 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000325 ///
326 /// \param M The macro.
327 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000328 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000329
330 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000331 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000332
David Majnemer91fc4c22014-01-29 18:57:46 +0000333 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000334 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000335
336 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000337 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000338
Jim Grosbach4b905842013-09-20 23:08:21 +0000339 void printMacroInstantiations();
340 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000341 SMRange Range = None) const {
342 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000343 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000344 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000345 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000346
Jim Grosbach4b905842013-09-20 23:08:21 +0000347 /// \brief Enter the specified file. This returns true on failure.
348 bool enterIncludeFile(const std::string &Filename);
349
350 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000351 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000352 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
353 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000354
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000355 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000356 /// current token is not set; clients should ensure Lex() is called
357 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000358 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000359 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000360 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000361 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000362
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000363 /// \brief Parse up to the end of statement and a return the contents from the
364 /// current token until the end of the statement; the current token on exit
365 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000366 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000367
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000368 /// \brief Parse until the end of a statement or a comma is encountered,
369 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000370 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000371
Jim Grosbach4b905842013-09-20 23:08:21 +0000372 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000373 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000374
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000375 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
376 MCBinaryExpr::Opcode &Kind);
377
Jim Grosbach4b905842013-09-20 23:08:21 +0000378 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
379 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
380 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000381
Jim Grosbach4b905842013-09-20 23:08:21 +0000382 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000383
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000384 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
385 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
386
Eli Bendersky17233942013-01-15 22:59:42 +0000387 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000388 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000389 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000390 DK_SET,
391 DK_EQU,
392 DK_EQUIV,
393 DK_ASCII,
394 DK_ASCIZ,
395 DK_STRING,
396 DK_BYTE,
397 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000398 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000399 DK_VALUE,
400 DK_2BYTE,
401 DK_LONG,
402 DK_INT,
403 DK_4BYTE,
404 DK_QUAD,
405 DK_8BYTE,
406 DK_OCTA,
407 DK_DC,
408 DK_DC_A,
409 DK_DC_B,
410 DK_DC_D,
411 DK_DC_L,
412 DK_DC_S,
413 DK_DC_W,
414 DK_DC_X,
415 DK_DCB,
416 DK_DCB_B,
417 DK_DCB_D,
418 DK_DCB_L,
419 DK_DCB_S,
420 DK_DCB_W,
421 DK_DCB_X,
422 DK_DS,
423 DK_DS_B,
424 DK_DS_D,
425 DK_DS_L,
426 DK_DS_P,
427 DK_DS_S,
428 DK_DS_W,
429 DK_DS_X,
430 DK_SINGLE,
431 DK_FLOAT,
432 DK_DOUBLE,
433 DK_ALIGN,
434 DK_ALIGN32,
435 DK_BALIGN,
436 DK_BALIGNW,
437 DK_BALIGNL,
438 DK_P2ALIGN,
439 DK_P2ALIGNW,
440 DK_P2ALIGNL,
441 DK_ORG,
442 DK_FILL,
443 DK_ENDR,
444 DK_BUNDLE_ALIGN_MODE,
445 DK_BUNDLE_LOCK,
446 DK_BUNDLE_UNLOCK,
447 DK_ZERO,
448 DK_EXTERN,
449 DK_GLOBL,
450 DK_GLOBAL,
451 DK_LAZY_REFERENCE,
452 DK_NO_DEAD_STRIP,
453 DK_SYMBOL_RESOLVER,
454 DK_PRIVATE_EXTERN,
455 DK_REFERENCE,
456 DK_WEAK_DEFINITION,
457 DK_WEAK_REFERENCE,
458 DK_WEAK_DEF_CAN_BE_HIDDEN,
459 DK_COMM,
460 DK_COMMON,
461 DK_LCOMM,
462 DK_ABORT,
463 DK_INCLUDE,
464 DK_INCBIN,
465 DK_CODE16,
466 DK_CODE16GCC,
467 DK_REPT,
468 DK_IRP,
469 DK_IRPC,
470 DK_IF,
471 DK_IFEQ,
472 DK_IFGE,
473 DK_IFGT,
474 DK_IFLE,
475 DK_IFLT,
476 DK_IFNE,
477 DK_IFB,
478 DK_IFNB,
479 DK_IFC,
480 DK_IFEQS,
481 DK_IFNC,
482 DK_IFNES,
483 DK_IFDEF,
484 DK_IFNDEF,
485 DK_IFNOTDEF,
486 DK_ELSEIF,
487 DK_ELSE,
488 DK_ENDIF,
489 DK_SPACE,
490 DK_SKIP,
491 DK_FILE,
492 DK_LINE,
493 DK_LOC,
494 DK_STABS,
495 DK_CV_FILE,
496 DK_CV_FUNC_ID,
497 DK_CV_INLINE_SITE_ID,
498 DK_CV_LOC,
499 DK_CV_LINETABLE,
500 DK_CV_INLINE_LINETABLE,
501 DK_CV_DEF_RANGE,
502 DK_CV_STRINGTABLE,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000503 DK_CV_FILECHECKSUMS,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000504 DK_CFI_SECTIONS,
505 DK_CFI_STARTPROC,
506 DK_CFI_ENDPROC,
507 DK_CFI_DEF_CFA,
508 DK_CFI_DEF_CFA_OFFSET,
509 DK_CFI_ADJUST_CFA_OFFSET,
510 DK_CFI_DEF_CFA_REGISTER,
511 DK_CFI_OFFSET,
512 DK_CFI_REL_OFFSET,
513 DK_CFI_PERSONALITY,
514 DK_CFI_LSDA,
515 DK_CFI_REMEMBER_STATE,
516 DK_CFI_RESTORE_STATE,
517 DK_CFI_SAME_VALUE,
518 DK_CFI_RESTORE,
519 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000520 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000521 DK_CFI_SIGNAL_FRAME,
522 DK_CFI_UNDEFINED,
523 DK_CFI_REGISTER,
524 DK_CFI_WINDOW_SAVE,
525 DK_MACROS_ON,
526 DK_MACROS_OFF,
527 DK_ALTMACRO,
528 DK_NOALTMACRO,
529 DK_MACRO,
530 DK_EXITM,
531 DK_ENDM,
532 DK_ENDMACRO,
533 DK_PURGEM,
534 DK_SLEB128,
535 DK_ULEB128,
536 DK_ERR,
537 DK_ERROR,
538 DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000539 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000540 };
541
Jim Grosbach4b905842013-09-20 23:08:21 +0000542 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000543 /// directives parsed by this class.
544 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000545
546 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000547 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000548 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000549 bool parseDirectiveValue(StringRef IDVal,
550 unsigned Size); // ".byte", ".long", ...
551 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
552 bool parseDirectiveRealValue(StringRef IDVal,
553 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000554 bool parseDirectiveFill(); // ".fill"
555 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000556 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000557 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
558 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000559 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000560 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000561
Eli Bendersky17233942013-01-15 22:59:42 +0000562 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000563 bool parseDirectiveFile(SMLoc DirectiveLoc);
564 bool parseDirectiveLine();
565 bool parseDirectiveLoc();
566 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000567
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000568 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
569 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000570 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000571 bool parseDirectiveCVFuncId();
572 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000573 bool parseDirectiveCVLoc();
574 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000575 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000576 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000577 bool parseDirectiveCVStringTable();
578 bool parseDirectiveCVFileChecksums();
579
Eli Bendersky17233942013-01-15 22:59:42 +0000580 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000581 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000582 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000583 bool parseDirectiveCFISections();
584 bool parseDirectiveCFIStartProc();
585 bool parseDirectiveCFIEndProc();
586 bool parseDirectiveCFIDefCfaOffset();
587 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
588 bool parseDirectiveCFIAdjustCfaOffset();
589 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
590 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
591 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
592 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
593 bool parseDirectiveCFIRememberState();
594 bool parseDirectiveCFIRestoreState();
595 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
596 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
597 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000598 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000599 bool parseDirectiveCFISignalFrame();
600 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000601
602 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000603 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000604 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000605 bool parseDirectiveEndMacro(StringRef Directive);
606 bool parseDirectiveMacro(SMLoc DirectiveLoc);
607 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000608 // alternate macro mode directives
609 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000610 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000611 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000612 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000613 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000614 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000615 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000616
Eli Bendersky17233942013-01-15 22:59:42 +0000617 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000618 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000619
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000620 // ".dcb"
621 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
622 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000623 // ".ds"
624 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000625
Eli Bendersky17233942013-01-15 22:59:42 +0000626 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000627 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000628
Jim Grosbach4b905842013-09-20 23:08:21 +0000629 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000630 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000631 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000632
Jim Grosbach4b905842013-09-20 23:08:21 +0000633 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000634
Jim Grosbach4b905842013-09-20 23:08:21 +0000635 bool parseDirectiveAbort(); // ".abort"
636 bool parseDirectiveInclude(); // ".include"
637 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000638
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000639 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
640 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000641 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000642 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000643 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000644 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000645 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
646 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000647 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000648 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
649 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
650 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
651 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000652 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000653
Jim Grosbach4b905842013-09-20 23:08:21 +0000654 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000655 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000656
Rafael Espindola34b9c512012-06-03 23:57:14 +0000657 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000658 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
659 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000660 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000661 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000662 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
663 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
664 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000665
Chad Rosierc7f552c2013-02-12 21:33:51 +0000666 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000667 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000668 size_t Len);
669
670 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000671 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000672
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000673 // "end"
674 bool parseDirectiveEnd(SMLoc DirectiveLoc);
675
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000676 // ".err" or ".error"
677 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000678
Nico Weber404012b2014-07-24 16:26:06 +0000679 // ".warning"
680 bool parseDirectiveWarning(SMLoc DirectiveLoc);
681
Eli Bendersky17233942013-01-15 22:59:42 +0000682 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000683};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000684
685} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000686
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000687namespace llvm {
688
689extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000690extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000691extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000692
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000693} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000694
Chris Lattnerc35681b2010-01-19 19:46:13 +0000695enum { DEFAULT_ADDRSPACE = 0 };
696
David Blaikie9f380a32015-03-16 18:06:57 +0000697AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000698 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000699 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000700 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000701 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000702 // Save the old handler.
703 SavedDiagHandler = SrcMgr.getDiagHandler();
704 SavedDiagContext = SrcMgr.getDiagContext();
705 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000706 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000707 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000708
Daniel Dunbarc5011082010-07-12 18:12:02 +0000709 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000710 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
711 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000712 PlatformParser.reset(createCOFFAsmParser());
713 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000714 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000715 PlatformParser.reset(createDarwinAsmParser());
716 IsDarwin = true;
717 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000718 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000719 PlatformParser.reset(createELFAsmParser());
720 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000721 case MCObjectFileInfo::IsWasm:
722 llvm_unreachable("Wasm parsing not supported yet");
723 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000724 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000725
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000726 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000727 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000728
729 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000730}
731
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000732AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000733 assert((HadError || ActiveMacros.empty()) &&
734 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000735
736 // Restore the saved diagnostics handler and context for use during
737 // finalization.
738 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000739}
740
Jim Grosbach4b905842013-09-20 23:08:21 +0000741void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000742 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000743 for (std::vector<MacroInstantiation *>::const_reverse_iterator
744 it = ActiveMacros.rbegin(),
745 ie = ActiveMacros.rend();
746 it != ie; ++it)
747 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000748 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000749}
750
Nirav Dave2364748a2016-09-16 18:30:20 +0000751void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
752 printPendingErrors();
753 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000754 printMacroInstantiations();
755}
756
Nirav Dave2364748a2016-09-16 18:30:20 +0000757bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000758 if(getTargetParser().getTargetOptions().MCNoWarn)
759 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000760 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000761 return Error(L, Msg, Range);
762 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000763 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000764 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000765}
766
Nirav Dave2364748a2016-09-16 18:30:20 +0000767bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000768 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000769 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000770 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000771 return true;
772}
773
Jim Grosbach4b905842013-09-20 23:08:21 +0000774bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000775 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000776 unsigned NewBuf =
777 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
778 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000779 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000780
Sean Callanan7a77eae2010-01-21 00:19:58 +0000781 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000782 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000783 return false;
784}
Daniel Dunbar43235712010-07-18 18:54:11 +0000785
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000786/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000787/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000788/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000789bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
790 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000791 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000792 unsigned NewBuf =
793 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
794 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000795 return true;
796
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000797 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000798 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
799 Bytes = Bytes.drop_front(Skip);
800 if (Count) {
801 int64_t Res;
802 if (!Count->evaluateAsAbsolute(Res))
803 return Error(Loc, "expected absolute expression");
804 if (Res < 0)
805 return Warning(Loc, "negative count has no effect");
806 Bytes = Bytes.take_front(Res);
807 }
808 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000809 return false;
810}
811
Alp Tokera55b95b2014-07-06 10:33:31 +0000812void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
813 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000814 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
815 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000816}
817
Sean Callanan7a77eae2010-01-21 00:19:58 +0000818const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000819 if (Lexer.getTok().is(AsmToken::Error))
820 Error(Lexer.getErrLoc(), Lexer.getErr());
821
Nirav Dave53a72f42016-07-11 12:42:14 +0000822 // if it's a end of statement with a comment in it
823 if (getTok().is(AsmToken::EndOfStatement)) {
824 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000825 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000826 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
827 Out.addExplicitComment(Twine(getTok().getString()));
828 }
829
Sean Callanan7a77eae2010-01-21 00:19:58 +0000830 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000831
832 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000833 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000834 if (MAI.preserveAsmComments())
835 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000836 tok = &Lexer.Lex();
837 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000838
Sean Callanan7a77eae2010-01-21 00:19:58 +0000839 if (tok->is(AsmToken::Eof)) {
840 // If this is the end of an included file, pop the parent file off the
841 // include stack.
842 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
843 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000844 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000845 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000846 }
847 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000848
Sean Callanan7a77eae2010-01-21 00:19:58 +0000849 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000850}
851
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000852bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000853 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000854 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000855 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000856
Chris Lattner36e02122009-06-21 20:54:55 +0000857 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000858 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000859
860 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000861 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000862 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000863
Kevin Enderby6469fc22011-11-01 22:27:22 +0000864 // If we are generating dwarf for assembly source files save the initial text
865 // section and generate a .file directive.
866 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000867 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000868 if (!Sec->getBeginSymbol()) {
869 MCSymbol *SectionStartSym = getContext().createTempSymbol();
870 getStreamer().EmitLabel(SectionStartSym);
871 Sec->setBeginSymbol(SectionStartSym);
872 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000873 bool InsertResult = getContext().addGenDwarfSection(Sec);
874 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000875 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000876 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
877 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000878 }
879
Chris Lattner73f36112009-07-02 21:53:43 +0000880 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000881 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000882 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000883 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000884 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000885
Nirav Dave2364748a2016-09-16 18:30:20 +0000886 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
887 // for printing ErrMsg via Lex() only if no (presumably better) parser error
888 // exists.
889 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000890 Lex();
891 }
892
Nirav Dave2364748a2016-09-16 18:30:20 +0000893 // parseStatement returned true so may need to emit an error.
894 printPendingErrors();
895
896 // Skipping to the next line if needed.
897 if (!getLexer().isAtStartOfStatement())
898 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000899 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000900
Nirav Dave2364748a2016-09-16 18:30:20 +0000901 // All errors should have been emitted.
902 assert(!hasPendingError() && "unexpected error from parseStatement");
903
Oliver Stannard21718282016-07-26 14:19:47 +0000904 getTargetParser().flushPendingInstructions(getStreamer());
905
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000906 if (TheCondState.TheCond != StartingCondState.TheCond ||
907 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000908 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000909 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000910 const auto &LineTables = getContext().getMCDwarfLineTables();
911 if (!LineTables.empty()) {
912 unsigned Index = 0;
913 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
914 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000915 printError(getTok().getLoc(), "unassigned file number: " +
916 Twine(Index) +
917 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000918 ++Index;
919 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000920 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000921
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000922 // Check to see that all assembler local symbols were actually defined.
923 // Targets that don't do subsections via symbols may not want this, though,
924 // so conservatively exclude them. Only do this if we're finalizing, though,
925 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000926 if (!NoFinalize) {
927 if (MAI.hasSubsectionsViaSymbols()) {
928 for (const auto &TableEntry : getContext().getSymbols()) {
929 MCSymbol *Sym = TableEntry.getValue();
930 // Variable symbols may not be marked as defined, so check those
931 // explicitly. If we know it's a variable, we have a definition for
932 // the purposes of this check.
933 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
934 // FIXME: We would really like to refer back to where the symbol was
935 // first referenced for a source location. We need to add something
936 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000937 printError(getTok().getLoc(), "assembler local symbol '" +
938 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000939 }
940 }
941
942 // Temporary symbols like the ones for directional jumps don't go in the
943 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000944 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
945 if (std::get<2>(LocSym)->isUndefined()) {
946 // Reset the state of any "# line file" directives we've seen to the
947 // context as it was at the diagnostic site.
948 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000949 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000950 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000951 }
952 }
953
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000954 // Finalize the output stream if there are no errors and if the client wants
955 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000956 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000957 Out.Finish();
958
Oliver Stannard07b43d32015-11-17 09:58:07 +0000959 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000960}
961
Nirav Davef43cc9f2016-10-10 15:24:54 +0000962bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000963 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000964 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000965 return Error(getTok().getLoc(),
966 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000967 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000968 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000969}
970
Jim Grosbach4b905842013-09-20 23:08:21 +0000971/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000972void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000973 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000974 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000975
Chris Lattnere5074c42009-06-22 01:29:09 +0000976 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000977 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000978 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000979}
980
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000981StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000982 const char *Start = getTok().getLoc().getPointer();
983
Jim Grosbach4b905842013-09-20 23:08:21 +0000984 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000985 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000986
987 const char *End = getTok().getLoc().getPointer();
988 return StringRef(Start, End - Start);
989}
Chris Lattner78db3622009-06-22 05:51:26 +0000990
Jim Grosbach4b905842013-09-20 23:08:21 +0000991StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000992 const char *Start = getTok().getLoc().getPointer();
993
994 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000995 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000996 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000997
998 const char *End = getTok().getLoc().getPointer();
999 return StringRef(Start, End - Start);
1000}
1001
Jim Grosbach4b905842013-09-20 23:08:21 +00001002/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001003/// NOTE: This assumes the leading '(' has already been consumed.
1004///
1005/// parenexpr ::= expr)
1006///
Jim Grosbach4b905842013-09-20 23:08:21 +00001007bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1008 if (parseExpression(Res))
1009 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001010 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +00001011 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001012 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001013 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +00001014 return false;
1015}
Chris Lattner78db3622009-06-22 05:51:26 +00001016
Jim Grosbach4b905842013-09-20 23:08:21 +00001017/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001018/// NOTE: This assumes the leading '[' has already been consumed.
1019///
1020/// bracketexpr ::= expr]
1021///
Jim Grosbach4b905842013-09-20 23:08:21 +00001022bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1023 if (parseExpression(Res))
1024 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001025 EndLoc = getTok().getEndLoc();
1026 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1027 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001028 return false;
1029}
1030
Jim Grosbach4b905842013-09-20 23:08:21 +00001031/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001032/// primaryexpr ::= (parenexpr
1033/// primaryexpr ::= symbol
1034/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001035/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001036/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001037bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001038 SMLoc FirstTokenLoc = getLexer().getLoc();
1039 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1040 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001041 default:
1042 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001043 // If we have an error assume that we've already handled it.
1044 case AsmToken::Error:
1045 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001046 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001047 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001048 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001049 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001050 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001051 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001052 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001053 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001054 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001055 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001056 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001057 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001058 // We may have failed but $ may be a valid token.
1059 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001060 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001061 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001062 // This is a '$' reference, which references the current PC. Emit a
1063 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001064 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001065 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001066 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001067 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001068 EndLoc = FirstTokenLoc;
1069 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001070 }
1071 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001072 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001073 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001074 // Parse symbol variant
1075 std::pair<StringRef, StringRef> Split;
1076 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001077 if (FirstTokenKind == AsmToken::String) {
1078 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001079 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001080 SMLoc AtLoc = getLexer().getLoc();
1081 StringRef VName;
1082 if (parseIdentifier(VName))
1083 return Error(AtLoc, "expected symbol variant after '@'");
1084
1085 Split = std::make_pair(Identifier, VName);
1086 }
1087 } else {
1088 Split = Identifier.split('@');
1089 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001090 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001091 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001092 StringRef VName;
1093 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001094 // eat ')'.
1095 if (parseToken(AsmToken::RParen,
1096 "unexpected token in variant, expected ')'"))
1097 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001098 Split = std::make_pair(Identifier, VName);
1099 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001100
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001101 EndLoc = SMLoc::getFromPointer(Identifier.end());
1102
Daniel Dunbard20cda02009-10-16 01:34:54 +00001103 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001104 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001105 if (SymbolName.empty())
1106 return true;
1107
Hans Wennborgce69d772013-10-18 20:46:28 +00001108 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001109
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001110 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001111 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001112 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001113 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1114 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001115 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001116 Variant = MCSymbolRefExpr::VK_None;
1117 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001118 return Error(SMLoc::getFromPointer(Split.second.begin()),
1119 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001120 }
1121 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001122
Jim Grosbach6f482002015-05-18 18:43:14 +00001123 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001124
Daniel Dunbard20cda02009-10-16 01:34:54 +00001125 // If this is an absolute variable reference, substitute it now to preserve
1126 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001127 if (Sym->isVariable() &&
1128 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001129 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001130 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001131
Vedant Kumar86dbd922015-08-31 17:44:53 +00001132 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001133 return false;
1134 }
1135
1136 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001137 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001138 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001139 }
David Woodhousef42a6662014-02-01 16:20:54 +00001140 case AsmToken::BigNum:
1141 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001142 case AsmToken::Integer: {
1143 SMLoc Loc = getTok().getLoc();
1144 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001145 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001146 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001147 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001148 // Look for 'b' or 'f' following an Integer as a directional label
1149 if (Lexer.getKind() == AsmToken::Identifier) {
1150 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001151 // Lookup the symbol variant if used.
1152 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1153 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1154 if (Split.first.size() != IDVal.size()) {
1155 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001156 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001157 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001158 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001159 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001160 if (IDVal == "f" || IDVal == "b") {
1161 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001162 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001163 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001164 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001165 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001166 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001167 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001168 Lex(); // Eat identifier.
1169 }
1170 }
Chris Lattner78db3622009-06-22 05:51:26 +00001171 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001172 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001173 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001174 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001175 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001176 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001177 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001178 Lex(); // Eat token.
1179 return false;
1180 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001181 case AsmToken::Dot: {
1182 // This is a '.' reference, which references the current PC. Emit a
1183 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001184 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001185 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001186 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001187 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001188 Lex(); // Eat identifier.
1189 return false;
1190 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001191 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001192 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001193 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001194 case AsmToken::LBrac:
1195 if (!PlatformParser->HasBracketExpressions())
1196 return TokError("brackets expression not supported on this target");
1197 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001198 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001199 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001200 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001201 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001202 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001203 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001204 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001205 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001206 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001207 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001208 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001209 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001210 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001211 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001212 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001213 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001214 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001215 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001216 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001217 // MIPS unary expression operators. The lexer won't generate these tokens if
1218 // MCAsmInfo::HasMipsExpressions is false for the target.
1219 case AsmToken::PercentCall16:
1220 case AsmToken::PercentCall_Hi:
1221 case AsmToken::PercentCall_Lo:
1222 case AsmToken::PercentDtprel_Hi:
1223 case AsmToken::PercentDtprel_Lo:
1224 case AsmToken::PercentGot:
1225 case AsmToken::PercentGot_Disp:
1226 case AsmToken::PercentGot_Hi:
1227 case AsmToken::PercentGot_Lo:
1228 case AsmToken::PercentGot_Ofst:
1229 case AsmToken::PercentGot_Page:
1230 case AsmToken::PercentGottprel:
1231 case AsmToken::PercentGp_Rel:
1232 case AsmToken::PercentHi:
1233 case AsmToken::PercentHigher:
1234 case AsmToken::PercentHighest:
1235 case AsmToken::PercentLo:
1236 case AsmToken::PercentNeg:
1237 case AsmToken::PercentPcrel_Hi:
1238 case AsmToken::PercentPcrel_Lo:
1239 case AsmToken::PercentTlsgd:
1240 case AsmToken::PercentTlsldm:
1241 case AsmToken::PercentTprel_Hi:
1242 case AsmToken::PercentTprel_Lo:
1243 Lex(); // Eat the operator.
1244 if (Lexer.isNot(AsmToken::LParen))
1245 return TokError("expected '(' after operator");
1246 Lex(); // Eat the operator.
1247 if (parseExpression(Res, EndLoc))
1248 return true;
1249 if (Lexer.isNot(AsmToken::RParen))
1250 return TokError("expected ')'");
1251 Lex(); // Eat the operator.
1252 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1253 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001254 }
1255}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001256
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001257bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001258 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001259 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001260}
1261
Daniel Dunbar55f16672010-09-17 02:47:07 +00001262const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001263AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001264 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001265 // Ask the target implementation about this expression first.
1266 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1267 if (NewE)
1268 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001269 // Recurse over the given expression, rebuilding it to apply the given variant
1270 // if there is exactly one symbol.
1271 switch (E->getKind()) {
1272 case MCExpr::Target:
1273 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001274 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001275
1276 case MCExpr::SymbolRef: {
1277 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1278
1279 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001280 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1281 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001282 return E;
1283 }
1284
Jim Grosbach13760bd2015-05-30 01:25:56 +00001285 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001286 }
1287
1288 case MCExpr::Unary: {
1289 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001290 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001291 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001292 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001293 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001294 }
1295
1296 case MCExpr::Binary: {
1297 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001298 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1299 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001300
1301 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001302 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001303
Jim Grosbach4b905842013-09-20 23:08:21 +00001304 if (!LHS)
1305 LHS = BE->getLHS();
1306 if (!RHS)
1307 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001308
Jim Grosbach13760bd2015-05-30 01:25:56 +00001309 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001310 }
1311 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001312
Craig Toppera2886c22012-02-07 05:05:23 +00001313 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001314}
1315
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001316/// This function checks if the next token is <string> type or arithmetic.
1317/// string that begin with character '<' must end with character '>'.
1318/// otherwise it is arithmetics.
1319/// If the function returns a 'true' value,
1320/// the End argument will be filled with the last location pointed to the '>'
1321/// character.
1322
1323/// There is a gap between the AltMacro's documentation and the single quote implementation.
1324/// GCC does not fully support this feature and so we will not support it.
1325/// TODO: Adding single quote as a string.
1326bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1327 assert((StrLoc.getPointer() != NULL) &&
1328 "Argument to the function cannot be a NULL value");
1329 const char *CharPtr = StrLoc.getPointer();
1330 while ((*CharPtr != '>') && (*CharPtr != '\n') &&
1331 (*CharPtr != '\r') && (*CharPtr != '\0')){
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001332 if(*CharPtr == '!')
1333 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001334 CharPtr++;
1335 }
1336 if (*CharPtr == '>') {
1337 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1338 return true;
1339 }
1340 return false;
1341}
1342
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001343/// \brief creating a string without the escape characters '!'.
1344void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) {
Michael Zuckermanff298792017-05-10 14:00:57 +00001345 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001346 if (AltMacroStr[Pos] == '!')
1347 Pos++;
1348 Res += AltMacroStr[Pos];
1349 }
1350}
1351
Jim Grosbach4b905842013-09-20 23:08:21 +00001352/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001353///
Jim Grosbachbd164242011-08-20 16:24:13 +00001354/// expr ::= expr &&,|| expr -> lowest.
1355/// expr ::= expr |,^,&,! expr
1356/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1357/// expr ::= expr <<,>> expr
1358/// expr ::= expr +,- expr
1359/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001360/// expr ::= primaryexpr
1361///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001362bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001363 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001364 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001365 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001366 return true;
1367
Daniel Dunbar55f16672010-09-17 02:47:07 +00001368 // As a special case, we support 'a op b @ modifier' by rewriting the
1369 // expression to include the modifier. This is inefficient, but in general we
1370 // expect users to use 'a@modifier op b'.
1371 if (Lexer.getKind() == AsmToken::At) {
1372 Lex();
1373
1374 if (Lexer.isNot(AsmToken::Identifier))
1375 return TokError("unexpected symbol modifier following '@'");
1376
1377 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001378 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001379 if (Variant == MCSymbolRefExpr::VK_Invalid)
1380 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1381
Jim Grosbach4b905842013-09-20 23:08:21 +00001382 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001383 if (!ModifiedRes) {
1384 return TokError("invalid modifier '" + getTok().getIdentifier() +
1385 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001386 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001387
Daniel Dunbar55f16672010-09-17 02:47:07 +00001388 Res = ModifiedRes;
1389 Lex();
1390 }
1391
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001392 // Try to constant fold it up front, if possible.
1393 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001394 if (Res->evaluateAsAbsolute(Value))
1395 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001396
1397 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001398}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001399
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001400bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001401 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001402 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001403}
1404
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001405bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1406 SMLoc &EndLoc) {
1407 if (parseParenExpr(Res, EndLoc))
1408 return true;
1409
1410 for (; ParenDepth > 0; --ParenDepth) {
1411 if (parseBinOpRHS(1, Res, EndLoc))
1412 return true;
1413
1414 // We don't Lex() the last RParen.
1415 // This is the same behavior as parseParenExpression().
1416 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001417 EndLoc = getTok().getEndLoc();
1418 if (parseToken(AsmToken::RParen,
1419 "expected ')' in parentheses expression"))
1420 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001421 }
1422 }
1423 return false;
1424}
1425
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001426bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001427 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001428
Daniel Dunbar75630b32009-06-30 02:10:03 +00001429 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001430 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001431 return true;
1432
Jim Grosbach13760bd2015-05-30 01:25:56 +00001433 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001434 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001435
1436 return false;
1437}
1438
David Majnemer0993e0b2015-10-26 03:15:34 +00001439static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1440 MCBinaryExpr::Opcode &Kind,
1441 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001442 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001443 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001444 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001445
Jim Grosbach4b905842013-09-20 23:08:21 +00001446 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001447 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001448 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001449 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001450 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001451 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001452 return 1;
1453
Jim Grosbach4b905842013-09-20 23:08:21 +00001454 // Low Precedence: |, &, ^
1455 //
1456 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001457 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001458 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001459 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001460 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001461 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001462 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001463 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001464 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001465 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001466
Jim Grosbach4b905842013-09-20 23:08:21 +00001467 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001468 case AsmToken::EqualEqual:
1469 Kind = MCBinaryExpr::EQ;
1470 return 3;
1471 case AsmToken::ExclaimEqual:
1472 case AsmToken::LessGreater:
1473 Kind = MCBinaryExpr::NE;
1474 return 3;
1475 case AsmToken::Less:
1476 Kind = MCBinaryExpr::LT;
1477 return 3;
1478 case AsmToken::LessEqual:
1479 Kind = MCBinaryExpr::LTE;
1480 return 3;
1481 case AsmToken::Greater:
1482 Kind = MCBinaryExpr::GT;
1483 return 3;
1484 case AsmToken::GreaterEqual:
1485 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001486 return 3;
1487
Jim Grosbach4b905842013-09-20 23:08:21 +00001488 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001489 case AsmToken::LessLess:
1490 Kind = MCBinaryExpr::Shl;
1491 return 4;
1492 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001493 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001494 return 4;
1495
Jim Grosbach4b905842013-09-20 23:08:21 +00001496 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001497 case AsmToken::Plus:
1498 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001499 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001500 case AsmToken::Minus:
1501 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001502 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001503
Jim Grosbach4b905842013-09-20 23:08:21 +00001504 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001505 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001506 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001507 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001508 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001509 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001510 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001511 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001512 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001513 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001514 }
1515}
1516
David Majnemer0993e0b2015-10-26 03:15:34 +00001517static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1518 MCBinaryExpr::Opcode &Kind,
1519 bool ShouldUseLogicalShr) {
1520 switch (K) {
1521 default:
1522 return 0; // not a binop.
1523
1524 // Lowest Precedence: &&, ||
1525 case AsmToken::AmpAmp:
1526 Kind = MCBinaryExpr::LAnd;
1527 return 2;
1528 case AsmToken::PipePipe:
1529 Kind = MCBinaryExpr::LOr;
1530 return 1;
1531
1532 // Low Precedence: ==, !=, <>, <, <=, >, >=
1533 case AsmToken::EqualEqual:
1534 Kind = MCBinaryExpr::EQ;
1535 return 3;
1536 case AsmToken::ExclaimEqual:
1537 case AsmToken::LessGreater:
1538 Kind = MCBinaryExpr::NE;
1539 return 3;
1540 case AsmToken::Less:
1541 Kind = MCBinaryExpr::LT;
1542 return 3;
1543 case AsmToken::LessEqual:
1544 Kind = MCBinaryExpr::LTE;
1545 return 3;
1546 case AsmToken::Greater:
1547 Kind = MCBinaryExpr::GT;
1548 return 3;
1549 case AsmToken::GreaterEqual:
1550 Kind = MCBinaryExpr::GTE;
1551 return 3;
1552
1553 // Low Intermediate Precedence: +, -
1554 case AsmToken::Plus:
1555 Kind = MCBinaryExpr::Add;
1556 return 4;
1557 case AsmToken::Minus:
1558 Kind = MCBinaryExpr::Sub;
1559 return 4;
1560
1561 // High Intermediate Precedence: |, &, ^
1562 //
1563 // FIXME: gas seems to support '!' as an infix operator?
1564 case AsmToken::Pipe:
1565 Kind = MCBinaryExpr::Or;
1566 return 5;
1567 case AsmToken::Caret:
1568 Kind = MCBinaryExpr::Xor;
1569 return 5;
1570 case AsmToken::Amp:
1571 Kind = MCBinaryExpr::And;
1572 return 5;
1573
1574 // Highest Precedence: *, /, %, <<, >>
1575 case AsmToken::Star:
1576 Kind = MCBinaryExpr::Mul;
1577 return 6;
1578 case AsmToken::Slash:
1579 Kind = MCBinaryExpr::Div;
1580 return 6;
1581 case AsmToken::Percent:
1582 Kind = MCBinaryExpr::Mod;
1583 return 6;
1584 case AsmToken::LessLess:
1585 Kind = MCBinaryExpr::Shl;
1586 return 6;
1587 case AsmToken::GreaterGreater:
1588 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1589 return 6;
1590 }
1591}
1592
1593unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1594 MCBinaryExpr::Opcode &Kind) {
1595 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1596 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1597 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1598}
1599
Jim Grosbach4b905842013-09-20 23:08:21 +00001600/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001601/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001602bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001603 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001604 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001605 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001606 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001607 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001608
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001609 // If the next token is lower precedence than we are allowed to eat, return
1610 // successfully with what we ate already.
1611 if (TokPrec < Precedence)
1612 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001613
Sean Callanan686ed8d2010-01-19 20:22:31 +00001614 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001615
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001616 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001617 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001618 if (parsePrimaryExpr(RHS, EndLoc))
1619 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001620
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001621 // If BinOp binds less tightly with RHS than the operator after RHS, let
1622 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001623 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001624 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001625 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1626 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001627
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001628 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001629 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001630 }
1631}
1632
Chris Lattner36e02122009-06-21 20:54:55 +00001633/// ParseStatement:
1634/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001635/// ::= Label* Directive ...Operands... EndOfStatement
1636/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001637bool AsmParser::parseStatement(ParseStatementInfo &Info,
1638 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001639 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001640 // Eat initial spaces and comments
1641 while (Lexer.is(AsmToken::Space))
1642 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001643 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001644 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001645 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001646 getTok().getString().front() == '\n')
1647 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001648 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001649 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001650 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001651 if (Lexer.is(AsmToken::Hash)) {
1652 // Seeing a hash here means that it was an end-of-line comment in
1653 // an asm syntax where hash's are not comment and the previous
1654 // statement parser did not check the end of statement. Relex as
1655 // EndOfStatement.
1656 StringRef CommentStr = parseStringToEndOfStatement();
1657 Lexer.Lex();
1658 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1659 return false;
1660 }
Nirav Davefd910412016-06-17 16:06:17 +00001661 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001662 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001663 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001664 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001665 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001666 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001667 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001668 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001669 if (Lexer.is(AsmToken::Integer)) {
1670 LocalLabelVal = getTok().getIntVal();
1671 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001672 if (!TheCondState.Ignore) {
1673 Lex(); // always eat a token
1674 return Error(IDLoc, "unexpected token at start of statement");
1675 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001676 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001677 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001678 IDVal = getTok().getString();
1679 Lex(); // Consume the integer token to be used as an identifier token.
1680 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001681 if (!TheCondState.Ignore) {
1682 Lex(); // always eat a token
1683 return Error(IDLoc, "unexpected token at start of statement");
1684 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001685 }
1686 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001687 } else if (Lexer.is(AsmToken::Dot)) {
1688 // Treat '.' as a valid identifier in this context.
1689 Lex();
1690 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001691 } else if (Lexer.is(AsmToken::LCurly)) {
1692 // Treat '{' as a valid identifier in this context.
1693 Lex();
1694 IDVal = "{";
1695
1696 } else if (Lexer.is(AsmToken::RCurly)) {
1697 // Treat '}' as a valid identifier in this context.
1698 Lex();
1699 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001700 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001701 if (!TheCondState.Ignore) {
1702 Lex(); // always eat a token
1703 return Error(IDLoc, "unexpected token at start of statement");
1704 }
Chris Lattner926885c2010-04-17 18:14:27 +00001705 IDVal = "";
1706 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001707
Chris Lattner926885c2010-04-17 18:14:27 +00001708 // Handle conditional assembly here before checking for skipping. We
1709 // have to do this so that .endif isn't skipped in a ".if 0" block for
1710 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001711 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001712 DirectiveKindMap.find(IDVal);
1713 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1714 ? DK_NO_DIRECTIVE
1715 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001716 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001717 default:
1718 break;
1719 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001720 case DK_IFEQ:
1721 case DK_IFGE:
1722 case DK_IFGT:
1723 case DK_IFLE:
1724 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001725 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001726 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001727 case DK_IFB:
1728 return parseDirectiveIfb(IDLoc, true);
1729 case DK_IFNB:
1730 return parseDirectiveIfb(IDLoc, false);
1731 case DK_IFC:
1732 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001733 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001734 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001735 case DK_IFNC:
1736 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001737 case DK_IFNES:
1738 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001739 case DK_IFDEF:
1740 return parseDirectiveIfdef(IDLoc, true);
1741 case DK_IFNDEF:
1742 case DK_IFNOTDEF:
1743 return parseDirectiveIfdef(IDLoc, false);
1744 case DK_ELSEIF:
1745 return parseDirectiveElseIf(IDLoc);
1746 case DK_ELSE:
1747 return parseDirectiveElse(IDLoc);
1748 case DK_ENDIF:
1749 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001750 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001751
Eli Bendersky88024712013-01-16 19:32:36 +00001752 // Ignore the statement if in the middle of inactive conditional
1753 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001754 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001755 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001756 return false;
1757 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001758
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001759 // FIXME: Recurse on local labels?
1760
1761 // See what kind of statement we have.
1762 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001763 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001764 if (!getTargetParser().isLabel(ID))
1765 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001766 if (checkForValidSection())
1767 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001768
Chris Lattner36e02122009-06-21 20:54:55 +00001769 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001770 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001771
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001772 // Diagnose attempt to use '.' as a label.
1773 if (IDVal == ".")
1774 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1775
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001776 // Diagnose attempt to use a variable as a label.
1777 //
1778 // FIXME: Diagnostics. Note the location of the definition as a label.
1779 // FIXME: This doesn't diagnose assignment to a symbol which has been
1780 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001781 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001782 if (LocalLabelVal == -1) {
1783 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001784 StringRef RewrittenLabel =
1785 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001786 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001787 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001788 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1789 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001790 IDVal = RewrittenLabel;
1791 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001792 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001793 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001794 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001795 // End of Labels should be treated as end of line for lexing
1796 // purposes but that information is not available to the Lexer who
1797 // does not understand Labels. This may cause us to see a Hash
1798 // here instead of a preprocessor line comment.
1799 if (getTok().is(AsmToken::Hash)) {
1800 StringRef CommentStr = parseStringToEndOfStatement();
1801 Lexer.Lex();
1802 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1803 }
1804
Nirav Dave8ea792d2016-07-13 14:03:12 +00001805 // Consume any end of statement token, if present, to avoid spurious
1806 // AddBlankLine calls().
1807 if (getTok().is(AsmToken::EndOfStatement)) {
1808 Lex();
1809 }
1810
Daniel Dunbare73b2672009-08-26 22:13:22 +00001811 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001812 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001813 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001814
Kevin Enderbye7739d42011-12-09 18:09:40 +00001815 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001816 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001817 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001818 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1819 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001820
Tim Northover1744d0a2013-10-25 12:49:50 +00001821 getTargetParser().onLabelParsed(Sym);
1822
Eli Friedman0f4871d2012-10-22 23:58:19 +00001823 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001824 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001825
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001826 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001827 if (!getTargetParser().equalIsAsmAssignment())
1828 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001829 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001830 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001831
Jim Grosbach4b905842013-09-20 23:08:21 +00001832 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001833
1834 default: // Normal instruction or directive.
1835 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001836 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001837
1838 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001839 if (areMacrosEnabled())
1840 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1841 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001842 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001843
Michael J. Spencer530ce852010-10-09 11:00:50 +00001844 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001845
Eli Bendersky17233942013-01-15 22:59:42 +00001846 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001847 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001848 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001849 //
Eli Bendersky17233942013-01-15 22:59:42 +00001850 // 1. The target-specific assembly parser. Some directives are target
1851 // specific or may potentially behave differently on certain targets.
1852 // 2. Asm parser extensions. For example, platform-specific parsers
1853 // (like the ELF parser) register themselves as extensions.
1854 // 3. The generic directive parser implemented by this class. These are
1855 // all the directives that behave in a target and platform independent
1856 // manner, or at least have a default behavior that's shared between
1857 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001858
Oliver Stannard21718282016-07-26 14:19:47 +00001859 getTargetParser().flushPendingInstructions(getStreamer());
1860
Nirav Dave2364748a2016-09-16 18:30:20 +00001861 SMLoc StartTokLoc = getTok().getLoc();
1862 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1863
1864 if (hasPendingError())
1865 return true;
1866 // Currently the return value should be true if we are
1867 // uninterested but as this is at odds with the standard parsing
1868 // convention (return true = error) we have instances of a parsed
1869 // directive that fails returning true as an error. Catch these
1870 // cases as best as possible errors here.
1871 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1872 return true;
1873 // Return if we did some parsing or believe we succeeded.
1874 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001875 return false;
1876
Alp Tokercb402912014-01-24 17:20:08 +00001877 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001878 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001879 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1880 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001881 if (Handler.first)
1882 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1883
1884 // Finally, if no one else is interested in this directive, it must be
1885 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001886 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001887 default:
1888 break;
1889 case DK_SET:
1890 case DK_EQU:
1891 return parseDirectiveSet(IDVal, true);
1892 case DK_EQUIV:
1893 return parseDirectiveSet(IDVal, false);
1894 case DK_ASCII:
1895 return parseDirectiveAscii(IDVal, false);
1896 case DK_ASCIZ:
1897 case DK_STRING:
1898 return parseDirectiveAscii(IDVal, true);
1899 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001900 case DK_DC_B:
1901 return parseDirectiveValue(IDVal, 1);
1902 case DK_DC:
1903 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001904 case DK_SHORT:
1905 case DK_VALUE:
1906 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001907 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001908 case DK_LONG:
1909 case DK_INT:
1910 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001911 case DK_DC_L:
1912 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001913 case DK_QUAD:
1914 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001915 return parseDirectiveValue(IDVal, 8);
1916 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001917 return parseDirectiveValue(
1918 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001919 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001920 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001921 case DK_SINGLE:
1922 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001923 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001924 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001925 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001926 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001927 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001928 case DK_ALIGN: {
1929 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1930 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1931 }
1932 case DK_ALIGN32: {
1933 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1934 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1935 }
1936 case DK_BALIGN:
1937 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1938 case DK_BALIGNW:
1939 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1940 case DK_BALIGNL:
1941 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1942 case DK_P2ALIGN:
1943 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1944 case DK_P2ALIGNW:
1945 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1946 case DK_P2ALIGNL:
1947 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1948 case DK_ORG:
1949 return parseDirectiveOrg();
1950 case DK_FILL:
1951 return parseDirectiveFill();
1952 case DK_ZERO:
1953 return parseDirectiveZero();
1954 case DK_EXTERN:
1955 eatToEndOfStatement(); // .extern is the default, ignore it.
1956 return false;
1957 case DK_GLOBL:
1958 case DK_GLOBAL:
1959 return parseDirectiveSymbolAttribute(MCSA_Global);
1960 case DK_LAZY_REFERENCE:
1961 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1962 case DK_NO_DEAD_STRIP:
1963 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1964 case DK_SYMBOL_RESOLVER:
1965 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1966 case DK_PRIVATE_EXTERN:
1967 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1968 case DK_REFERENCE:
1969 return parseDirectiveSymbolAttribute(MCSA_Reference);
1970 case DK_WEAK_DEFINITION:
1971 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1972 case DK_WEAK_REFERENCE:
1973 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1974 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1975 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1976 case DK_COMM:
1977 case DK_COMMON:
1978 return parseDirectiveComm(/*IsLocal=*/false);
1979 case DK_LCOMM:
1980 return parseDirectiveComm(/*IsLocal=*/true);
1981 case DK_ABORT:
1982 return parseDirectiveAbort();
1983 case DK_INCLUDE:
1984 return parseDirectiveInclude();
1985 case DK_INCBIN:
1986 return parseDirectiveIncbin();
1987 case DK_CODE16:
1988 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001989 return TokError(Twine(IDVal) +
1990 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001991 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001992 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001993 case DK_IRP:
1994 return parseDirectiveIrp(IDLoc);
1995 case DK_IRPC:
1996 return parseDirectiveIrpc(IDLoc);
1997 case DK_ENDR:
1998 return parseDirectiveEndr(IDLoc);
1999 case DK_BUNDLE_ALIGN_MODE:
2000 return parseDirectiveBundleAlignMode();
2001 case DK_BUNDLE_LOCK:
2002 return parseDirectiveBundleLock();
2003 case DK_BUNDLE_UNLOCK:
2004 return parseDirectiveBundleUnlock();
2005 case DK_SLEB128:
2006 return parseDirectiveLEB128(true);
2007 case DK_ULEB128:
2008 return parseDirectiveLEB128(false);
2009 case DK_SPACE:
2010 case DK_SKIP:
2011 return parseDirectiveSpace(IDVal);
2012 case DK_FILE:
2013 return parseDirectiveFile(IDLoc);
2014 case DK_LINE:
2015 return parseDirectiveLine();
2016 case DK_LOC:
2017 return parseDirectiveLoc();
2018 case DK_STABS:
2019 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002020 case DK_CV_FILE:
2021 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002022 case DK_CV_FUNC_ID:
2023 return parseDirectiveCVFuncId();
2024 case DK_CV_INLINE_SITE_ID:
2025 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002026 case DK_CV_LOC:
2027 return parseDirectiveCVLoc();
2028 case DK_CV_LINETABLE:
2029 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002030 case DK_CV_INLINE_LINETABLE:
2031 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002032 case DK_CV_DEF_RANGE:
2033 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002034 case DK_CV_STRINGTABLE:
2035 return parseDirectiveCVStringTable();
2036 case DK_CV_FILECHECKSUMS:
2037 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00002038 case DK_CFI_SECTIONS:
2039 return parseDirectiveCFISections();
2040 case DK_CFI_STARTPROC:
2041 return parseDirectiveCFIStartProc();
2042 case DK_CFI_ENDPROC:
2043 return parseDirectiveCFIEndProc();
2044 case DK_CFI_DEF_CFA:
2045 return parseDirectiveCFIDefCfa(IDLoc);
2046 case DK_CFI_DEF_CFA_OFFSET:
2047 return parseDirectiveCFIDefCfaOffset();
2048 case DK_CFI_ADJUST_CFA_OFFSET:
2049 return parseDirectiveCFIAdjustCfaOffset();
2050 case DK_CFI_DEF_CFA_REGISTER:
2051 return parseDirectiveCFIDefCfaRegister(IDLoc);
2052 case DK_CFI_OFFSET:
2053 return parseDirectiveCFIOffset(IDLoc);
2054 case DK_CFI_REL_OFFSET:
2055 return parseDirectiveCFIRelOffset(IDLoc);
2056 case DK_CFI_PERSONALITY:
2057 return parseDirectiveCFIPersonalityOrLsda(true);
2058 case DK_CFI_LSDA:
2059 return parseDirectiveCFIPersonalityOrLsda(false);
2060 case DK_CFI_REMEMBER_STATE:
2061 return parseDirectiveCFIRememberState();
2062 case DK_CFI_RESTORE_STATE:
2063 return parseDirectiveCFIRestoreState();
2064 case DK_CFI_SAME_VALUE:
2065 return parseDirectiveCFISameValue(IDLoc);
2066 case DK_CFI_RESTORE:
2067 return parseDirectiveCFIRestore(IDLoc);
2068 case DK_CFI_ESCAPE:
2069 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002070 case DK_CFI_RETURN_COLUMN:
2071 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002072 case DK_CFI_SIGNAL_FRAME:
2073 return parseDirectiveCFISignalFrame();
2074 case DK_CFI_UNDEFINED:
2075 return parseDirectiveCFIUndefined(IDLoc);
2076 case DK_CFI_REGISTER:
2077 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002078 case DK_CFI_WINDOW_SAVE:
2079 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002080 case DK_MACROS_ON:
2081 case DK_MACROS_OFF:
2082 return parseDirectiveMacrosOnOff(IDVal);
2083 case DK_MACRO:
2084 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002085 case DK_ALTMACRO:
2086 case DK_NOALTMACRO:
2087 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002088 case DK_EXITM:
2089 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002090 case DK_ENDM:
2091 case DK_ENDMACRO:
2092 return parseDirectiveEndMacro(IDVal);
2093 case DK_PURGEM:
2094 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002095 case DK_END:
2096 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002097 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002098 return parseDirectiveError(IDLoc, false);
2099 case DK_ERROR:
2100 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002101 case DK_WARNING:
2102 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002103 case DK_RELOC:
2104 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002105 case DK_DCB:
2106 case DK_DCB_W:
2107 return parseDirectiveDCB(IDVal, 2);
2108 case DK_DCB_B:
2109 return parseDirectiveDCB(IDVal, 1);
2110 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002111 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002112 case DK_DCB_L:
2113 return parseDirectiveDCB(IDVal, 4);
2114 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002115 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002116 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002117 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002118 return TokError(Twine(IDVal) +
2119 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002120 case DK_DS:
2121 case DK_DS_W:
2122 return parseDirectiveDS(IDVal, 2);
2123 case DK_DS_B:
2124 return parseDirectiveDS(IDVal, 1);
2125 case DK_DS_D:
2126 return parseDirectiveDS(IDVal, 8);
2127 case DK_DS_L:
2128 case DK_DS_S:
2129 return parseDirectiveDS(IDVal, 4);
2130 case DK_DS_P:
2131 case DK_DS_X:
2132 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00002133 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002134
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002135 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002136 }
Chris Lattner36e02122009-06-21 20:54:55 +00002137
Chad Rosierc7f552c2013-02-12 21:33:51 +00002138 // __asm _emit or __asm __emit
2139 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2140 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002141 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002142
2143 // __asm align
2144 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002145 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002146
Coby Tayree3847be92017-04-04 17:57:23 +00002147 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002148 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002149 if (checkForValidSection())
2150 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002151
Chris Lattner7cbfa442010-05-19 23:34:33 +00002152 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002153 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002154 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002155 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2156 Info.ParsedOperands);
2157 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002158
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002159 // Dump the parsed representation, if requested.
2160 if (getShowParsedOperands()) {
2161 SmallString<256> Str;
2162 raw_svector_ostream OS(Str);
2163 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002164 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002165 if (i != 0)
2166 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002167 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002168 }
2169 OS << "]";
2170
Jim Grosbach4b905842013-09-20 23:08:21 +00002171 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002172 }
2173
Nirav Dave2364748a2016-09-16 18:30:20 +00002174 // Fail even if ParseInstruction erroneously returns false.
2175 if (hasPendingError() || ParseHadError)
2176 return true;
2177
Oliver Stannard8b273082014-06-19 15:52:37 +00002178 // If we are generating dwarf for the current section then generate a .loc
2179 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002180 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002181 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002182 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002183 unsigned Line;
2184 if (ActiveMacros.empty())
2185 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2186 else
Frederic Riss16238d92015-06-25 21:57:33 +00002187 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2188 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002189
Eli Bendersky88024712013-01-16 19:32:36 +00002190 // If we previously parsed a cpp hash file line comment then make sure the
2191 // current Dwarf File is for the CppHashFilename if not then emit the
2192 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002193 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002194 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002195 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002196 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002197
Jim Grosbach4b905842013-09-20 23:08:21 +00002198 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2199 // cache with the different Loc from the call above we save the last
2200 // info we queried here with SrcMgr.FindLineNumber().
2201 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002202 if (LastQueryIDLoc == CppHashInfo.Loc &&
2203 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002204 CppHashLocLineNo = LastQueryLine;
2205 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002206 CppHashLocLineNo =
2207 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002208 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002209 LastQueryIDLoc = CppHashInfo.Loc;
2210 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002211 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002212 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002213 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002214
Jim Grosbach4b905842013-09-20 23:08:21 +00002215 getStreamer().EmitDwarfLocDirective(
2216 getContext().getGenDwarfFileNumber(), Line, 0,
2217 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2218 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002219 }
2220
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002221 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002222 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002223 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002224 if (getTargetParser().MatchAndEmitInstruction(
2225 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2226 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002227 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002228 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002229 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002230}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002231
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002232// Parse and erase curly braces marking block start/end
2233bool
2234AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2235 // Identify curly brace marking block start/end
2236 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2237 return false;
2238
2239 SMLoc StartLoc = Lexer.getLoc();
2240 Lex(); // Eat the brace
2241 if (Lexer.is(AsmToken::EndOfStatement))
2242 Lex(); // Eat EndOfStatement following the brace
2243
2244 // Erase the block start/end brace from the output asm string
2245 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2246 StartLoc.getPointer());
2247 return true;
2248}
2249
Jim Grosbach4b905842013-09-20 23:08:21 +00002250/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002251/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002252bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002253 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002254 // Lexer only ever emits HashDirective if it fully formed if it's
2255 // done the checking already so this is an internal error.
2256 assert(getTok().is(AsmToken::Integer) &&
2257 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002258 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002259 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002260 assert(getTok().is(AsmToken::String) &&
2261 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002262 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002263 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002264
Kevin Enderby72553612011-09-13 23:45:18 +00002265 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002266 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002267
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002268 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002269 CppHashInfo.Loc = L;
2270 CppHashInfo.Filename = Filename;
2271 CppHashInfo.LineNumber = LineNumber;
2272 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002273 return false;
2274}
2275
Jim Grosbach4b905842013-09-20 23:08:21 +00002276/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002277/// for the Filename and LineNo if any in the diagnostic.
2278void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002279 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002280 raw_ostream &OS = errs();
2281
2282 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002283 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002284 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2285 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002286 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002287
Jim Grosbach4b905842013-09-20 23:08:21 +00002288 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002289 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002290 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2291 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2292 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002293 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2294 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002295 }
2296
Eric Christophera7c32732012-12-18 00:30:54 +00002297 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002298 // manager changed or buffer changed (like in a nested include) then just
2299 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002300 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002301 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002302 if (Parser->SavedDiagHandler)
2303 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2304 else
Craig Topper353eda42014-04-24 06:44:33 +00002305 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002306 return;
2307 }
2308
Eric Christophera7c32732012-12-18 00:30:54 +00002309 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002310 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2311 // for the diagnostic.
2312 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002313
2314 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2315 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002316 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002317 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002318 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002319
Jim Grosbach4b905842013-09-20 23:08:21 +00002320 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2321 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002322 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002323
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002324 if (Parser->SavedDiagHandler)
2325 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2326 else
Craig Topper353eda42014-04-24 06:44:33 +00002327 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002328}
2329
Rafael Espindola2c064482012-08-21 18:29:30 +00002330// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2331// difference being that that function accepts '@' as part of identifiers and
2332// we can't do that. AsmLexer.cpp should probably be changed to handle
2333// '@' as a special case when needed.
2334static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002335 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2336 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002337}
2338
Rafael Espindola34b9c512012-06-03 23:57:14 +00002339bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002340 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002341 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002342 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002343 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002344 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002345 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002346 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002347
Preston Gurd05500642012-09-19 20:36:12 +00002348 // A macro without parameters is handled differently on Darwin:
2349 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002350 while (!Body.empty()) {
2351 // Scan for the next substitution.
2352 std::size_t End = Body.size(), Pos = 0;
2353 for (; Pos != End; ++Pos) {
2354 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002355 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002356 // This macro has no parameters, look for $0, $1, etc.
2357 if (Body[Pos] != '$' || Pos + 1 == End)
2358 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002359
Rafael Espindola1134ab232011-06-05 02:43:45 +00002360 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002361 if (Next == '$' || Next == 'n' ||
2362 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002363 break;
2364 } else {
2365 // This macro has parameters, look for \foo, \bar, etc.
2366 if (Body[Pos] == '\\' && Pos + 1 != End)
2367 break;
2368 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002369 }
2370
2371 // Add the prefix.
2372 OS << Body.slice(0, Pos);
2373
2374 // Check if we reached the end.
2375 if (Pos == End)
2376 break;
2377
Benjamin Kramer513e7442014-02-20 13:36:32 +00002378 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002379 switch (Body[Pos + 1]) {
2380 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002381 case '$':
2382 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002383 break;
2384
Jim Grosbach4b905842013-09-20 23:08:21 +00002385 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002386 case 'n':
2387 OS << A.size();
2388 break;
2389
Jim Grosbach4b905842013-09-20 23:08:21 +00002390 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002391 default: {
2392 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002393 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002394 if (Index >= A.size())
2395 break;
2396
2397 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002398 for (const AsmToken &Token : A[Index])
2399 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002400 break;
2401 }
2402 }
2403 Pos += 2;
2404 } else {
2405 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002406
2407 // Check for the \@ pseudo-variable.
2408 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002409 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002410 else
2411 while (isIdentifierChar(Body[I]) && I + 1 != End)
2412 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002413
Jim Grosbach4b905842013-09-20 23:08:21 +00002414 const char *Begin = Body.data() + Pos + 1;
2415 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002416 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002417
Toma Tabacu217116e2015-04-27 10:50:29 +00002418 if (Argument == "@") {
2419 OS << NumOfMacroInstantiations;
2420 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002421 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002422 for (; Index < NParameters; ++Index)
2423 if (Parameters[Index].Name == Argument)
2424 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002425
Toma Tabacu217116e2015-04-27 10:50:29 +00002426 if (Index == NParameters) {
2427 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2428 Pos += 3;
2429 else {
2430 OS << '\\' << Argument;
2431 Pos = I;
2432 }
2433 } else {
2434 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002435 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002436 // For altmacro mode, you can write '%expr'.
2437 // The prefix '%' evaluates the expression 'expr'
2438 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2439 // Here, we identify the integer token which is the result of the
2440 // absolute expression evaluation and replace it with its string representation.
2441 if ((Lexer.IsaAltMacroMode()) &&
2442 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2443 // Emit an integer value to the buffer.
2444 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002445 // Only Token that was validated as a string and begins with '<'
2446 // is considered altMacroString!!!
2447 else if ((Lexer.IsaAltMacroMode()) &&
2448 (*(Token.getString().begin()) == '<') &&
2449 Token.is(AsmToken::String)) {
2450 std::string Res;
2451 altMacroString(Token.getStringContents(), Res);
2452 OS << Res;
2453 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002454 // We expect no quotes around the string's contents when
2455 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002456 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002457 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002458 else
Craig Topper84008482015-10-10 05:38:14 +00002459 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002460
2461 Pos += 1 + Argument.size();
2462 }
Preston Gurd05500642012-09-19 20:36:12 +00002463 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002464 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002465 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002466 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002467 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002468
Rafael Espindola1134ab232011-06-05 02:43:45 +00002469 return false;
2470}
Daniel Dunbar43235712010-07-18 18:54:11 +00002471
Nico Weber2a8f9222014-07-24 16:29:04 +00002472MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002473 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002474 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002475 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002476
Jim Grosbach4b905842013-09-20 23:08:21 +00002477static bool isOperator(AsmToken::TokenKind kind) {
2478 switch (kind) {
2479 default:
2480 return false;
2481 case AsmToken::Plus:
2482 case AsmToken::Minus:
2483 case AsmToken::Tilde:
2484 case AsmToken::Slash:
2485 case AsmToken::Star:
2486 case AsmToken::Dot:
2487 case AsmToken::Equal:
2488 case AsmToken::EqualEqual:
2489 case AsmToken::Pipe:
2490 case AsmToken::PipePipe:
2491 case AsmToken::Caret:
2492 case AsmToken::Amp:
2493 case AsmToken::AmpAmp:
2494 case AsmToken::Exclaim:
2495 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002496 case AsmToken::Less:
2497 case AsmToken::LessEqual:
2498 case AsmToken::LessLess:
2499 case AsmToken::LessGreater:
2500 case AsmToken::Greater:
2501 case AsmToken::GreaterEqual:
2502 case AsmToken::GreaterGreater:
2503 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002504 }
2505}
2506
David Majnemer16252452014-01-29 00:07:39 +00002507namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002508
David Majnemer16252452014-01-29 00:07:39 +00002509class AsmLexerSkipSpaceRAII {
2510public:
2511 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2512 Lexer.setSkipSpace(SkipSpace);
2513 }
2514
2515 ~AsmLexerSkipSpaceRAII() {
2516 Lexer.setSkipSpace(true);
2517 }
2518
2519private:
2520 AsmLexer &Lexer;
2521};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002522
2523} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002524
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002525bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2526
2527 if (Vararg) {
2528 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2529 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002530 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002531 }
2532 return false;
2533 }
2534
Rafael Espindola768b41c2012-06-15 14:02:34 +00002535 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002536
David Majnemer16252452014-01-29 00:07:39 +00002537 // Darwin doesn't use spaces to delmit arguments.
2538 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002539
Scott Egertona1fa68a2016-02-11 13:48:49 +00002540 bool SpaceEaten;
2541
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002542 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002543 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002544 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002545 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002546
Scott Egertona1fa68a2016-02-11 13:48:49 +00002547 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002548
Scott Egertona1fa68a2016-02-11 13:48:49 +00002549 if (Lexer.is(AsmToken::Comma))
2550 break;
2551
2552 if (Lexer.is(AsmToken::Space)) {
2553 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002554 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002555 }
Preston Gurd05500642012-09-19 20:36:12 +00002556
2557 // Spaces can delimit parameters, but could also be part an expression.
2558 // If the token after a space is an operator, add the token and the next
2559 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002560 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002561 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002562 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002563 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002564
Scott Egertona1fa68a2016-02-11 13:48:49 +00002565 // Whitespace after an operator can be ignored.
2566 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002567 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002568
2569 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002570 }
2571 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002572 if (SpaceEaten)
2573 break;
Preston Gurd05500642012-09-19 20:36:12 +00002574 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002575
Jim Grosbach4b905842013-09-20 23:08:21 +00002576 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002577 // to be able to fill in the remaining default parameter values
2578 if (Lexer.is(AsmToken::EndOfStatement))
2579 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002580
2581 // Adjust the current parentheses level.
2582 if (Lexer.is(AsmToken::LParen))
2583 ++ParenLevel;
2584 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2585 --ParenLevel;
2586
2587 // Append the token to the current argument list.
2588 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002589 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002590 }
Preston Gurd05500642012-09-19 20:36:12 +00002591
Rafael Espindola768b41c2012-06-15 14:02:34 +00002592 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002593 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002594 return false;
2595}
2596
2597// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002598bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002599 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002600 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002601 bool NamedParametersFound = false;
2602 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002603
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002604 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002605 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002606
Rafael Espindola768b41c2012-06-15 14:02:34 +00002607 // Parse two kinds of macro invocations:
2608 // - macros defined without any parameters accept an arbitrary number of them
2609 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002610 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002611 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2612 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002613 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002614 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002615
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002616 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002617 if (parseIdentifier(FA.Name))
2618 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002619
Nirav Dave2364748a2016-09-16 18:30:20 +00002620 if (Lexer.isNot(AsmToken::Equal))
2621 return TokError("expected '=' after formal parameter identifier");
2622
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002623 Lex();
2624
2625 NamedParametersFound = true;
2626 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002627 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002628
Nirav Dave2364748a2016-09-16 18:30:20 +00002629 if (NamedParametersFound && FA.Name.empty())
2630 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002631
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002632 SMLoc StrLoc = Lexer.getLoc();
2633 SMLoc EndLoc;
Michael Zuckerman56704612017-05-01 13:20:12 +00002634 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
Michael Zuckerman56704612017-05-01 13:20:12 +00002635 const MCExpr *AbsoluteExp;
2636 int64_t Value;
2637 /// Eat '%'
2638 Lex();
2639 if (parseExpression(AbsoluteExp, EndLoc))
2640 return false;
2641 if (!AbsoluteExp->evaluateAsAbsolute(Value))
2642 return Error(StrLoc, "expected absolute expression");
2643 const char *StrChar = StrLoc.getPointer();
2644 const char *EndChar = EndLoc.getPointer();
2645 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2646 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002647 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2648 isAltmacroString(StrLoc, EndLoc)) {
2649 const char *StrChar = StrLoc.getPointer();
2650 const char *EndChar = EndLoc.getPointer();
2651 jumpToLoc(EndLoc, CurBuffer);
2652 /// Eat from '<' to '>'
2653 Lex();
2654 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2655 FA.Value.push_back(newToken);
2656 } else if(parseMacroArgument(FA.Value, Vararg))
Michael Zuckerman56704612017-05-01 13:20:12 +00002657 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002658
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002659 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002660 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002661 unsigned FAI = 0;
2662 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002663 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002664 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002665
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002666 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002667 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002668 return Error(IDLoc, "parameter named '" + FA.Name +
2669 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002670 }
2671 PI = FAI;
2672 }
2673
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002674 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002675 if (A.size() <= PI)
2676 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002677 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002678
2679 if (FALocs.size() <= PI)
2680 FALocs.resize(PI + 1);
2681
2682 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002683 }
Jim Grosbach206661622012-07-30 22:44:17 +00002684
Preston Gurd242ed3152012-09-19 20:29:04 +00002685 // At the end of the statement, fill in remaining arguments that have
2686 // default values. If there aren't any, then the next argument is
2687 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002688 if (Lexer.is(AsmToken::EndOfStatement)) {
2689 bool Failure = false;
2690 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2691 if (A[FAI].empty()) {
2692 if (M->Parameters[FAI].Required) {
2693 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2694 "missing value for required parameter "
2695 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2696 Failure = true;
2697 }
2698
2699 if (!M->Parameters[FAI].Value.empty())
2700 A[FAI] = M->Parameters[FAI].Value;
2701 }
2702 }
2703 return Failure;
2704 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002705
2706 if (Lexer.is(AsmToken::Comma))
2707 Lex();
2708 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002709
2710 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002711}
2712
Jim Grosbach4b905842013-09-20 23:08:21 +00002713const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002714 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2715 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002716}
2717
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002718void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2719 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002720}
2721
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002722void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002723
Jim Grosbach4b905842013-09-20 23:08:21 +00002724bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002725 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2726 // eliminate this, although we should protect against infinite loops.
2727 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2728 if (ActiveMacros.size() == MaxNestingDepth) {
2729 std::ostringstream MaxNestingDepthError;
2730 MaxNestingDepthError << "macros cannot be nested more than "
2731 << MaxNestingDepth << " levels deep."
2732 << " Use -asm-macro-max-nesting-depth to increase "
2733 "this limit.";
2734 return TokError(MaxNestingDepthError.str());
2735 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002736
Eli Bendersky38274122013-01-14 23:22:36 +00002737 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002738 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002739 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002740
Rafael Espindola1134ab232011-06-05 02:43:45 +00002741 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2742 // to hold the macro body with substitutions.
2743 SmallString<256> Buf;
2744 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002745 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002746
Toma Tabacu217116e2015-04-27 10:50:29 +00002747 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002748 return true;
2749
Eli Bendersky38274122013-01-14 23:22:36 +00002750 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002751 // instantiation.
2752 OS << ".endmacro\n";
2753
Rafael Espindola3560ff22014-08-27 20:03:13 +00002754 std::unique_ptr<MemoryBuffer> Instantiation =
2755 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002756
Daniel Dunbar43235712010-07-18 18:54:11 +00002757 // Create the macro instantiation object and add to the current macro
2758 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002759 MacroInstantiation *MI = new MacroInstantiation(
2760 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002761 ActiveMacros.push_back(MI);
2762
Toma Tabacu217116e2015-04-27 10:50:29 +00002763 ++NumOfMacroInstantiations;
2764
Daniel Dunbar43235712010-07-18 18:54:11 +00002765 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002766 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002767 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002768 Lex();
2769
2770 return false;
2771}
2772
Jim Grosbach4b905842013-09-20 23:08:21 +00002773void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002774 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002775 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002776 Lex();
2777
2778 // Pop the instantiation entry.
2779 delete ActiveMacros.back();
2780 ActiveMacros.pop_back();
2781}
2782
Jim Grosbach4b905842013-09-20 23:08:21 +00002783bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002784 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002785 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002786 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002787 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2788 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002789 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002790
Pete Cooper80d21cb2015-06-22 19:35:57 +00002791 if (!Sym) {
2792 // In the case where we parse an expression starting with a '.', we will
2793 // not generate an error, nor will we create a symbol. In this case we
2794 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002795 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002796 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002797
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002798 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002799 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002800 if (NoDeadStrip)
2801 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2802
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002803 return false;
2804}
2805
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002806/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002807/// ::= identifier
2808/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002809bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002810 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002811 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2812 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002813 // handle this as a context dependent token, instead we detect adjacent tokens
2814 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002815 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2816 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002817
Hans Wennborgce69d772013-10-18 20:46:28 +00002818 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002819
2820 AsmToken Buf[1];
2821 Lexer.peekTokens(Buf, false);
2822
2823 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002824 return true;
2825
Hans Wennborgce69d772013-10-18 20:46:28 +00002826 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002827 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002828 return true;
2829
Nirav Daved0463322016-10-12 13:58:07 +00002830 // eat $ or @
2831 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002832 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002833 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002834 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002835 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002836 return false;
2837 }
2838
Jim Grosbach4b905842013-09-20 23:08:21 +00002839 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002840 return true;
2841
Sean Callanan936b0d32010-01-19 21:44:56 +00002842 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002843
Sean Callanan686ed8d2010-01-19 20:22:31 +00002844 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002845
2846 return false;
2847}
2848
Jim Grosbach4b905842013-09-20 23:08:21 +00002849/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002850/// ::= .equ identifier ',' expression
2851/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002852/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002853bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002854 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002855 if (check(parseIdentifier(Name), "expected identifier") ||
2856 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2857 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2858 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002859}
2860
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002861bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002862 if (check(getTok().isNot(AsmToken::String), "expected string"))
2863 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002864
2865 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002866 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002867 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2868 if (Str[i] != '\\') {
2869 Data += Str[i];
2870 continue;
2871 }
2872
2873 // Recognize escaped characters. Note that this escape semantics currently
2874 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2875 ++i;
2876 if (i == e)
2877 return TokError("unexpected backslash at end of string");
2878
2879 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002880 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002881 // Consume up to three octal characters.
2882 unsigned Value = Str[i] - '0';
2883
Jim Grosbach4b905842013-09-20 23:08:21 +00002884 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002885 ++i;
2886 Value = Value * 8 + (Str[i] - '0');
2887
Jim Grosbach4b905842013-09-20 23:08:21 +00002888 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002889 ++i;
2890 Value = Value * 8 + (Str[i] - '0');
2891 }
2892 }
2893
2894 if (Value > 255)
2895 return TokError("invalid octal escape sequence (out of range)");
2896
Jim Grosbach4b905842013-09-20 23:08:21 +00002897 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002898 continue;
2899 }
2900
2901 // Otherwise recognize individual escapes.
2902 switch (Str[i]) {
2903 default:
2904 // Just reject invalid escape sequences for now.
2905 return TokError("invalid escape sequence (unrecognized character)");
2906
2907 case 'b': Data += '\b'; break;
2908 case 'f': Data += '\f'; break;
2909 case 'n': Data += '\n'; break;
2910 case 'r': Data += '\r'; break;
2911 case 't': Data += '\t'; break;
2912 case '"': Data += '"'; break;
2913 case '\\': Data += '\\'; break;
2914 }
2915 }
2916
Nirav Davea645433c2016-07-18 15:24:03 +00002917 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002918 return false;
2919}
2920
Jim Grosbach4b905842013-09-20 23:08:21 +00002921/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002922/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002923bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002924 auto parseOp = [&]() -> bool {
2925 std::string Data;
2926 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002927 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002928 getStreamer().EmitBytes(Data);
2929 if (ZeroTerminated)
2930 getStreamer().EmitBytes(StringRef("\0", 1));
2931 return false;
2932 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002933
Nirav Dave1a9044b2016-10-24 14:35:29 +00002934 if (parseMany(parseOp))
2935 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002936 return false;
2937}
2938
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002939/// parseDirectiveReloc
2940/// ::= .reloc expression , identifier [ , expression ]
2941bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2942 const MCExpr *Offset;
2943 const MCExpr *Expr = nullptr;
2944
2945 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002946 int64_t OffsetValue;
2947 // We can only deal with constant expressions at the moment.
2948
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002949 if (parseExpression(Offset))
2950 return true;
2951
Nirav Davea645433c2016-07-18 15:24:03 +00002952 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2953 "expression is not a constant value") ||
2954 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2955 parseToken(AsmToken::Comma, "expected comma") ||
2956 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2957 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002958
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002959 SMLoc NameLoc = Lexer.getTok().getLoc();
2960 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002961 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002962
2963 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002964 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002965 SMLoc ExprLoc = Lexer.getLoc();
2966 if (parseExpression(Expr))
2967 return true;
2968
2969 MCValue Value;
2970 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2971 return Error(ExprLoc, "expression must be relocatable");
2972 }
2973
Nirav Davea645433c2016-07-18 15:24:03 +00002974 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002975 "unexpected token in .reloc directive"))
2976 return true;
2977
2978 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2979 return Error(NameLoc, "unknown relocation name");
2980
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002981 return false;
2982}
2983
Jim Grosbach4b905842013-09-20 23:08:21 +00002984/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002985/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002986bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2987 auto parseOp = [&]() -> bool {
2988 const MCExpr *Value;
2989 SMLoc ExprLoc = getLexer().getLoc();
2990 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002991 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002992 // Special case constant expressions to match code generator.
2993 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2994 assert(Size <= 8 && "Invalid size");
2995 uint64_t IntValue = MCE->getValue();
2996 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2997 return Error(ExprLoc, "out of range literal value");
2998 getStreamer().EmitIntValue(IntValue, Size);
2999 } else
3000 getStreamer().EmitValue(Value, Size, ExprLoc);
3001 return false;
3002 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00003003
Nirav Dave1a9044b2016-10-24 14:35:29 +00003004 if (parseMany(parseOp))
3005 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00003006 return false;
3007}
3008
David Woodhoused6de0d92014-02-01 16:20:59 +00003009/// ParseDirectiveOctaValue
3010/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003011
3012bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3013 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00003014 if (checkForValidSection())
3015 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003016 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
3017 return TokError("unknown token in expression");
3018 SMLoc ExprLoc = getTok().getLoc();
3019 APInt IntValue = getTok().getAPIntVal();
3020 uint64_t hi, lo;
3021 Lex();
3022 if (!IntValue.isIntN(128))
3023 return Error(ExprLoc, "out of range literal value");
3024 if (!IntValue.isIntN(64)) {
3025 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3026 lo = IntValue.getLoBits(64).getZExtValue();
3027 } else {
3028 hi = 0;
3029 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00003030 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003031 if (MAI.isLittleEndian()) {
3032 getStreamer().EmitIntValue(lo, 8);
3033 getStreamer().EmitIntValue(hi, 8);
3034 } else {
3035 getStreamer().EmitIntValue(hi, 8);
3036 getStreamer().EmitIntValue(lo, 8);
3037 }
3038 return false;
3039 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003040
Nirav Dave1a9044b2016-10-24 14:35:29 +00003041 if (parseMany(parseOp))
3042 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003043 return false;
3044}
3045
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003046bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3047 // We don't truly support arithmetic on floating point expressions, so we
3048 // have to manually parse unary prefixes.
3049 bool IsNeg = false;
3050 if (getLexer().is(AsmToken::Minus)) {
3051 Lexer.Lex();
3052 IsNeg = true;
3053 } else if (getLexer().is(AsmToken::Plus))
3054 Lexer.Lex();
3055
3056 if (Lexer.is(AsmToken::Error))
3057 return TokError(Lexer.getErr());
3058 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3059 Lexer.isNot(AsmToken::Identifier))
3060 return TokError("unexpected token in directive");
3061
3062 // Convert to an APFloat.
3063 APFloat Value(Semantics);
3064 StringRef IDVal = getTok().getString();
3065 if (getLexer().is(AsmToken::Identifier)) {
3066 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3067 Value = APFloat::getInf(Semantics);
3068 else if (!IDVal.compare_lower("nan"))
3069 Value = APFloat::getNaN(Semantics, false, ~0);
3070 else
3071 return TokError("invalid floating point literal");
3072 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3073 APFloat::opInvalidOp)
3074 return TokError("invalid floating point literal");
3075 if (IsNeg)
3076 Value.changeSign();
3077
3078 // Consume the numeric token.
3079 Lex();
3080
3081 Res = Value.bitcastToAPInt();
3082
3083 return false;
3084}
3085
Jim Grosbach4b905842013-09-20 23:08:21 +00003086/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003087/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003088bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3089 const fltSemantics &Semantics) {
3090 auto parseOp = [&]() -> bool {
3091 APInt AsInt;
3092 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003093 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003094 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3095 AsInt.getBitWidth() / 8);
3096 return false;
3097 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003098
Nirav Dave1a9044b2016-10-24 14:35:29 +00003099 if (parseMany(parseOp))
3100 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003101 return false;
3102}
3103
Jim Grosbach4b905842013-09-20 23:08:21 +00003104/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003105/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003106bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003107 SMLoc NumBytesLoc = Lexer.getLoc();
3108 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003109 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003110 return true;
3111
Rafael Espindolab91bac62010-10-05 19:42:57 +00003112 int64_t Val = 0;
3113 if (getLexer().is(AsmToken::Comma)) {
3114 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003115 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003116 return true;
3117 }
3118
Nirav Davea645433c2016-07-18 15:24:03 +00003119 if (parseToken(AsmToken::EndOfStatement,
3120 "unexpected token in '.zero' directive"))
3121 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003122 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003123
3124 return false;
3125}
3126
Jim Grosbach4b905842013-09-20 23:08:21 +00003127/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003128/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003129bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003130 SMLoc NumValuesLoc = Lexer.getLoc();
3131 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003132 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003133 return true;
3134
Roman Divackye33098f2013-09-24 17:44:41 +00003135 int64_t FillSize = 1;
3136 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003137
David Majnemer522d3db2014-02-01 07:19:38 +00003138 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003139
Nirav Dave1a9044b2016-10-24 14:35:29 +00003140 if (parseOptionalToken(AsmToken::Comma)) {
3141 SizeLoc = getTok().getLoc();
3142 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003143 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003144 if (parseOptionalToken(AsmToken::Comma)) {
3145 ExprLoc = getTok().getLoc();
3146 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003147 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003148 }
3149 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003150 if (parseToken(AsmToken::EndOfStatement,
3151 "unexpected token in '.fill' directive"))
3152 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003153
David Majnemer522d3db2014-02-01 07:19:38 +00003154 if (FillSize < 0) {
3155 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003156 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003157 }
3158 if (FillSize > 8) {
3159 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3160 FillSize = 8;
3161 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003162
David Majnemer522d3db2014-02-01 07:19:38 +00003163 if (!isUInt<32>(FillExpr) && FillSize > 4)
3164 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3165
Petr Hosek67a94a72016-05-28 05:57:48 +00003166 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003167
3168 return false;
3169}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003170
Jim Grosbach4b905842013-09-20 23:08:21 +00003171/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003172/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003173bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003174 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003175 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003176 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003177 return true;
3178
3179 // Parse optional fill expression.
3180 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003181 if (parseOptionalToken(AsmToken::Comma))
3182 if (parseAbsoluteExpression(FillExpr))
3183 return addErrorSuffix(" in '.org' directive");
3184 if (parseToken(AsmToken::EndOfStatement))
3185 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003186
Oliver Stannard268f42f2016-12-14 10:43:58 +00003187 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003188 return false;
3189}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003190
Jim Grosbach4b905842013-09-20 23:08:21 +00003191/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003192/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003193bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003194 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003195 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003196 SMLoc MaxBytesLoc;
3197 bool HasFillExpr = false;
3198 int64_t FillExpr = 0;
3199 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003200
3201 auto parseAlign = [&]() -> bool {
3202 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003203 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003204 if (parseOptionalToken(AsmToken::Comma)) {
3205 // The fill expression can be omitted while specifying a maximum number of
3206 // alignment bytes, e.g:
3207 // .align 3,,4
3208 if (getTok().isNot(AsmToken::Comma)) {
3209 HasFillExpr = true;
3210 if (parseAbsoluteExpression(FillExpr))
3211 return true;
3212 }
3213 if (parseOptionalToken(AsmToken::Comma))
3214 if (parseTokenLoc(MaxBytesLoc) ||
3215 parseAbsoluteExpression(MaxBytesToFill))
3216 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003217 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003218 return parseToken(AsmToken::EndOfStatement);
3219 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003220
Nirav Dave1a9044b2016-10-24 14:35:29 +00003221 if (parseAlign())
3222 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003223
Nirav Dave2364748a2016-09-16 18:30:20 +00003224 // Always emit an alignment here even if we thrown an error.
3225 bool ReturnVal = false;
3226
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003227 // Compute alignment in bytes.
3228 if (IsPow2) {
3229 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003230 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003231 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003232 Alignment = 31;
3233 }
3234
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003235 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003236 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003237 // Reject alignments that aren't either a power of two or zero,
3238 // for gas compatibility. Alignment of zero is silently rounded
3239 // up to one.
3240 if (Alignment == 0)
3241 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003242 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003243 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003244 }
3245
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003246 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003247 if (MaxBytesLoc.isValid()) {
3248 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003249 ReturnVal |= Error(MaxBytesLoc,
3250 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003251 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003252 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003253 }
3254
3255 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003256 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003257 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003258 MaxBytesToFill = 0;
3259 }
3260 }
3261
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003262 // Check whether we should use optimal code alignment for this .align
3263 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003264 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003265 assert(Section && "must have section to emit alignment");
3266 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003267 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3268 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003269 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003270 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003271 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003272 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3273 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003274 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003275
Nirav Dave2364748a2016-09-16 18:30:20 +00003276 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003277}
3278
Jim Grosbach4b905842013-09-20 23:08:21 +00003279/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003280/// ::= .file [number] filename
3281/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003282bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003283 // FIXME: I'm not sure what this is.
3284 int64_t FileNumber = -1;
3285 SMLoc FileNumberLoc = getLexer().getLoc();
3286 if (getLexer().is(AsmToken::Integer)) {
3287 FileNumber = getTok().getIntVal();
3288 Lex();
3289
3290 if (FileNumber < 1)
3291 return TokError("file number less than one");
3292 }
3293
Nirav Davea645433c2016-07-18 15:24:03 +00003294 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003295
3296 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003297 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003298 if (check(getTok().isNot(AsmToken::String),
3299 "unexpected token in '.file' directive") ||
3300 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003301 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003302
3303 StringRef Directory;
3304 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003305 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003306 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003307 if (check(FileNumber == -1,
3308 "explicit path specified, but no file number") ||
3309 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003310 return true;
3311 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003312 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003313 } else {
3314 Filename = Path;
3315 }
3316
Nirav Davea645433c2016-07-18 15:24:03 +00003317 if (parseToken(AsmToken::EndOfStatement,
3318 "unexpected token in '.file' directive"))
3319 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003320
3321 if (FileNumber == -1)
3322 getStreamer().EmitFileDirective(Filename);
3323 else {
David Blaikie22748082016-05-26 00:22:26 +00003324 // If there is -g option as well as debug info from directive file,
3325 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003326 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003327 getContext().setGenDwarfForAssembly(false);
3328 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003329 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003330 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003331 }
3332
3333 return false;
3334}
3335
Jim Grosbach4b905842013-09-20 23:08:21 +00003336/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003337/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003338bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003339 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003340 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003341 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3342 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003343 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003344 // FIXME: Do something with the .line.
3345 }
Nirav Davea645433c2016-07-18 15:24:03 +00003346 if (parseToken(AsmToken::EndOfStatement,
3347 "unexpected token in '.line' directive"))
3348 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003349
3350 return false;
3351}
3352
Jim Grosbach4b905842013-09-20 23:08:21 +00003353/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003354/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3355/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3356/// The first number is a file number, must have been previously assigned with
3357/// a .file directive, the second number is the line number and optionally the
3358/// third number is a column position (zero if not specified). The remaining
3359/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003360bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003361 int64_t FileNumber = 0, LineNumber = 0;
3362 SMLoc Loc = getTok().getLoc();
3363 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3364 check(FileNumber < 1, Loc,
3365 "file number less than one in '.loc' directive") ||
3366 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3367 "unassigned file number in '.loc' directive"))
3368 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003369
Nirav Davea645433c2016-07-18 15:24:03 +00003370 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003371 if (getLexer().is(AsmToken::Integer)) {
3372 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003373 if (LineNumber < 0)
3374 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003375 Lex();
3376 }
3377
3378 int64_t ColumnPos = 0;
3379 if (getLexer().is(AsmToken::Integer)) {
3380 ColumnPos = getTok().getIntVal();
3381 if (ColumnPos < 0)
3382 return TokError("column position less than zero in '.loc' directive");
3383 Lex();
3384 }
3385
3386 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3387 unsigned Isa = 0;
3388 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003389
Nirav Dave1a9044b2016-10-24 14:35:29 +00003390 auto parseLocOp = [&]() -> bool {
3391 StringRef Name;
3392 SMLoc Loc = getTok().getLoc();
3393 if (parseIdentifier(Name))
3394 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003395
Nirav Dave1a9044b2016-10-24 14:35:29 +00003396 if (Name == "basic_block")
3397 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3398 else if (Name == "prologue_end")
3399 Flags |= DWARF2_FLAG_PROLOGUE_END;
3400 else if (Name == "epilogue_begin")
3401 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3402 else if (Name == "is_stmt") {
3403 Loc = getTok().getLoc();
3404 const MCExpr *Value;
3405 if (parseExpression(Value))
3406 return true;
3407 // The expression must be the constant 0 or 1.
3408 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3409 int Value = MCE->getValue();
3410 if (Value == 0)
3411 Flags &= ~DWARF2_FLAG_IS_STMT;
3412 else if (Value == 1)
3413 Flags |= DWARF2_FLAG_IS_STMT;
3414 else
3415 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003416 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003417 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003418 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003419 } else if (Name == "isa") {
3420 Loc = getTok().getLoc();
3421 const MCExpr *Value;
3422 if (parseExpression(Value))
3423 return true;
3424 // The expression must be a constant greater or equal to 0.
3425 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3426 int Value = MCE->getValue();
3427 if (Value < 0)
3428 return Error(Loc, "isa number less than zero");
3429 Isa = Value;
3430 } else {
3431 return Error(Loc, "isa number not a constant value");
3432 }
3433 } else if (Name == "discriminator") {
3434 if (parseAbsoluteExpression(Discriminator))
3435 return true;
3436 } else {
3437 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003438 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003439 return false;
3440 };
3441
Nirav Davee2369aa2016-10-26 17:28:58 +00003442 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003443 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003444
3445 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3446 Isa, Discriminator, StringRef());
3447
3448 return false;
3449}
3450
Jim Grosbach4b905842013-09-20 23:08:21 +00003451/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003452/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003453bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003454 return TokError("unsupported directive '.stabs'");
3455}
3456
Reid Kleckner2214ed82016-01-29 00:49:42 +00003457/// parseDirectiveCVFile
3458/// ::= .cv_file number filename
3459bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003460 SMLoc FileNumberLoc = getTok().getLoc();
3461 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003462 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003463
3464 if (parseIntToken(FileNumber,
3465 "expected file number in '.cv_file' directive") ||
3466 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3467 check(getTok().isNot(AsmToken::String),
3468 "unexpected token in '.cv_file' directive") ||
3469 // Usually directory and filename are together, otherwise just
3470 // directory. Allow the strings to have escaped octal character sequence.
3471 parseEscapedString(Filename) ||
3472 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003473 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003474 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003475
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003476 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003477 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003478
3479 return false;
3480}
3481
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003482bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3483 StringRef DirectiveName) {
3484 SMLoc Loc;
3485 return parseTokenLoc(Loc) ||
3486 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3487 "' directive") ||
3488 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3489 "expected function id within range [0, UINT_MAX)");
3490}
3491
3492bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3493 SMLoc Loc;
3494 return parseTokenLoc(Loc) ||
3495 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3496 "' directive") ||
3497 check(FileNumber < 1, Loc, "file number less than one in '" +
3498 DirectiveName + "' directive") ||
3499 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3500 "unassigned file number in '" + DirectiveName + "' directive");
3501}
3502
3503/// parseDirectiveCVFuncId
3504/// ::= .cv_func_id FunctionId
3505///
3506/// Introduces a function ID that can be used with .cv_loc.
3507bool AsmParser::parseDirectiveCVFuncId() {
3508 SMLoc FunctionIdLoc = getTok().getLoc();
3509 int64_t FunctionId;
3510
3511 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3512 parseToken(AsmToken::EndOfStatement,
3513 "unexpected token in '.cv_func_id' directive"))
3514 return true;
3515
3516 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003517 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003518
3519 return false;
3520}
3521
3522/// parseDirectiveCVInlineSiteId
3523/// ::= .cv_inline_site_id FunctionId
3524/// "within" IAFunc
3525/// "inlined_at" IAFile IALine [IACol]
3526///
3527/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3528/// at" source location information for use in the line table of the caller,
3529/// whether the caller is a real function or another inlined call site.
3530bool AsmParser::parseDirectiveCVInlineSiteId() {
3531 SMLoc FunctionIdLoc = getTok().getLoc();
3532 int64_t FunctionId;
3533 int64_t IAFunc;
3534 int64_t IAFile;
3535 int64_t IALine;
3536 int64_t IACol = 0;
3537
3538 // FunctionId
3539 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3540 return true;
3541
3542 // "within"
3543 if (check((getLexer().isNot(AsmToken::Identifier) ||
3544 getTok().getIdentifier() != "within"),
3545 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3546 return true;
3547 Lex();
3548
3549 // IAFunc
3550 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3551 return true;
3552
3553 // "inlined_at"
3554 if (check((getLexer().isNot(AsmToken::Identifier) ||
3555 getTok().getIdentifier() != "inlined_at"),
3556 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3557 "directive") )
3558 return true;
3559 Lex();
3560
3561 // IAFile IALine
3562 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3563 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3564 return true;
3565
3566 // [IACol]
3567 if (getLexer().is(AsmToken::Integer)) {
3568 IACol = getTok().getIntVal();
3569 Lex();
3570 }
3571
3572 if (parseToken(AsmToken::EndOfStatement,
3573 "unexpected token in '.cv_inline_site_id' directive"))
3574 return true;
3575
3576 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3577 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003578 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003579
3580 return false;
3581}
3582
Reid Kleckner2214ed82016-01-29 00:49:42 +00003583/// parseDirectiveCVLoc
3584/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3585/// [is_stmt VALUE]
3586/// The first number is a file number, must have been previously assigned with
3587/// a .file directive, the second number is the line number and optionally the
3588/// third number is a column position (zero if not specified). The remaining
3589/// optional items are .loc sub-directives.
3590bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003591 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003592 SMLoc Loc;
3593 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003594 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3595 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003596 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003597
3598 int64_t LineNumber = 0;
3599 if (getLexer().is(AsmToken::Integer)) {
3600 LineNumber = getTok().getIntVal();
3601 if (LineNumber < 0)
3602 return TokError("line number less than zero in '.cv_loc' directive");
3603 Lex();
3604 }
3605
3606 int64_t ColumnPos = 0;
3607 if (getLexer().is(AsmToken::Integer)) {
3608 ColumnPos = getTok().getIntVal();
3609 if (ColumnPos < 0)
3610 return TokError("column position less than zero in '.cv_loc' directive");
3611 Lex();
3612 }
3613
3614 bool PrologueEnd = false;
3615 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003616
3617 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003618 StringRef Name;
3619 SMLoc Loc = getTok().getLoc();
3620 if (parseIdentifier(Name))
3621 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003622 if (Name == "prologue_end")
3623 PrologueEnd = true;
3624 else if (Name == "is_stmt") {
3625 Loc = getTok().getLoc();
3626 const MCExpr *Value;
3627 if (parseExpression(Value))
3628 return true;
3629 // The expression must be the constant 0 or 1.
3630 IsStmt = ~0ULL;
3631 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3632 IsStmt = MCE->getValue();
3633
3634 if (IsStmt > 1)
3635 return Error(Loc, "is_stmt value not 0 or 1");
3636 } else {
3637 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3638 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003639 return false;
3640 };
3641
3642 if (parseMany(parseOp, false /*hasComma*/))
3643 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003644
3645 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003646 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3647 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003648 return false;
3649}
3650
3651/// parseDirectiveCVLinetable
3652/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3653bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003654 int64_t FunctionId;
3655 StringRef FnStartName, FnEndName;
3656 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003657 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003658 parseToken(AsmToken::Comma,
3659 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003660 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3661 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003662 parseToken(AsmToken::Comma,
3663 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003664 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3665 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003666 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003667
3668 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3669 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3670
3671 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3672 return false;
3673}
3674
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003675/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003676/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003677bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003678 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3679 StringRef FnStartName, FnEndName;
3680 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003681 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003682 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003683 parseIntToken(
3684 SourceFileId,
3685 "expected SourceField in '.cv_inline_linetable' directive") ||
3686 check(SourceFileId <= 0, Loc,
3687 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003688 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003689 parseIntToken(
3690 SourceLineNum,
3691 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3692 check(SourceLineNum < 0, Loc,
3693 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003694 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3695 "expected identifier in directive") ||
3696 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3697 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003698 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003699
Nirav Davea645433c2016-07-18 15:24:03 +00003700 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3701 return true;
3702
3703 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3704 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003705 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3706 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003707 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003708 return false;
3709}
3710
David Majnemer408b5e62016-02-05 01:55:49 +00003711/// parseDirectiveCVDefRange
3712/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3713bool AsmParser::parseDirectiveCVDefRange() {
3714 SMLoc Loc;
3715 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3716 while (getLexer().is(AsmToken::Identifier)) {
3717 Loc = getLexer().getLoc();
3718 StringRef GapStartName;
3719 if (parseIdentifier(GapStartName))
3720 return Error(Loc, "expected identifier in directive");
3721 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3722
3723 Loc = getLexer().getLoc();
3724 StringRef GapEndName;
3725 if (parseIdentifier(GapEndName))
3726 return Error(Loc, "expected identifier in directive");
3727 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3728
3729 Ranges.push_back({GapStartSym, GapEndSym});
3730 }
3731
David Majnemer408b5e62016-02-05 01:55:49 +00003732 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003733 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3734 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003735 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003736
3737 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3738 return false;
3739}
3740
Reid Kleckner2214ed82016-01-29 00:49:42 +00003741/// parseDirectiveCVStringTable
3742/// ::= .cv_stringtable
3743bool AsmParser::parseDirectiveCVStringTable() {
3744 getStreamer().EmitCVStringTableDirective();
3745 return false;
3746}
3747
3748/// parseDirectiveCVFileChecksums
3749/// ::= .cv_filechecksums
3750bool AsmParser::parseDirectiveCVFileChecksums() {
3751 getStreamer().EmitCVFileChecksumsDirective();
3752 return false;
3753}
3754
Jim Grosbach4b905842013-09-20 23:08:21 +00003755/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003756/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003757bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003758 StringRef Name;
3759 bool EH = false;
3760 bool Debug = false;
3761
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003762 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003763 return TokError("Expected an identifier");
3764
3765 if (Name == ".eh_frame")
3766 EH = true;
3767 else if (Name == ".debug_frame")
3768 Debug = true;
3769
3770 if (getLexer().is(AsmToken::Comma)) {
3771 Lex();
3772
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003773 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003774 return TokError("Expected an identifier");
3775
3776 if (Name == ".eh_frame")
3777 EH = true;
3778 else if (Name == ".debug_frame")
3779 Debug = true;
3780 }
3781
3782 getStreamer().EmitCFISections(EH, Debug);
3783 return false;
3784}
3785
Jim Grosbach4b905842013-09-20 23:08:21 +00003786/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003787/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003788bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003789 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003790 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3791 if (check(parseIdentifier(Simple) || Simple != "simple",
3792 "unexpected token") ||
3793 parseToken(AsmToken::EndOfStatement))
3794 return addErrorSuffix(" in '.cfi_startproc' directive");
3795 }
Nirav Davea645433c2016-07-18 15:24:03 +00003796
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003797 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003798 return false;
3799}
3800
Jim Grosbach4b905842013-09-20 23:08:21 +00003801/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003802/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003803bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003804 getStreamer().EmitCFIEndProc();
3805 return false;
3806}
3807
Jim Grosbach4b905842013-09-20 23:08:21 +00003808/// \brief parse register name or number.
3809bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003810 SMLoc DirectiveLoc) {
3811 unsigned RegNo;
3812
3813 if (getLexer().isNot(AsmToken::Integer)) {
3814 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3815 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003816 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003817 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003818 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003819
3820 return false;
3821}
3822
Jim Grosbach4b905842013-09-20 23:08:21 +00003823/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003824/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003825bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003826 int64_t Register = 0, Offset = 0;
3827 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3828 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3829 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003830 return true;
3831
3832 getStreamer().EmitCFIDefCfa(Register, Offset);
3833 return false;
3834}
3835
Jim Grosbach4b905842013-09-20 23:08:21 +00003836/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003837/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003838bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003839 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003840 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003841 return true;
3842
3843 getStreamer().EmitCFIDefCfaOffset(Offset);
3844 return false;
3845}
3846
Jim Grosbach4b905842013-09-20 23:08:21 +00003847/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003848/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003849bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003850 int64_t Register1 = 0, Register2 = 0;
3851 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3852 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3853 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003854 return true;
3855
3856 getStreamer().EmitCFIRegister(Register1, Register2);
3857 return false;
3858}
3859
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003860/// parseDirectiveCFIWindowSave
3861/// ::= .cfi_window_save
3862bool AsmParser::parseDirectiveCFIWindowSave() {
3863 getStreamer().EmitCFIWindowSave();
3864 return false;
3865}
3866
Jim Grosbach4b905842013-09-20 23:08:21 +00003867/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003868/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003869bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003870 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003871 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003872 return true;
3873
3874 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3875 return false;
3876}
3877
Jim Grosbach4b905842013-09-20 23:08:21 +00003878/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003879/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003880bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003881 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003882 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003883 return true;
3884
3885 getStreamer().EmitCFIDefCfaRegister(Register);
3886 return false;
3887}
3888
Jim Grosbach4b905842013-09-20 23:08:21 +00003889/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003890/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003891bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003892 int64_t Register = 0;
3893 int64_t Offset = 0;
3894
Nirav Davea645433c2016-07-18 15:24:03 +00003895 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3896 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3897 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003898 return true;
3899
3900 getStreamer().EmitCFIOffset(Register, Offset);
3901 return false;
3902}
3903
Jim Grosbach4b905842013-09-20 23:08:21 +00003904/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003905/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003906bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003907 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003908
Nirav Davea645433c2016-07-18 15:24:03 +00003909 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3910 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3911 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003912 return true;
3913
3914 getStreamer().EmitCFIRelOffset(Register, Offset);
3915 return false;
3916}
3917
3918static bool isValidEncoding(int64_t Encoding) {
3919 if (Encoding & ~0xff)
3920 return false;
3921
3922 if (Encoding == dwarf::DW_EH_PE_omit)
3923 return true;
3924
3925 const unsigned Format = Encoding & 0xf;
3926 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3927 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3928 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3929 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3930 return false;
3931
3932 const unsigned Application = Encoding & 0x70;
3933 if (Application != dwarf::DW_EH_PE_absptr &&
3934 Application != dwarf::DW_EH_PE_pcrel)
3935 return false;
3936
3937 return true;
3938}
3939
Jim Grosbach4b905842013-09-20 23:08:21 +00003940/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003941/// IsPersonality true for cfi_personality, false for cfi_lsda
3942/// ::= .cfi_personality encoding, [symbol_name]
3943/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003944bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003945 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003946 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003947 return true;
3948 if (Encoding == dwarf::DW_EH_PE_omit)
3949 return false;
3950
Eli Bendersky17233942013-01-15 22:59:42 +00003951 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003952 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3953 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3954 check(parseIdentifier(Name), "expected identifier in directive"))
3955 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003956
Jim Grosbach6f482002015-05-18 18:43:14 +00003957 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003958
3959 if (IsPersonality)
3960 getStreamer().EmitCFIPersonality(Sym, Encoding);
3961 else
3962 getStreamer().EmitCFILsda(Sym, Encoding);
3963 return false;
3964}
3965
Jim Grosbach4b905842013-09-20 23:08:21 +00003966/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003967/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003968bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003969 getStreamer().EmitCFIRememberState();
3970 return false;
3971}
3972
Jim Grosbach4b905842013-09-20 23:08:21 +00003973/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003974/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003975bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003976 getStreamer().EmitCFIRestoreState();
3977 return false;
3978}
3979
Jim Grosbach4b905842013-09-20 23:08:21 +00003980/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003981/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003982bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003983 int64_t Register = 0;
3984
Jim Grosbach4b905842013-09-20 23:08:21 +00003985 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003986 return true;
3987
3988 getStreamer().EmitCFISameValue(Register);
3989 return false;
3990}
3991
Jim Grosbach4b905842013-09-20 23:08:21 +00003992/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003993/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003994bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003995 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003996 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003997 return true;
3998
3999 getStreamer().EmitCFIRestore(Register);
4000 return false;
4001}
4002
Jim Grosbach4b905842013-09-20 23:08:21 +00004003/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004004/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004005bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004006 std::string Values;
4007 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004008 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004009 return true;
4010
4011 Values.push_back((uint8_t)CurrValue);
4012
4013 while (getLexer().is(AsmToken::Comma)) {
4014 Lex();
4015
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004016 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004017 return true;
4018
4019 Values.push_back((uint8_t)CurrValue);
4020 }
4021
4022 getStreamer().EmitCFIEscape(Values);
4023 return false;
4024}
4025
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004026/// parseDirectiveCFIReturnColumn
4027/// ::= .cfi_return_column register
4028bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4029 int64_t Register = 0;
4030 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4031 return true;
4032 getStreamer().EmitCFIReturnColumn(Register);
4033 return false;
4034}
4035
Jim Grosbach4b905842013-09-20 23:08:21 +00004036/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004037/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004038bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004039 if (parseToken(AsmToken::EndOfStatement,
4040 "unexpected token in '.cfi_signal_frame'"))
4041 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004042
4043 getStreamer().EmitCFISignalFrame();
4044 return false;
4045}
4046
Jim Grosbach4b905842013-09-20 23:08:21 +00004047/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004048/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004049bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004050 int64_t Register = 0;
4051
Jim Grosbach4b905842013-09-20 23:08:21 +00004052 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004053 return true;
4054
4055 getStreamer().EmitCFIUndefined(Register);
4056 return false;
4057}
4058
Michael Zuckerman56704612017-05-01 13:20:12 +00004059/// parseDirectiveAltmacro
4060/// ::= .altmacro
4061/// ::= .noaltmacro
4062bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4063 if (getLexer().isNot(AsmToken::EndOfStatement))
4064 return TokError("unexpected token in '" + Directive + "' directive");
4065 if (Directive == ".altmacro")
4066 getLexer().SetAltMacroMode(true);
4067 else
4068 getLexer().SetAltMacroMode(false);
4069 return false;
4070}
4071
Jim Grosbach4b905842013-09-20 23:08:21 +00004072/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004073/// ::= .macros_on
4074/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004075bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004076 if (parseToken(AsmToken::EndOfStatement,
4077 "unexpected token in '" + Directive + "' directive"))
4078 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004079
Jim Grosbach4b905842013-09-20 23:08:21 +00004080 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004081 return false;
4082}
4083
Jim Grosbach4b905842013-09-20 23:08:21 +00004084/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004085/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004086bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004087 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004088 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004089 return TokError("expected identifier in '.macro' directive");
4090
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004091 if (getLexer().is(AsmToken::Comma))
4092 Lex();
4093
Eli Bendersky17233942013-01-15 22:59:42 +00004094 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004095 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004096
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004097 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004098 return Error(Lexer.getLoc(),
4099 "Vararg parameter '" + Parameters.back().Name +
4100 "' should be last one in the list of parameters.");
4101
David Majnemer91fc4c22014-01-29 18:57:46 +00004102 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004103 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004104 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004105
Coby Tayreebedaae02017-04-08 20:29:03 +00004106 // Emit an error if two (or more) named parameters share the same name
4107 for (const MCAsmMacroParameter& CurrParam : Parameters)
4108 if (CurrParam.Name.equals(Parameter.Name))
4109 return TokError("macro '" + Name + "' has multiple parameters"
4110 " named '" + Parameter.Name + "'");
4111
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004112 if (Lexer.is(AsmToken::Colon)) {
4113 Lex(); // consume ':'
4114
4115 SMLoc QualLoc;
4116 StringRef Qualifier;
4117
4118 QualLoc = Lexer.getLoc();
4119 if (parseIdentifier(Qualifier))
4120 return Error(QualLoc, "missing parameter qualifier for "
4121 "'" + Parameter.Name + "' in macro '" + Name + "'");
4122
4123 if (Qualifier == "req")
4124 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004125 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004126 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004127 else
4128 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4129 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4130 }
4131
David Majnemer91fc4c22014-01-29 18:57:46 +00004132 if (getLexer().is(AsmToken::Equal)) {
4133 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004134
4135 SMLoc ParamLoc;
4136
4137 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004138 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004139 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004140
4141 if (Parameter.Required)
4142 Warning(ParamLoc, "pointless default value for required parameter "
4143 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004144 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004145
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004146 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004147
4148 if (getLexer().is(AsmToken::Comma))
4149 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004150 }
4151
Nirav Dave1180e6892016-06-02 17:15:05 +00004152 // Eat just the end of statement.
4153 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004154
Nirav Dave1180e6892016-06-02 17:15:05 +00004155 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004156 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004157 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004158 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004159 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004160 // Ignore Lexing errors in macros.
4161 while (Lexer.is(AsmToken::Error)) {
4162 Lexer.Lex();
4163 }
4164
Eli Bendersky17233942013-01-15 22:59:42 +00004165 // Check whether we have reached the end of the file.
4166 if (getLexer().is(AsmToken::Eof))
4167 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4168
4169 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004170 if (getLexer().is(AsmToken::Identifier)) {
4171 if (getTok().getIdentifier() == ".endm" ||
4172 getTok().getIdentifier() == ".endmacro") {
4173 if (MacroDepth == 0) { // Outermost macro.
4174 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004175 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004176 if (getLexer().isNot(AsmToken::EndOfStatement))
4177 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4178 "' directive");
4179 break;
4180 } else {
4181 // Otherwise we just found the end of an inner macro.
4182 --MacroDepth;
4183 }
4184 } else if (getTok().getIdentifier() == ".macro") {
4185 // We allow nested macros. Those aren't instantiated until the outermost
4186 // macro is expanded so just ignore them for now.
4187 ++MacroDepth;
4188 }
Eli Bendersky17233942013-01-15 22:59:42 +00004189 }
4190
4191 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004192 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004193 }
4194
Jim Grosbach4b905842013-09-20 23:08:21 +00004195 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004196 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4197 }
4198
4199 const char *BodyStart = StartToken.getLoc().getPointer();
4200 const char *BodyEnd = EndToken.getLoc().getPointer();
4201 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004202 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004203 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00004204 return false;
4205}
4206
Jim Grosbach4b905842013-09-20 23:08:21 +00004207/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004208///
4209/// With the support added for named parameters there may be code out there that
4210/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004211/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004212/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004213/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004214/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4215/// warning that the positional parameter found in body which have no effect.
4216/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004217/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004218/// intended or change the macro to use the named parameters. It is possible
4219/// this warning will trigger when the none of the named parameters are used
4220/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004221void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004222 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004223 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004224 // If this macro is not defined with named parameters the warning we are
4225 // checking for here doesn't apply.
4226 unsigned NParameters = Parameters.size();
4227 if (NParameters == 0)
4228 return;
4229
4230 bool NamedParametersFound = false;
4231 bool PositionalParametersFound = false;
4232
4233 // Look at the body of the macro for use of both the named parameters and what
4234 // are likely to be positional parameters. This is what expandMacro() is
4235 // doing when it finds the parameters in the body.
4236 while (!Body.empty()) {
4237 // Scan for the next possible parameter.
4238 std::size_t End = Body.size(), Pos = 0;
4239 for (; Pos != End; ++Pos) {
4240 // Check for a substitution or escape.
4241 // This macro is defined with parameters, look for \foo, \bar, etc.
4242 if (Body[Pos] == '\\' && Pos + 1 != End)
4243 break;
4244
4245 // This macro should have parameters, but look for $0, $1, ..., $n too.
4246 if (Body[Pos] != '$' || Pos + 1 == End)
4247 continue;
4248 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004249 if (Next == '$' || Next == 'n' ||
4250 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004251 break;
4252 }
4253
4254 // Check if we reached the end.
4255 if (Pos == End)
4256 break;
4257
4258 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004259 switch (Body[Pos + 1]) {
4260 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004261 case '$':
4262 break;
4263
Jim Grosbach4b905842013-09-20 23:08:21 +00004264 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004265 case 'n':
4266 PositionalParametersFound = true;
4267 break;
4268
Jim Grosbach4b905842013-09-20 23:08:21 +00004269 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004270 default: {
4271 PositionalParametersFound = true;
4272 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004273 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004274 }
4275 Pos += 2;
4276 } else {
4277 unsigned I = Pos + 1;
4278 while (isIdentifierChar(Body[I]) && I + 1 != End)
4279 ++I;
4280
Jim Grosbach4b905842013-09-20 23:08:21 +00004281 const char *Begin = Body.data() + Pos + 1;
4282 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004283 unsigned Index = 0;
4284 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004285 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004286 break;
4287
4288 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004289 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4290 Pos += 3;
4291 else {
4292 Pos = I;
4293 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004294 } else {
4295 NamedParametersFound = true;
4296 Pos += 1 + Argument.size();
4297 }
4298 }
4299 // Update the scan point.
4300 Body = Body.substr(Pos);
4301 }
4302
4303 if (!NamedParametersFound && PositionalParametersFound)
4304 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4305 "used in macro body, possible positional parameter "
4306 "found in body which will have no effect");
4307}
4308
Nico Weber155dccd12014-07-24 17:08:39 +00004309/// parseDirectiveExitMacro
4310/// ::= .exitm
4311bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004312 if (parseToken(AsmToken::EndOfStatement,
4313 "unexpected token in '" + Directive + "' directive"))
4314 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004315
4316 if (!isInsideMacroInstantiation())
4317 return TokError("unexpected '" + Directive + "' in file, "
4318 "no current macro definition");
4319
4320 // Exit all conditionals that are active in the current macro.
4321 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4322 TheCondState = TheCondStack.back();
4323 TheCondStack.pop_back();
4324 }
4325
4326 handleMacroExit();
4327 return false;
4328}
4329
Jim Grosbach4b905842013-09-20 23:08:21 +00004330/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004331/// ::= .endm
4332/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004333bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004334 if (getLexer().isNot(AsmToken::EndOfStatement))
4335 return TokError("unexpected token in '" + Directive + "' directive");
4336
4337 // If we are inside a macro instantiation, terminate the current
4338 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004339 if (isInsideMacroInstantiation()) {
4340 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004341 return false;
4342 }
4343
4344 // Otherwise, this .endmacro is a stray entry in the file; well formed
4345 // .endmacro directives are handled during the macro definition parsing.
4346 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004347 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004348}
4349
Jim Grosbach4b905842013-09-20 23:08:21 +00004350/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004351/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004352bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004353 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004354 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004355 if (parseTokenLoc(Loc) ||
4356 check(parseIdentifier(Name), Loc,
4357 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004358 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004359 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004360 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004361
Nirav Dave1ab71992016-07-18 19:35:21 +00004362 if (!lookupMacro(Name))
4363 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4364
Jim Grosbach4b905842013-09-20 23:08:21 +00004365 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004366 return false;
4367}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004368
Jim Grosbach4b905842013-09-20 23:08:21 +00004369/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004370/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004371bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004372 // Expect a single argument: an expression that evaluates to a constant
4373 // in the inclusive range 0-30.
4374 SMLoc ExprLoc = getLexer().getLoc();
4375 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004376 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004377 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4378 "in '.bundle_align_mode' "
4379 "directive") ||
4380 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4381 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004382 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004383
4384 // Because of AlignSizePow2's verified range we can safely truncate it to
4385 // unsigned.
4386 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4387 return false;
4388}
4389
Jim Grosbach4b905842013-09-20 23:08:21 +00004390/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004391/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004392bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004393 if (checkForValidSection())
4394 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004395 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004396
Nirav Dave1a9044b2016-10-24 14:35:29 +00004397 StringRef Option;
4398 SMLoc Loc = getTok().getLoc();
4399 const char *kInvalidOptionError =
4400 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004401
Nirav Dave1a9044b2016-10-24 14:35:29 +00004402 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004403 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4404 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004405 parseToken(AsmToken::EndOfStatement,
4406 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004407 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004408 AlignToEnd = true;
4409 }
4410
Eli Bendersky802b6282013-01-07 21:51:08 +00004411 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004412 return false;
4413}
4414
Jim Grosbach4b905842013-09-20 23:08:21 +00004415/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004416/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004417bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004418 if (checkForValidSection() ||
4419 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004420 "unexpected token in '.bundle_unlock' directive"))
4421 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004422
4423 getStreamer().EmitBundleUnlock();
4424 return false;
4425}
4426
Jim Grosbach4b905842013-09-20 23:08:21 +00004427/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004428/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004429bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004430 SMLoc NumBytesLoc = Lexer.getLoc();
4431 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004432 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004433 return true;
4434
4435 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004436 if (parseOptionalToken(AsmToken::Comma))
4437 if (parseAbsoluteExpression(FillExpr))
4438 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4439 if (parseToken(AsmToken::EndOfStatement))
4440 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004441
Eli Bendersky17233942013-01-15 22:59:42 +00004442 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004443 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004444
4445 return false;
4446}
4447
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004448/// parseDirectiveDCB
4449/// ::= .dcb.{b, l, w} expression, expression
4450bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004451 SMLoc NumValuesLoc = Lexer.getLoc();
4452 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004453 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004454 return true;
4455
4456 if (NumValues < 0) {
4457 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4458 return false;
4459 }
4460
4461 if (parseToken(AsmToken::Comma,
4462 "unexpected token in '" + Twine(IDVal) + "' directive"))
4463 return true;
4464
4465 const MCExpr *Value;
4466 SMLoc ExprLoc = getLexer().getLoc();
4467 if (parseExpression(Value))
4468 return true;
4469
4470 // Special case constant expressions to match code generator.
4471 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4472 assert(Size <= 8 && "Invalid size");
4473 uint64_t IntValue = MCE->getValue();
4474 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4475 return Error(ExprLoc, "literal value out of range for directive");
4476 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4477 getStreamer().EmitIntValue(IntValue, Size);
4478 } else {
4479 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4480 getStreamer().EmitValue(Value, Size, ExprLoc);
4481 }
4482
4483 if (parseToken(AsmToken::EndOfStatement,
4484 "unexpected token in '" + Twine(IDVal) + "' directive"))
4485 return true;
4486
4487 return false;
4488}
4489
4490/// parseDirectiveRealDCB
4491/// ::= .dcb.{d, s} expression, expression
4492bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004493 SMLoc NumValuesLoc = Lexer.getLoc();
4494 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004495 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004496 return true;
4497
4498 if (NumValues < 0) {
4499 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4500 return false;
4501 }
4502
4503 if (parseToken(AsmToken::Comma,
4504 "unexpected token in '" + Twine(IDVal) + "' directive"))
4505 return true;
4506
4507 APInt AsInt;
4508 if (parseRealValue(Semantics, AsInt))
4509 return true;
4510
4511 if (parseToken(AsmToken::EndOfStatement,
4512 "unexpected token in '" + Twine(IDVal) + "' directive"))
4513 return true;
4514
4515 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4516 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4517 AsInt.getBitWidth() / 8);
4518
4519 return false;
4520}
4521
Petr Hosek85b2f672016-09-23 21:53:36 +00004522/// parseDirectiveDS
4523/// ::= .ds.{b, d, l, p, s, w, x} expression
4524bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004525 SMLoc NumValuesLoc = Lexer.getLoc();
4526 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004527 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004528 return true;
4529
4530 if (NumValues < 0) {
4531 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4532 return false;
4533 }
4534
4535 if (parseToken(AsmToken::EndOfStatement,
4536 "unexpected token in '" + Twine(IDVal) + "' directive"))
4537 return true;
4538
4539 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4540 getStreamer().emitFill(Size, 0);
4541
4542 return false;
4543}
4544
Jim Grosbach4b905842013-09-20 23:08:21 +00004545/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004546/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004547bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004548 if (checkForValidSection())
4549 return true;
4550
Nirav Dave1a9044b2016-10-24 14:35:29 +00004551 auto parseOp = [&]() -> bool {
4552 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004553 if (parseExpression(Value))
4554 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004555 if (Signed)
4556 getStreamer().EmitSLEB128Value(Value);
4557 else
4558 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004559 return false;
4560 };
Eli Bendersky17233942013-01-15 22:59:42 +00004561
Nirav Dave1a9044b2016-10-24 14:35:29 +00004562 if (parseMany(parseOp))
4563 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004564
4565 return false;
4566}
4567
Jim Grosbach4b905842013-09-20 23:08:21 +00004568/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004569/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004570bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004571 auto parseOp = [&]() -> bool {
4572 StringRef Name;
4573 SMLoc Loc = getTok().getLoc();
4574 if (parseIdentifier(Name))
4575 return Error(Loc, "expected identifier");
4576 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004577
Nirav Dave1a9044b2016-10-24 14:35:29 +00004578 // Assembler local symbols don't make any sense here. Complain loudly.
4579 if (Sym->isTemporary())
4580 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004581
Nirav Dave1a9044b2016-10-24 14:35:29 +00004582 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4583 return Error(Loc, "unable to emit symbol attribute");
4584 return false;
4585 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004586
Nirav Dave1a9044b2016-10-24 14:35:29 +00004587 if (parseMany(parseOp))
4588 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004589 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004590}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004591
Jim Grosbach4b905842013-09-20 23:08:21 +00004592/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004593/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004594bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004595 if (checkForValidSection())
4596 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004597
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004598 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004599 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004600 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004601 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004602
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004603 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004604 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004605
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004606 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004607 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004608 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004609
4610 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004611 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004612 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004613 return true;
4614
4615 int64_t Pow2Alignment = 0;
4616 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004617 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004618 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004619 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004620 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004621 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004622
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004623 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4624 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004625 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4626
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004627 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004628 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4629 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004630 if (!isPowerOf2_64(Pow2Alignment))
4631 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4632 Pow2Alignment = Log2_64(Pow2Alignment);
4633 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004634 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004635
Nirav Dave1a9044b2016-10-24 14:35:29 +00004636 if (parseToken(AsmToken::EndOfStatement,
4637 "unexpected token in '.comm' or '.lcomm' directive"))
4638 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004639
Chris Lattner28ad7542009-07-09 17:25:12 +00004640 // NOTE: a size of zero for a .comm should create a undefined symbol
4641 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004642 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004643 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004644 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004645
Eric Christopherbc818852010-05-14 01:38:54 +00004646 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004647 // may internally end up wanting an alignment in bytes.
4648 // FIXME: Diagnose overflow.
4649 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004650 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004651 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004652
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004653 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004654 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004655 return Error(IDLoc, "invalid symbol redefinition");
4656
Chris Lattner28ad7542009-07-09 17:25:12 +00004657 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004658 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004659 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004660 return false;
4661 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004662
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004663 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004664 return false;
4665}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004666
Jim Grosbach4b905842013-09-20 23:08:21 +00004667/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004668/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004669bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004670 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004671 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004672
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004673 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004674 if (parseToken(AsmToken::EndOfStatement,
4675 "unexpected token in '.abort' directive"))
4676 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004677
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004678 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004679 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004680 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004681 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004682 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004683
4684 return false;
4685}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004686
Jim Grosbach4b905842013-09-20 23:08:21 +00004687/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004688/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004689bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004690 // Allow the strings to have escaped octal character sequence.
4691 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004692 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004693
Nirav Davea645433c2016-07-18 15:24:03 +00004694 if (check(getTok().isNot(AsmToken::String),
4695 "expected string in '.include' directive") ||
4696 parseEscapedString(Filename) ||
4697 check(getTok().isNot(AsmToken::EndOfStatement),
4698 "unexpected token in '.include' directive") ||
4699 // Attempt to switch the lexer to the included file before consuming the
4700 // end of statement to avoid losing it when we switch.
4701 check(enterIncludeFile(Filename), IncludeLoc,
4702 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004703 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004704
4705 return false;
4706}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004707
Jim Grosbach4b905842013-09-20 23:08:21 +00004708/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004709/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004710bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004711 // Allow the strings to have escaped octal character sequence.
4712 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004713 SMLoc IncbinLoc = getTok().getLoc();
4714 if (check(getTok().isNot(AsmToken::String),
4715 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004716 parseEscapedString(Filename))
4717 return true;
4718
4719 int64_t Skip = 0;
4720 const MCExpr *Count = nullptr;
4721 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004722 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004723 // The skip expression can be omitted while specifying the count, e.g:
4724 // .incbin "filename",,4
4725 if (getTok().isNot(AsmToken::Comma)) {
4726 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4727 return true;
4728 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004729 if (parseOptionalToken(AsmToken::Comma)) {
4730 CountLoc = getTok().getLoc();
4731 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004732 return true;
4733 }
4734 }
4735
4736 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004737 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004738 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004739
Petr Hosek2f4ac442016-09-23 00:41:06 +00004740 if (check(Skip < 0, SkipLoc, "skip is negative"))
4741 return true;
4742
Nirav Dave1ab71992016-07-18 19:35:21 +00004743 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004744 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004745 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004746 return false;
4747}
4748
Jim Grosbach4b905842013-09-20 23:08:21 +00004749/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004750/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4751bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004752 TheCondStack.push_back(TheCondState);
4753 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004754 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004755 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004756 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004757 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004758 if (parseAbsoluteExpression(ExprValue) ||
4759 parseToken(AsmToken::EndOfStatement,
4760 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004761 return true;
4762
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004763 switch (DirKind) {
4764 default:
4765 llvm_unreachable("unsupported directive");
4766 case DK_IF:
4767 case DK_IFNE:
4768 break;
4769 case DK_IFEQ:
4770 ExprValue = ExprValue == 0;
4771 break;
4772 case DK_IFGE:
4773 ExprValue = ExprValue >= 0;
4774 break;
4775 case DK_IFGT:
4776 ExprValue = ExprValue > 0;
4777 break;
4778 case DK_IFLE:
4779 ExprValue = ExprValue <= 0;
4780 break;
4781 case DK_IFLT:
4782 ExprValue = ExprValue < 0;
4783 break;
4784 }
4785
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004786 TheCondState.CondMet = ExprValue;
4787 TheCondState.Ignore = !TheCondState.CondMet;
4788 }
4789
4790 return false;
4791}
4792
Jim Grosbach4b905842013-09-20 23:08:21 +00004793/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004794/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004795bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004796 TheCondStack.push_back(TheCondState);
4797 TheCondState.TheCond = AsmCond::IfCond;
4798
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004799 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004800 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004801 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004802 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004803
Nirav Davea645433c2016-07-18 15:24:03 +00004804 if (parseToken(AsmToken::EndOfStatement,
4805 "unexpected token in '.ifb' directive"))
4806 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004807
4808 TheCondState.CondMet = ExpectBlank == Str.empty();
4809 TheCondState.Ignore = !TheCondState.CondMet;
4810 }
4811
4812 return false;
4813}
4814
Jim Grosbach4b905842013-09-20 23:08:21 +00004815/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004816/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004817/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004818bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004819 TheCondStack.push_back(TheCondState);
4820 TheCondState.TheCond = AsmCond::IfCond;
4821
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004822 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004823 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004824 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004825 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004826
Nirav Davea645433c2016-07-18 15:24:03 +00004827 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4828 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004829
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004830 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004831
Nirav Davea645433c2016-07-18 15:24:03 +00004832 if (parseToken(AsmToken::EndOfStatement,
4833 "unexpected token in '.ifc' directive"))
4834 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004835
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004836 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004837 TheCondState.Ignore = !TheCondState.CondMet;
4838 }
4839
4840 return false;
4841}
4842
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004843/// parseDirectiveIfeqs
4844/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004845bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004846 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004847 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004848 return TokError("expected string parameter for '.ifeqs' directive");
4849 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004850 }
4851
4852 StringRef String1 = getTok().getStringContents();
4853 Lex();
4854
4855 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004856 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004857 return TokError(
4858 "expected comma after first string for '.ifeqs' directive");
4859 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004860 }
4861
4862 Lex();
4863
4864 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004865 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004866 return TokError("expected string parameter for '.ifeqs' directive");
4867 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004868 }
4869
4870 StringRef String2 = getTok().getStringContents();
4871 Lex();
4872
4873 TheCondStack.push_back(TheCondState);
4874 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004875 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004876 TheCondState.Ignore = !TheCondState.CondMet;
4877
4878 return false;
4879}
4880
Jim Grosbach4b905842013-09-20 23:08:21 +00004881/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004882/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004883bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004884 StringRef Name;
4885 TheCondStack.push_back(TheCondState);
4886 TheCondState.TheCond = AsmCond::IfCond;
4887
4888 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004889 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004890 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004891 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4892 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4893 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004894
Jim Grosbach6f482002015-05-18 18:43:14 +00004895 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004896
4897 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004898 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004899 else
Craig Topper353eda42014-04-24 06:44:33 +00004900 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004901 TheCondState.Ignore = !TheCondState.CondMet;
4902 }
4903
4904 return false;
4905}
4906
Jim Grosbach4b905842013-09-20 23:08:21 +00004907/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004908/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004909bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004910 if (TheCondState.TheCond != AsmCond::IfCond &&
4911 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004912 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4913 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004914 TheCondState.TheCond = AsmCond::ElseIfCond;
4915
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004916 bool LastIgnoreState = false;
4917 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004918 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004919 if (LastIgnoreState || TheCondState.CondMet) {
4920 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004921 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004922 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004923 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004924 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004925 return true;
4926
Nirav Dave1a9044b2016-10-24 14:35:29 +00004927 if (parseToken(AsmToken::EndOfStatement,
4928 "unexpected token in '.elseif' directive"))
4929 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004930
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004931 TheCondState.CondMet = ExprValue;
4932 TheCondState.Ignore = !TheCondState.CondMet;
4933 }
4934
4935 return false;
4936}
4937
Jim Grosbach4b905842013-09-20 23:08:21 +00004938/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004939/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004940bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004941 if (parseToken(AsmToken::EndOfStatement,
4942 "unexpected token in '.else' directive"))
4943 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004944
4945 if (TheCondState.TheCond != AsmCond::IfCond &&
4946 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004947 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4948 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004949 TheCondState.TheCond = AsmCond::ElseCond;
4950 bool LastIgnoreState = false;
4951 if (!TheCondStack.empty())
4952 LastIgnoreState = TheCondStack.back().Ignore;
4953 if (LastIgnoreState || TheCondState.CondMet)
4954 TheCondState.Ignore = true;
4955 else
4956 TheCondState.Ignore = false;
4957
4958 return false;
4959}
4960
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004961/// parseDirectiveEnd
4962/// ::= .end
4963bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004964 if (parseToken(AsmToken::EndOfStatement,
4965 "unexpected token in '.end' directive"))
4966 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004967
4968 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004969 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004970
4971 return false;
4972}
4973
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004974/// parseDirectiveError
4975/// ::= .err
4976/// ::= .error [string]
4977bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4978 if (!TheCondStack.empty()) {
4979 if (TheCondStack.back().Ignore) {
4980 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004981 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004982 }
4983 }
4984
4985 if (!WithMessage)
4986 return Error(L, ".err encountered");
4987
4988 StringRef Message = ".error directive invoked in source file";
4989 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004990 if (Lexer.isNot(AsmToken::String))
4991 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004992
4993 Message = getTok().getStringContents();
4994 Lex();
4995 }
4996
Nirav Dave2364748a2016-09-16 18:30:20 +00004997 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004998}
4999
Nico Weber404012b2014-07-24 16:26:06 +00005000/// parseDirectiveWarning
5001/// ::= .warning [string]
5002bool AsmParser::parseDirectiveWarning(SMLoc L) {
5003 if (!TheCondStack.empty()) {
5004 if (TheCondStack.back().Ignore) {
5005 eatToEndOfStatement();
5006 return false;
5007 }
5008 }
5009
5010 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005011
5012 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005013 if (Lexer.isNot(AsmToken::String))
5014 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005015
5016 Message = getTok().getStringContents();
5017 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005018 if (parseToken(AsmToken::EndOfStatement,
5019 "expected end of statement in '.warning' directive"))
5020 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005021 }
5022
Nirav Dave2364748a2016-09-16 18:30:20 +00005023 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005024}
5025
Jim Grosbach4b905842013-09-20 23:08:21 +00005026/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005027/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005028bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005029 if (parseToken(AsmToken::EndOfStatement,
5030 "unexpected token in '.endif' directive"))
5031 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005032
Jim Grosbach4b905842013-09-20 23:08:21 +00005033 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005034 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5035 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005036 if (!TheCondStack.empty()) {
5037 TheCondState = TheCondStack.back();
5038 TheCondStack.pop_back();
5039 }
5040
5041 return false;
5042}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005043
Eli Bendersky17233942013-01-15 22:59:42 +00005044void AsmParser::initializeDirectiveKindMap() {
5045 DirectiveKindMap[".set"] = DK_SET;
5046 DirectiveKindMap[".equ"] = DK_EQU;
5047 DirectiveKindMap[".equiv"] = DK_EQUIV;
5048 DirectiveKindMap[".ascii"] = DK_ASCII;
5049 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5050 DirectiveKindMap[".string"] = DK_STRING;
5051 DirectiveKindMap[".byte"] = DK_BYTE;
5052 DirectiveKindMap[".short"] = DK_SHORT;
5053 DirectiveKindMap[".value"] = DK_VALUE;
5054 DirectiveKindMap[".2byte"] = DK_2BYTE;
5055 DirectiveKindMap[".long"] = DK_LONG;
5056 DirectiveKindMap[".int"] = DK_INT;
5057 DirectiveKindMap[".4byte"] = DK_4BYTE;
5058 DirectiveKindMap[".quad"] = DK_QUAD;
5059 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005060 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005061 DirectiveKindMap[".single"] = DK_SINGLE;
5062 DirectiveKindMap[".float"] = DK_FLOAT;
5063 DirectiveKindMap[".double"] = DK_DOUBLE;
5064 DirectiveKindMap[".align"] = DK_ALIGN;
5065 DirectiveKindMap[".align32"] = DK_ALIGN32;
5066 DirectiveKindMap[".balign"] = DK_BALIGN;
5067 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5068 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5069 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5070 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5071 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5072 DirectiveKindMap[".org"] = DK_ORG;
5073 DirectiveKindMap[".fill"] = DK_FILL;
5074 DirectiveKindMap[".zero"] = DK_ZERO;
5075 DirectiveKindMap[".extern"] = DK_EXTERN;
5076 DirectiveKindMap[".globl"] = DK_GLOBL;
5077 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005078 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5079 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5080 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5081 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5082 DirectiveKindMap[".reference"] = DK_REFERENCE;
5083 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5084 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5085 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5086 DirectiveKindMap[".comm"] = DK_COMM;
5087 DirectiveKindMap[".common"] = DK_COMMON;
5088 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5089 DirectiveKindMap[".abort"] = DK_ABORT;
5090 DirectiveKindMap[".include"] = DK_INCLUDE;
5091 DirectiveKindMap[".incbin"] = DK_INCBIN;
5092 DirectiveKindMap[".code16"] = DK_CODE16;
5093 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5094 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005095 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005096 DirectiveKindMap[".irp"] = DK_IRP;
5097 DirectiveKindMap[".irpc"] = DK_IRPC;
5098 DirectiveKindMap[".endr"] = DK_ENDR;
5099 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5100 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5101 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5102 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005103 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5104 DirectiveKindMap[".ifge"] = DK_IFGE;
5105 DirectiveKindMap[".ifgt"] = DK_IFGT;
5106 DirectiveKindMap[".ifle"] = DK_IFLE;
5107 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005108 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005109 DirectiveKindMap[".ifb"] = DK_IFB;
5110 DirectiveKindMap[".ifnb"] = DK_IFNB;
5111 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005112 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005113 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005114 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005115 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5116 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5117 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5118 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5119 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005120 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005121 DirectiveKindMap[".endif"] = DK_ENDIF;
5122 DirectiveKindMap[".skip"] = DK_SKIP;
5123 DirectiveKindMap[".space"] = DK_SPACE;
5124 DirectiveKindMap[".file"] = DK_FILE;
5125 DirectiveKindMap[".line"] = DK_LINE;
5126 DirectiveKindMap[".loc"] = DK_LOC;
5127 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005128 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005129 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005130 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5131 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005132 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005133 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005134 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005135 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5136 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00005137 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5138 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5139 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5140 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5141 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5142 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5143 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5144 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5145 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5146 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5147 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5148 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5149 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5150 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5151 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5152 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5153 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5154 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005155 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005156 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5157 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5158 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005159 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005160 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5161 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5162 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005163 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005164 DirectiveKindMap[".endm"] = DK_ENDM;
5165 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5166 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005167 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005168 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005169 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005170 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5171 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005172 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005173 DirectiveKindMap[".dc"] = DK_DC;
5174 DirectiveKindMap[".dc.a"] = DK_DC_A;
5175 DirectiveKindMap[".dc.b"] = DK_DC_B;
5176 DirectiveKindMap[".dc.d"] = DK_DC_D;
5177 DirectiveKindMap[".dc.l"] = DK_DC_L;
5178 DirectiveKindMap[".dc.s"] = DK_DC_S;
5179 DirectiveKindMap[".dc.w"] = DK_DC_W;
5180 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005181 DirectiveKindMap[".dcb"] = DK_DCB;
5182 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5183 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5184 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5185 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5186 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5187 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005188 DirectiveKindMap[".ds"] = DK_DS;
5189 DirectiveKindMap[".ds.b"] = DK_DS_B;
5190 DirectiveKindMap[".ds.d"] = DK_DS_D;
5191 DirectiveKindMap[".ds.l"] = DK_DS_L;
5192 DirectiveKindMap[".ds.p"] = DK_DS_P;
5193 DirectiveKindMap[".ds.s"] = DK_DS_S;
5194 DirectiveKindMap[".ds.w"] = DK_DS_W;
5195 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005196}
5197
Jim Grosbach4b905842013-09-20 23:08:21 +00005198MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005199 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005200
Rafael Espindola34b9c512012-06-03 23:57:14 +00005201 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005202 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005203 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005204 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005205 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005206 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005207 }
5208
Rafael Espindola34b9c512012-06-03 23:57:14 +00005209 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005210 (getTok().getIdentifier() == ".rept" ||
5211 getTok().getIdentifier() == ".irp" ||
5212 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005213 ++NestLevel;
5214 }
5215
5216 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005217 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005218 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005219 EndToken = getTok();
5220 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005221 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005222 printError(getTok().getLoc(),
5223 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005224 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005225 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005226 break;
5227 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005228 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005229 }
5230
Rafael Espindola34b9c512012-06-03 23:57:14 +00005231 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005232 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005233 }
5234
5235 const char *BodyStart = StartToken.getLoc().getPointer();
5236 const char *BodyEnd = EndToken.getLoc().getPointer();
5237 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5238
Rafael Espindola34b9c512012-06-03 23:57:14 +00005239 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005240 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005241 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005242}
5243
Jim Grosbach4b905842013-09-20 23:08:21 +00005244void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005245 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005246 OS << ".endr\n";
5247
Rafael Espindola3560ff22014-08-27 20:03:13 +00005248 std::unique_ptr<MemoryBuffer> Instantiation =
5249 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005250
Rafael Espindola34b9c512012-06-03 23:57:14 +00005251 // Create the macro instantiation object and add to the current macro
5252 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005253 MacroInstantiation *MI = new MacroInstantiation(
5254 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005255 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005256
Rafael Espindola34b9c512012-06-03 23:57:14 +00005257 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005258 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005259 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005260 Lex();
5261}
5262
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005263/// parseDirectiveRept
5264/// ::= .rep | .rept count
5265bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005266 const MCExpr *CountExpr;
5267 SMLoc CountLoc = getTok().getLoc();
5268 if (parseExpression(CountExpr))
5269 return true;
5270
Rafael Espindola34b9c512012-06-03 23:57:14 +00005271 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005272 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005273 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5274 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005275
Nirav Davea645433c2016-07-18 15:24:03 +00005276 if (check(Count < 0, CountLoc, "Count is negative") ||
5277 parseToken(AsmToken::EndOfStatement,
5278 "unexpected token in '" + Dir + "' directive"))
5279 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005280
5281 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005282 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005283 if (!M)
5284 return true;
5285
5286 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5287 // to hold the macro body with substitutions.
5288 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005289 raw_svector_ostream OS(Buf);
5290 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005291 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5292 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005293 return true;
5294 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005295 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005296
5297 return false;
5298}
5299
Jim Grosbach4b905842013-09-20 23:08:21 +00005300/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005301/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005302bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005303 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005304 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005305 if (check(parseIdentifier(Parameter.Name),
5306 "expected identifier in '.irp' directive") ||
5307 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5308 parseMacroArguments(nullptr, A) ||
5309 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005310 return true;
5311
Rafael Espindola768b41c2012-06-15 14:02:34 +00005312 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005313 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005314 if (!M)
5315 return true;
5316
5317 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5318 // to hold the macro body with substitutions.
5319 SmallString<256> Buf;
5320 raw_svector_ostream OS(Buf);
5321
Craig Topper84008482015-10-10 05:38:14 +00005322 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005323 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5324 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005325 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005326 return true;
5327 }
5328
Jim Grosbach4b905842013-09-20 23:08:21 +00005329 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005330
5331 return false;
5332}
5333
Jim Grosbach4b905842013-09-20 23:08:21 +00005334/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005335/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005336bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005337 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005338 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005339
5340 if (check(parseIdentifier(Parameter.Name),
5341 "expected identifier in '.irpc' directive") ||
5342 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5343 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005344 return true;
5345
5346 if (A.size() != 1 || A.front().size() != 1)
5347 return TokError("unexpected token in '.irpc' directive");
5348
5349 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005350 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5351 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005352
5353 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005354 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005355 if (!M)
5356 return true;
5357
5358 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5359 // to hold the macro body with substitutions.
5360 SmallString<256> Buf;
5361 raw_svector_ostream OS(Buf);
5362
5363 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005364 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005365 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005366 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005367
Toma Tabacu217116e2015-04-27 10:50:29 +00005368 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5369 // This is undocumented, but GAS seems to support it.
5370 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005371 return true;
5372 }
5373
Jim Grosbach4b905842013-09-20 23:08:21 +00005374 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005375
5376 return false;
5377}
5378
Jim Grosbach4b905842013-09-20 23:08:21 +00005379bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005380 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005381 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005382
5383 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005384 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005385 assert(getLexer().is(AsmToken::EndOfStatement));
5386
Jim Grosbach4b905842013-09-20 23:08:21 +00005387 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005388 return false;
5389}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005390
Jim Grosbach4b905842013-09-20 23:08:21 +00005391bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005392 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005393 const MCExpr *Value;
5394 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005395 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005396 return true;
5397 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5398 if (!MCE)
5399 return Error(ExprLoc, "unexpected expression in _emit");
5400 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005401 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005402 return Error(ExprLoc, "literal value out of range for directive");
5403
Craig Topper7d5b2312015-10-10 05:25:02 +00005404 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005405 return false;
5406}
5407
Jim Grosbach4b905842013-09-20 23:08:21 +00005408bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005409 const MCExpr *Value;
5410 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005411 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005412 return true;
5413 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5414 if (!MCE)
5415 return Error(ExprLoc, "unexpected expression in align");
5416 uint64_t IntValue = MCE->getValue();
5417 if (!isPowerOf2_64(IntValue))
5418 return Error(ExprLoc, "literal value not a power of two greater then zero");
5419
Craig Topper7d5b2312015-10-10 05:25:02 +00005420 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005421 return false;
5422}
5423
Chad Rosierf43fcf52013-02-13 21:27:17 +00005424// We are comparing pointers, but the pointers are relative to a single string.
5425// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005426static int rewritesSort(const AsmRewrite *AsmRewriteA,
5427 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005428 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5429 return -1;
5430 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5431 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005432
Chad Rosierfce4fab2013-04-08 17:43:47 +00005433 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5434 // rewrite to the same location. Make sure the SizeDirective rewrite is
5435 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5436 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005437 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5438 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005439 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005440
Jim Grosbach4b905842013-09-20 23:08:21 +00005441 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5442 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005443 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005444 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005445}
5446
Jim Grosbach4b905842013-09-20 23:08:21 +00005447bool AsmParser::parseMSInlineAsm(
5448 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005449 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005450 SmallVectorImpl<std::string> &Constraints,
5451 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5452 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005453 SmallVector<void *, 4> InputDecls;
5454 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005455 SmallVector<bool, 4> InputDeclsAddressOf;
5456 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005457 SmallVector<std::string, 4> InputConstraints;
5458 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005459 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005460
Benjamin Kramer1a136112013-02-15 20:37:21 +00005461 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005462
5463 // Prime the lexer.
5464 Lex();
5465
5466 // While we have input, parse each statement.
5467 unsigned InputIdx = 0;
5468 unsigned OutputIdx = 0;
5469 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005470 // Parse curly braces marking block start/end
5471 if (parseCurlyBlockScope(AsmStrRewrites))
5472 continue;
5473
Eli Friedman0f4871d2012-10-22 23:58:19 +00005474 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005475 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005476
Nirav Dave2364748a2016-09-16 18:30:20 +00005477 if (StatementErr || Info.ParseError) {
5478 // Emit pending errors if any exist.
5479 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005480 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005481 }
5482
5483 // No pending error should exist here.
5484 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005485
Benjamin Kramer1a136112013-02-15 20:37:21 +00005486 if (Info.Opcode == ~0U)
5487 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005488
Benjamin Kramer1a136112013-02-15 20:37:21 +00005489 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005490
Benjamin Kramer1a136112013-02-15 20:37:21 +00005491 // Build the list of clobbers, outputs and inputs.
5492 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005493 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005494
Benjamin Kramer1a136112013-02-15 20:37:21 +00005495 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005496 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005497 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005498
Benjamin Kramer1a136112013-02-15 20:37:21 +00005499 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005500 if (Operand.isReg() && !Operand.needAddressOf() &&
5501 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005502 unsigned NumDefs = Desc.getNumDefs();
5503 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005504 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5505 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005506 continue;
5507 }
5508
5509 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005510 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005511 if (SymName.empty())
5512 continue;
5513
David Blaikie960ea3f2014-06-08 16:18:35 +00005514 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005515 if (!OpDecl)
5516 continue;
5517
5518 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005519 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005520 if (isOutput) {
5521 ++InputIdx;
5522 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005523 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005524 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005525 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005526 } else {
5527 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005528 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5529 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005530 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005531 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005532 }
Reid Kleckneree088972013-12-10 18:27:32 +00005533
5534 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005535 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5536 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005537 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005538 }
5539
5540 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005541 NumOutputs = OutputDecls.size();
5542 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005543
5544 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005545 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5546 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5547 ClobberRegs.end());
5548 Clobbers.assign(ClobberRegs.size(), std::string());
5549 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5550 raw_string_ostream OS(Clobbers[I]);
5551 IP->printRegName(OS, ClobberRegs[I]);
5552 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005553
5554 // Merge the various outputs and inputs. Output are expected first.
5555 if (NumOutputs || NumInputs) {
5556 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005557 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005558 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005559 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005560 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005561 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005562 }
5563 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005564 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005565 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005566 }
5567 }
5568
5569 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005570 std::string AsmStringIR;
5571 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005572 StringRef ASMString =
5573 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5574 const char *AsmStart = ASMString.begin();
5575 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005576 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005577 for (const AsmRewrite &AR : AsmStrRewrites) {
5578 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005579 if (Kind == AOK_Delete)
5580 continue;
5581
David Majnemer8114c1a2014-06-23 02:17:16 +00005582 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005583 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005584
Chad Rosier120eefd2013-03-19 17:32:17 +00005585 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005586 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005587 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005588
Chad Rosier37e755c2012-10-23 17:43:43 +00005589 // Skip the original expression.
5590 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005591 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005592 continue;
5593 }
5594
Chad Rosierff10ed12013-04-12 16:26:42 +00005595 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005596 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005597 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005598 default:
5599 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005600 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005601 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005602 break;
5603 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005604 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005605 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005606 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005607 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005608 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005609 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005610 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005611 break;
5612 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005613 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005614 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005615 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005616 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005617 default: break;
5618 case 8: OS << "byte ptr "; break;
5619 case 16: OS << "word ptr "; break;
5620 case 32: OS << "dword ptr "; break;
5621 case 64: OS << "qword ptr "; break;
5622 case 80: OS << "xword ptr "; break;
5623 case 128: OS << "xmmword ptr "; break;
5624 case 256: OS << "ymmword ptr "; break;
5625 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005626 break;
5627 case AOK_Emit:
5628 OS << ".byte";
5629 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005630 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005631 // MS alignment directives are measured in bytes. If the native assembler
5632 // measures alignment in bytes, we can pass it straight through.
5633 OS << ".align";
5634 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5635 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005636
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005637 // Alignment is in log2 form, so print that instead and skip the original
5638 // immediate.
5639 unsigned Val = AR.Val;
5640 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005641 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005642 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5643 break;
5644 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005645 case AOK_EVEN:
5646 OS << ".even";
5647 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005648 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005649 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005650 OS.flush();
5651 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005652 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005653 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005654 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005655 case AOK_EndOfStatement:
5656 OS << "\n\t";
5657 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005658 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005659
Chad Rosier8bce6642012-10-18 15:49:34 +00005660 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005661 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005662 }
5663
5664 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005665 if (AsmStart != AsmEnd)
5666 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005667
5668 AsmString = OS.str();
5669 return false;
5670}
5671
Pete Cooper80d21cb2015-06-22 19:35:57 +00005672namespace llvm {
5673namespace MCParserUtils {
5674
5675/// Returns whether the given symbol is used anywhere in the given expression,
5676/// or subexpressions.
5677static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5678 switch (Value->getKind()) {
5679 case MCExpr::Binary: {
5680 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5681 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5682 isSymbolUsedInExpression(Sym, BE->getRHS());
5683 }
5684 case MCExpr::Target:
5685 case MCExpr::Constant:
5686 return false;
5687 case MCExpr::SymbolRef: {
5688 const MCSymbol &S =
5689 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5690 if (S.isVariable())
5691 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5692 return &S == Sym;
5693 }
5694 case MCExpr::Unary:
5695 return isSymbolUsedInExpression(
5696 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5697 }
5698
5699 llvm_unreachable("Unknown expr kind!");
5700}
5701
5702bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5703 MCAsmParser &Parser, MCSymbol *&Sym,
5704 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005705
5706 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005707 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005708
5709 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005710 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005711 }
5712
5713 // Note: we don't count b as used in "a = b". This is to allow
5714 // a = b
5715 // b = c
5716
Nirav Dave1a9044b2016-10-24 14:35:29 +00005717 if (Parser.parseToken(AsmToken::EndOfStatement))
5718 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005719
5720 // Validate that the LHS is allowed to be a variable (either it has not been
5721 // used as a symbol, or it is an absolute symbol).
5722 Sym = Parser.getContext().lookupSymbol(Name);
5723 if (Sym) {
5724 // Diagnose assignment to a label.
5725 //
5726 // FIXME: Diagnostics. Note the location of the definition as a label.
5727 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5728 if (isSymbolUsedInExpression(Sym, Value))
5729 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005730 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5731 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005732 ; // Allow redefinitions of undefined symbols only used in directives.
5733 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5734 ; // Allow redefinitions of variables that haven't yet been used.
5735 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5736 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5737 else if (!Sym->isVariable())
5738 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5739 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5740 return Parser.Error(EqualLoc,
5741 "invalid reassignment of non-absolute variable '" +
5742 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005743 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005744 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005745 return false;
5746 } else
5747 Sym = Parser.getContext().getOrCreateSymbol(Name);
5748
5749 Sym->setRedefinable(allow_redef);
5750
5751 return false;
5752}
5753
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005754} // end namespace MCParserUtils
5755} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005756
Daniel Dunbar01e36072010-07-17 02:26:10 +00005757/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005758MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005759 MCStreamer &Out, const MCAsmInfo &MAI,
5760 unsigned CB) {
5761 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005762}